Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Audio effects in Mod Settings, JamesDSP's switch and a card per effect with its sliders, curve or file library
Vojtěch Škopeke41002b1aec1
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex c6d1d118..27990c65 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -218,7 +218,10 @@ header, slider and sticky header flags, the cards under the player and the lyricbuttons to hide); in the redesign instead Now playing (its device button), Vibrations, Controls (on until switched off) and Music Haptics(off until switched on, with an ⓘ saying it follows the sound this iPhone plays while Spotify is open), bothapplying straight away. Live Activity, in the redesign only: its switch and which view it shows, Lyrics, Queue or Control menu, both-applying straight away, the row reading out the view or Off. Home & Library, in the native look only:+applying straight away, the row reading out the view or Off. Audio effects, in either look (Shared/JamesDSP/JamesDSPPage.m):+JamesDSP's switch with what the engine is doing under it, then a card per effect in RootlessJamesDSP's order, each+opening out into its sliders, choices, curve or file library while its switch is on, everything applying as it+changes; the row reads out Off, On or how many effects are on. Home & Library, in the native look only:the Gradient page (the wash behind the top of Home in one of eight colours, at three strengths andfour heights) and the Home flags, the parts of Home to hide including the DJ button and badge, theplaylist header, buttons and pills to hide, and the Library flags. Then Premium, ads & privacydiff --git a/harness/jamesdsp-page/README.md b/harness/jamesdsp-page/README.mdnew file mode 100644index 00000000..6dd87896--- /dev/null+++ b/harness/jamesdsp-page/README.md@@ -0,0 +1,31 @@+# Audio effects page harness++Mod Settings > Audio effects (`tweak/Sources/Shared/JamesDSP/`) in a navigation controller, the way Mod+Settings pushes it: the real page, curve and file pages, the real `Settings/` framework and+`JamesDSPSettings.m`, with `stubs.m` standing in for the engine (a made-up status that changes every three+seconds, fake libraries in the app's temporary directory, a smooth curve through the gains instead of the+filter's response, and an error for any chosen file with "broken" in its name).++ THEOS=$HOME/theos ./build.sh+ xcrun simctl install <udid> build/JamesDSPHarness.app+ xcrun simctl launch <udid> com.vojta.jamesdspharness master allon section=4 drag=9:7.5+ xcrun simctl io <udid> screenshot shot.png++Other agents use the simulator too: make a device of your own (`xcrun simctl create`) and address it by+UDID. Every launch clears the `spotifyglass.dsp` keys first unless `keep` is on the line; `main.m` lists the+setup words (`master`, `allon`, `broken`, `slow`) and the actions, played one every 0.7 s from 1 s in:+scrolling to a card, flipping a card's switch, a band mid-drag and let go, a preset, a tap on a row, the+file and GraphicEQ pages, an import through the document picker's delegate, Paste, a slider moved, VoiceOver's+swipe on a slider or a band, the reset's alert confirmed, and `dump`, which logs the stored keys:++ xcrun simctl spawn <udid> log show --last 1m --predicate 'process == "JamesDSPHarness"' | grep '\[harness\]'++2026-09-18, iPhone 17 Pro (402pt) and iPhone 13 mini (375pt) on iOS 26.5: every card laid out with all+effects on, the fifteen band labels apart at 375pt, a preset morphing the curve with the handles (`slow`),+long choice names moving under the title, the animated opening of a card and an error row turning up on+the once a second tick; the values stored under the right keys, snapped to their steps.++What it does not cover: a real finger. The drag is played through the curve's own methods, so whether its+pan wins over the table's scroll when a finger starts on a handle (and loses anywhere else) is untested+here; `hit` logs which band a finger going down at and around each handle would take. Nor the document+picker's own UI, the pull-down menu of presets open, or Spotify's fonts, which the page adopts on the phone.diff --git a/harness/jamesdsp-page/build.sh b/harness/jamesdsp-page/build.shnew file mode 100755index 00000000..5d0c933d--- /dev/null+++ b/harness/jamesdsp-page/build.sh@@ -0,0 +1,36 @@+#!/bin/sh+# Builds the Audio effects page harness for the simulator: Shared/JamesDSP's page, the Settings/ framework+# and JamesDSPSettings.m as they are in the tweak, stubs.m for the engine.+set -e+SRC=$(cd "$(dirname "$0")/../../tweak/Sources" && pwd)+OUT=$(dirname "$0")/build+rm -rf "$OUT"; mkdir -p "$OUT/JamesDSPHarness.app"++SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O0 \+ -I"$SRC" -I"$SRC/Shared/JamesDSP" -isysroot "$SDK" -Wall -Wno-deprecated-declarations \+ "$(dirname "$0")/main.m" "$(dirname "$0")/stubs.m" \+ "$SRC"/Shared/JamesDSP/JamesDSPSettings.m "$SRC"/Shared/JamesDSP/JamesDSPPage.m \+ "$SRC"/Shared/JamesDSP/SGDSPCurveView.m "$SRC"/Shared/JamesDSP/JamesDSPLibraryPage.m \+ "$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework UniformTypeIdentifiers -framework Foundation \+ -o "$OUT/JamesDSPHarness.app/JamesDSPHarness"++cat > "$OUT/JamesDSPHarness.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>JamesDSPHarness</string>+<key>CFBundleIdentifier</key><string>com.vojta.jamesdspharness</string>+<key>CFBundleName</key><string>JamesDSPHarness</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/>+</dict>+</dict></plist>+PLIST+echo "built $OUT/JamesDSPHarness.app"diff --git a/harness/jamesdsp-page/main.m b/harness/jamesdsp-page/main.mnew file mode 100644index 00000000..246fd9f2--- /dev/null+++ b/harness/jamesdsp-page/main.m@@ -0,0 +1,247 @@+// The Audio effects page (Shared/JamesDSP) in a navigation controller, the way Mod Settings pushes it, with+// the real Settings/ framework and JamesDSPSettings.m behind it and stubs.m standing in for the engine.+// The launch line sets the page up and then plays actions, one every 0.7 s from 1 s in; screenshot after.+//+// THEOS=$HOME/theos ./build.sh && xcrun simctl install <udid> build/JamesDSPHarness.app+// xcrun simctl launch <udid> com.vojta.jamesdspharness [setup...] [action...]+//+// Setup: keep (the stored settings stay; otherwise every spotifyglass.dsp key is cleared first), master+// (JamesDSP on), allon (every effect on), broken (Liveprog's script is one that does not compile), slow+// (animations at a twentieth of their speed).+// Actions: scroll=<y>, section=<n> (that card at the top), toggle=<n> (flips card n's switch the way a tap+// does), drag=<band>:<gain> (the equalizer's band mid-drag, the bubble up), release (lets it go),+// preset=<i>, reset=eq, select=<section>.<row> (a tap on a row of the page on top), push=convolver|ddc|+// liveprog|geq, import=<name> (a file of that name picked in the document picker), paste=<text> (the+// GraphicEQ editor's Paste with that on the clipboard), slide=<section>.<row>:<value> (a slider dragged+// there), swipe=<section>.<row>:<n> and band=<band>:<n> (VoiceOver's swipe on a slider or an equalizer band,+// n times), string=<key after spotifyglass.dsp.>:<text> (stored behind the page's back, as the engine's+// errors turn up), pop, delete=<row> (the library's swipe to delete on that file), hit (which band a finger+// takes around each handle, to the log), confirm (the alert's destructive button), dump (the stored dsp keys and the first sections' frames to the log).+#import <UIKit/UIKit.h>+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>+#import "Shared/JamesDSP/JamesDSP.h"+#import "Shared/JamesDSP/JamesDSPPage.h"+#import "Shared/JamesDSP/SGDSPCurveView.h"+#import "Settings/SGModPage.h"++@interface SGDSPCurveView (Harness)+- (void)setBand:(NSInteger)band to:(double)value;+- (void)showBubbleFor:(NSInteger)band;+- (void)highlight:(NSInteger)band on:(BOOL)on;+- (void)refreshBar;+- (void)setGains:(NSArray<NSNumber *> *)gains animated:(BOOL)animated;+- (void)resetTapped;+- (NSInteger)bandAt:(CGPoint)point;+- (CGFloat)xFor:(double)hz;+- (CGFloat)yFor:(double)value;+@end++static NSArray<NSString *> *effectKeys(void) {+ return @[SGKeyDSPCompander, SGKeyDSPBass, SGKeyDSPEqualizer, SGKeyDSPGraphicEq, SGKeyDSPConvolver, SGKeyDSPDDC,+ SGKeyDSPLiveprog, SGKeyDSPReverb, SGKeyDSPStereoWide, SGKeyDSPCrossfeed, SGKeyDSPTube];+}++static void findViews(UIView *root, Class kind, NSMutableArray *found) {+ if ([root isKindOfClass:kind]) [found addObject:root];+ for (UIView *sub in root.subviews) findViews(sub, kind, found);+}++@interface AppDelegate : UIResponder <UIApplicationDelegate>+@property (nonatomic, strong) UIWindow *window;+@property (nonatomic, strong) UINavigationController *nav;+@property (nonatomic) NSInteger draggedBand;+@end++@implementation AppDelegate++- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {+ NSArray<NSString *> *args = NSProcessInfo.processInfo.arguments;+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ if (![args containsObject:@"keep"]) {+ for (NSString *key in store.dictionaryRepresentation.allKeys) {+ if ([key hasPrefix:@"spotifyglass.dsp"]) [store removeObjectForKey:key];+ }+ }+ if ([args containsObject:@"master"]) SGDSPSetSwitch(SGKeyDSP, YES);+ if ([args containsObject:@"allon"]) for (NSString *key in effectKeys()) SGDSPSetSwitch(key, YES);+ if ([args containsObject:@"broken"]) SGDSPSetString(SGKeyDSPLiveprogFile, @"Tape saturation broken.eel");++ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];+ self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ self.nav = [[UINavigationController alloc] initWithRootViewController:SGDSPSettingsPage()];+ self.window.rootViewController = self.nav;+ [self.window makeKeyAndVisible];+ // Animations at a twentieth of their speed, to be caught halfway in a screenshot.+ if ([args containsObject:@"slow"]) self.window.layer.speed = 0.05;+ self.draggedBand = -1;++ NSMutableArray<NSString *> *actions = [NSMutableArray array];+ for (NSString *arg in [args subarrayWithRange:NSMakeRange(1, args.count - 1)]) {+ if (![@[@"keep", @"master", @"allon", @"broken", @"slow"] containsObject:arg]) [actions addObject:arg];+ }+ [actions enumerateObjectsUsingBlock:^(NSString *action, NSUInteger i, BOOL *stop) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((1 + 0.7 * i) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ NSLog(@"[harness] %@", action);+ [self run:action];+ });+ }];+ return YES;+}++- (UITableView *)table {+ return ((UITableViewController *)self.nav.topViewController).tableView;+}++- (SGDSPCurveView *)curve {+ NSMutableArray<SGDSPCurveView *> *curves = [NSMutableArray array];+ findViews(self.table, SGDSPCurveView.class, curves);+ // The equalizer's has the presets, so it has the one more button.+ for (SGDSPCurveView *curve in curves) {+ NSMutableArray *buttons = [NSMutableArray array];+ findViews(curve, UIButton.class, buttons);+ if (buttons.count == 2) return curve;+ }+ return curves.firstObject;+}++// An SGModPage laid out like the Player page, to hold the Audio effects page up against.+- (UIViewController *)referencePage {+ SGModRow *blocked = SGPageRow(@"Blocked artists", ^UIViewController *{ return nil; });+ blocked.value = ^NSString *{ return @"Off"; };+ return [[SGModPage alloc] initWithTitle:@"Player" intro:@"Changes apply after you restart Spotify. Gestures and Blocked artists apply straight away." sections:@[+ SGSection(nil, @[SGWithSymbol(SGPageRow(@"Gestures", ^UIViewController *{ return nil; }), @"hand.tap"), SGWithSymbol(blocked, @"person.crop.circle.badge.xmark")]),+ SGSection(@"Vibrations", @[SGWithSymbol(SGSwitchRow(@"Controls", @"Play, pause, skipping, scrubbing, shuffle, repeat and adding a song", @"spotifyglass.x"), @"hand.tap"),+ SGWithSymbol(SGOptionRow(@"Music Haptics", @"Taps and rumbles along with the music", @"spotifyglass.y"), @"waveform")]),+ SGSection(nil, @[SGChoiceRow(@"Shows", nil, @"spotifyglass.z", @[@"Lyrics", @"Queue"], 0)]),+ ] footer:nil];+}++- (void)run:(NSString *)action {+ NSArray<NSString *> *parts = [action componentsSeparatedByString:@"="];+ NSString *verb = parts.firstObject, *value = parts.count > 1 ? parts[1] : @"";+ UITableView *table = self.table;+ if ([verb isEqualToString:@"scroll"]) {+ CGFloat max = MAX(-table.adjustedContentInset.top, table.contentSize.height - table.bounds.size.height + table.adjustedContentInset.bottom);+ [table setContentOffset:CGPointMake(0, MIN(value.doubleValue - table.adjustedContentInset.top, max)) animated:NO];+ } else if ([verb isEqualToString:@"section"]) {+ CGRect rect = [table rectForSection:value.integerValue];+ CGFloat max = table.contentSize.height - table.bounds.size.height + table.adjustedContentInset.bottom;+ [table setContentOffset:CGPointMake(0, MIN(rect.origin.y - table.adjustedContentInset.top, max)) animated:NO];+ } else if ([verb isEqualToString:@"toggle"]) {+ UITableViewCell *cell = [table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:value.integerValue]];+ UISwitch *toggle = (UISwitch *)cell.accessoryView;+ [toggle setOn:!toggle.on animated:YES];+ [toggle sendActionsForControlEvents:UIControlEventValueChanged];+ } else if ([verb isEqualToString:@"drag"]) {+ NSArray<NSString *> *bandGain = [value componentsSeparatedByString:@":"];+ SGDSPCurveView *curve = [self curve];+ self.draggedBand = bandGain[0].integerValue;+ [curve highlight:self.draggedBand on:YES];+ // A few steps on the way, the way a finger gets there.+ double target = bandGain[1].doubleValue;+ for (int step = 1; step <= 5; step++) [curve setBand:self.draggedBand to:round(target * step / 5 * 10) / 10];+ [curve showBubbleFor:self.draggedBand];+ } else if ([verb isEqualToString:@"release"]) {+ SGDSPCurveView *curve = [self curve];+ [curve highlight:self.draggedBand on:NO];+ [curve refreshBar];+ } else if ([verb isEqualToString:@"preset"]) {+ [[self curve] setGains:SGDSPEqualizerPreset(value.integerValue) animated:YES];+ } else if ([verb isEqualToString:@"reset"]) {+ [[self curve] resetTapped];+ } else if ([verb isEqualToString:@"select"]) {+ NSArray<NSString *> *at = [value componentsSeparatedByString:@"."];+ NSIndexPath *path = [NSIndexPath indexPathForRow:at[1].integerValue inSection:at[0].integerValue];+ [table.delegate tableView:table didSelectRowAtIndexPath:path];+ } else if ([verb isEqualToString:@"push"]) {+ NSDictionary<NSString *, NSNumber *> *kinds = @{@"convolver": @(SGDSPFileImpulseResponse), @"ddc": @(SGDSPFileDDC), @"liveprog": @(SGDSPFileLiveprog)};+ UIViewController *page = kinds[value] ? SGDSPLibraryPage(kinds[value].integerValue)+ : [value isEqualToString:@"reference"] ? [self referencePage] : SGDSPGraphicEqPage();+ [self.nav pushViewController:page animated:NO];+ } else if ([verb isEqualToString:@"import"]) {+ NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:value];+ [@"imported" writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];+ id<UIDocumentPickerDelegate> page = (id<UIDocumentPickerDelegate>)self.nav.topViewController;+ UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[UTTypeData] asCopy:YES];+ [page documentPicker:picker didPickDocumentsAtURLs:@[[NSURL fileURLWithPath:path]]];+ } else if ([verb isEqualToString:@"paste"]) {+ UIPasteboard.generalPasteboard.string = value;+ [table.delegate tableView:table didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:2]];+ } else if ([verb isEqualToString:@"slide"] || [verb isEqualToString:@"swipe"]) {+ // slide=S.R:value drags row R of card S's slider there; swipe=S.R:n is VoiceOver's swipe up, n times.+ NSArray<NSString *> *at = [value componentsSeparatedByString:@":"];+ NSArray<NSString *> *path = [at[0] componentsSeparatedByString:@"."];+ UITableViewCell *cell = [table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:path[1].integerValue inSection:path[0].integerValue]];+ NSMutableArray<UISlider *> *sliders = [NSMutableArray array];+ findViews(cell, UISlider.class, sliders);+ UISlider *slider = sliders.firstObject;+ if ([verb isEqualToString:@"swipe"]) {+ for (NSInteger i = 0; i < at[1].integerValue; i++) [slider accessibilityIncrement];+ } else {+ slider.value = at[1].floatValue;+ [slider sendActionsForControlEvents:UIControlEventValueChanged];+ [slider sendActionsForControlEvents:UIControlEventTouchUpInside];+ }+ NSLog(@"[harness] slider %@ reads %@", slider.accessibilityLabel, slider.accessibilityValue);+ } else if ([verb isEqualToString:@"band"]) {+ // band=B:n is VoiceOver's swipe on the equalizer's band B, up n times (down for a negative n).+ NSArray<NSString *> *at = [value componentsSeparatedByString:@":"];+ SGDSPCurveView *curve = [self curve];+ NSArray *elements = curve.accessibilityElements;+ UIAccessibilityElement *band = elements[2 + at[0].integerValue];+ for (NSInteger i = 0; i < labs(at[1].integerValue); i++) {+ if (at[1].integerValue > 0) [band accessibilityIncrement];+ else [band accessibilityDecrement];+ }+ NSLog(@"[harness] band %@ reads %@", band.accessibilityLabel, band.accessibilityValue);+ } else if ([verb isEqualToString:@"string"]) {+ // string=<key suffix>:<text>, stored behind the page's back the way the engine's own changes land.+ NSRange colon = [value rangeOfString:@":"];+ SGDSPSetString([@"spotifyglass.dsp." stringByAppendingString:[value substringToIndex:colon.location]], [value substringFromIndex:colon.location + 1]);+ } else if ([verb isEqualToString:@"confirm"]) {+ // confirm: the destructive button of the alert on screen, pressed.+ UIAlertController *alert = (UIAlertController *)self.nav.topViewController.presentedViewController;+ for (UIAlertAction *action in alert.actions) {+ if (action.style != UIAlertActionStyleDestructive) continue;+ void (^handler)(UIAlertAction *) = [action valueForKey:@"handler"];+ [alert dismissViewControllerAnimated:NO completion:^{ handler(action); }];+ }+ } else if ([verb isEqualToString:@"pop"]) {+ [self.nav popViewControllerAnimated:NO];+ } else if ([verb isEqualToString:@"delete"]) {+ // delete=<row>: the library's swipe action on that file, run as a swipe and a tap on Delete would.+ NSIndexPath *path = [NSIndexPath indexPathForRow:value.integerValue inSection:1];+ UISwipeActionsConfiguration *swipe = [(id<UITableViewDelegate>)table.delegate tableView:table trailingSwipeActionsConfigurationForRowAtIndexPath:path];+ UIContextualAction *action = swipe.actions.firstObject;+ action.handler(action, [table cellForRowAtIndexPath:path], ^(BOOL done) { NSLog(@"[harness] swipe action done %d", done); });+ } else if ([verb isEqualToString:@"hit"]) {+ // hit: which band a finger going down takes, on each handle, beside it, between two and far off.+ SGDSPCurveView *curve = [self curve];+ NSArray<NSNumber *> *gains = SGDSPGains(SGKeyDSPEqualizerGains);+ for (NSInteger band = 0; band < 15; band++) {+ CGFloat x = [curve xFor:SGDSPEqualizerFrequencies[band]], y = [curve yFor:gains[band].doubleValue];+ NSLog(@"[harness] band %ld: on %ld, 20pt above %ld, 40pt above %ld, halfway to the next %ld",+ (long)band, (long)[curve bandAt:CGPointMake(x, y)], (long)[curve bandAt:CGPointMake(x, y - 20)],+ (long)[curve bandAt:CGPointMake(x, y - 40)], (long)[curve bandAt:CGPointMake(x + 9, y)]);+ }+ } else if ([verb isEqualToString:@"dump"]) {+ NSDictionary *all = NSUserDefaults.standardUserDefaults.dictionaryRepresentation;+ for (NSString *key in [all.allKeys sortedArrayUsingSelector:@selector(compare:)]) {+ if ([key hasPrefix:@"spotifyglass.dsp"]) NSLog(@"[harness] %@ = %@", key, all[key]);+ }+ NSLog(@"[harness] summary: %@; on top %@ with %ld sections", SGDSPSummary(), self.nav.topViewController.class,+ (long)table.numberOfSections);+ for (NSInteger section = 0; section < MIN(3, table.numberOfSections); section++) {+ NSLog(@"[harness] section %ld header %@ rows from %@", (long)section, NSStringFromCGRect([table rectForHeaderInSection:section]),+ NSStringFromCGRect([table rectForSection:section]));+ }+ }+}++@end++int main(int argc, char *argv[]) {+ @autoreleasepool {+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(AppDelegate.class));+ }+}diff --git a/harness/jamesdsp-page/stubs.m b/harness/jamesdsp-page/stubs.mnew file mode 100644index 00000000..dc5cc52b--- /dev/null+++ b/harness/jamesdsp-page/stubs.m@@ -0,0 +1,109 @@+// The engine side of JamesDSP.h (JamesDSP.x in the tweak) the harness does not compile: a made-up status,+// a few fake files in a temporary library, and a smooth curve through the gains instead of the filter's+// real response. The page draws what these answer, so they answer the way the engine is documented to.+#import "Core/SGCore.h"+#import "JamesDSP.h"+#import "JamesDSPEngine.h"++void SGDSPApply(NSString *effect) {+ NSLog(@"[harness] apply %@", effect);+}++NSString *SGDSPStatus(void) {+ if (!SGDSPSwitch(SGKeyDSP)) return @"Off";+ // Alternates, so the page's once a second refresh can be seen working.+ return (long)NSDate.date.timeIntervalSince1970 % 6 < 3 ? @"Running · 44.1 kHz · 3% load" : @"Running · 44.1 kHz · 4% load";+}++// A chosen file whose name has "broken" in it did not take, the way a script that does not compile would not.+NSString *SGDSPError(NSString *switchKey) {+ NSDictionary<NSString *, NSString *> *files = @{+ SGKeyDSPLiveprog: SGKeyDSPLiveprogFile, SGKeyDSPConvolver: SGKeyDSPConvolverFile, SGKeyDSPDDC: SGKeyDSPDDCFile,+ };+ NSString *fileKey = files[switchKey];+ if (fileKey && [SGDSPString(fileKey) containsString:@"broken"]) {+ return [NSString stringWithFormat:@"%@, line 14: syntax error near \"spl0 =\"", SGDSPString(fileKey)];+ }+ if ([switchKey isEqualToString:SGKeyDSPGraphicEq] && ![SGDSPString(SGKeyDSPGraphicEqNodes) hasPrefix:@"GraphicEQ:"]) {+ return @"Not a GraphicEQ line: it starts with \"GraphicEQ:\"";+ }+ return nil;+}++#pragma mark - file libraries++static NSString *folderName(SGDSPFileKind kind) {+ return kind == SGDSPFileImpulseResponse ? @"Convolver" : kind == SGDSPFileDDC ? @"DDC" : @"Liveprog";+}++NSArray<NSString *> *SGDSPFileExtensions(SGDSPFileKind kind) {+ if (kind == SGDSPFileImpulseResponse) return @[@"wav", @"flac", @"irs"];+ return kind == SGDSPFileDDC ? @[@"vdc"] : @[@"eel"];+}++NSString *SGDSPLibraryDirectory(SGDSPFileKind kind) {+ NSString *path = [[NSTemporaryDirectory() stringByAppendingPathComponent:@"JamesDSPStandIn"] stringByAppendingPathComponent:folderName(kind)];+ NSFileManager *files = NSFileManager.defaultManager;+ if ([files fileExistsAtPath:path]) return path;+ [files createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];+ NSArray<NSString *> *shipped = kind == SGDSPFileImpulseResponse ? @[@"Concert hall.wav", @"Headphone crossfeed.irs", @"Small room.flac"]+ : kind == SGDSPFileDDC ? @[@"Beyerdynamic DT 770.vdc", @"Sennheiser HD 600.vdc"]+ : @[@"Bass enhancer.eel", @"Stereo panning.eel", @"Tape saturation broken.eel", @"Vinyl noise.eel"];+ for (NSString *name in shipped) {+ [[@"stand-in" dataUsingEncoding:NSUTF8StringEncoding] writeToFile:[path stringByAppendingPathComponent:name] atomically:YES];+ }+ return path;+}++NSArray<NSString *> *SGDSPLibraryFiles(SGDSPFileKind kind) {+ NSArray<NSString *> *extensions = SGDSPFileExtensions(kind);+ NSMutableArray<NSString *> *names = [NSMutableArray array];+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:SGDSPLibraryDirectory(kind) error:nil]) {+ if ([extensions containsObject:name.pathExtension.lowercaseString]) [names addObject:name];+ }+ return [names sortedArrayUsingSelector:@selector(localizedStandardCompare:)];+}++NSString *SGDSPImportFile(SGDSPFileKind kind, NSURL *url, NSError **error) {+ NSString *name = url.lastPathComponent;+ if (![SGDSPFileExtensions(kind) containsObject:name.pathExtension.lowercaseString]) {+ if (error) *error = [NSError errorWithDomain:@"JamesDSP" code:1 userInfo:@{NSLocalizedDescriptionKey: @"Not a file of this kind."}];+ return nil;+ }+ NSString *target = [SGDSPLibraryDirectory(kind) stringByAppendingPathComponent:name];+ [NSFileManager.defaultManager removeItemAtPath:target error:nil];+ if (![NSFileManager.defaultManager copyItemAtPath:url.path toPath:target error:error]) return nil;+ return name;+}++BOOL SGDSPDeleteFile(SGDSPFileKind kind, NSString *name) {+ return [NSFileManager.defaultManager removeItemAtPath:[SGDSPLibraryDirectory(kind) stringByAppendingPathComponent:name] error:nil];+}++#pragma mark - curves++// Catmull-Rom through the points on a log frequency axis, flat past the ends: smooth, and through every gain.+static void smoothCurve(const double *bands, NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *values) {+ NSInteger n = (NSInteger)gains.count;+ for (NSInteger i = 0; i < count; i++) {+ double f = 20 * pow(1000, count > 1 ? (double)i / (count - 1) : 0);+ frequencies[i] = f;+ double x = log(f);+ if (x <= log(bands[0])) { values[i] = gains[0].doubleValue; continue; }+ if (x >= log(bands[n - 1])) { values[i] = gains[n - 1].doubleValue; continue; }+ NSInteger k = 0;+ while (k < n - 2 && x > log(bands[k + 1])) k++;+ double t = (x - log(bands[k])) / (log(bands[k + 1]) - log(bands[k]));+ double p0 = gains[MAX(k - 1, 0)].doubleValue, p1 = gains[k].doubleValue;+ double p2 = gains[k + 1].doubleValue, p3 = gains[MIN(k + 2, n - 1)].doubleValue;+ values[i] = 0.5 * (2 * p1 + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + (-p0 + 3 * p1 - 3 * p2 + p3) * t * t * t);+ }+}++void SGDSPEqualizerResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *decibels) {+ smoothCurve(SGDSPEqualizerFrequencies, gains, count, frequencies, decibels);+}++void SGDSPCompanderResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *values) {+ smoothCurve(SGDSPCompanderFrequencies, gains, count, frequencies, values);+}diff --git a/tweak/Sources/App/ModSettings.x b/tweak/Sources/App/ModSettings.xindex 4da8f880..8973dba3 100644--- a/tweak/Sources/App/ModSettings.x+++ b/tweak/Sources/App/ModSettings.x@@ -1,6 +1,7 @@// Settings: a Mod Settings row at the end of Spotify's settings list opens the mod's own page: the// Appearance card with Redesigned UI, then a page per part of Spotify, each holding what that part-// offers in the stored look (App/Pages.m: Navbar, Player, and Home & Library for the native look), Premium, ads & privacy+// offers in the stored look (App/Pages.m: Navbar, Player, and Home & Library for the native look), Audio+// effects (JamesDSP, Shared/JamesDSP, in either look and applying straight away), Premium, ads & privacy// and Labs, All flags, a searchable list of every flag with an override per flag, and Mod, the// build, its updates and links. The same row leads the side drawer's list (trees/test6.txt), above// Your plan, so the page is a tap from Home, and holding Home on the tab bar opens it too. The tweaks read the switches when they run, so a change@@ -18,6 +19,7 @@#import "Native/Home/Home.h"#import "Shared/AdBlock/AdBlock.h"#import "Shared/Flags/Flags.h"+#import "Shared/JamesDSP/JamesDSPPage.h"#import "Redesigned/LiveActivity/LiveActivity.h"#import "App/About/About.h"#import "Pages.h"@@ -39,11 +41,15 @@ static UIViewController *modSettingsPage(void) {if (signing) [sections addObject:SGSection(nil, @[signing])];SGModRow *mod = pageRow(@"Mod", @"info.circle", ^UIViewController *{ return SGAboutPage(); });mod.value = ^NSString *{ return @(SG_VERSION); };+ // JamesDSP works on the sound, so both looks have it, with what it is doing beside the chevron.+ SGModRow *audioEffects = pageRow(@"Audio effects", @"slider.vertical.3", ^UIViewController *{ return SGDSPSettingsPage(); });+ audioEffects.value = ^NSString *{ return SGDSPSummary(); };// Home & Library holds only the native look's switches, so the redesign has no such page; the// Live Activity is the redesign's alone.NSMutableArray<SGModRow *> *parts = [NSMutableArray arrayWithArray:@[pageRow(@"Navbar", @"dock.rectangle", ^UIViewController *{ return SGNavbarPage(); }),pageRow(@"Player", @"play.circle", ^UIViewController *{ return SGPlayerSettingsPage(); }),+ audioEffects,]];if (SGRedesignedUIStored()) {SGModRow *liveActivity = pageRow(@"Live Activity", @"platter.filled.top.iphone", ^UIViewController *{ return SGRLiveActivitySettingsPage(); });diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSPLibraryPage.m b/tweak/Sources/Shared/JamesDSP/JamesDSPLibraryPage.mnew file mode 100644index 00000000..3906c0e2--- /dev/null+++ b/tweak/Sources/Shared/JamesDSP/JamesDSPLibraryPage.m@@ -0,0 +1,424 @@+// The pages a file effect's row and the Graphic EQ's row push: a library of files with the chosen one+// ticked, and the GraphicEQ text to paste or edit. Each shows the effect's error, if its last change did+// not take, in a red card at the top, looked at again once a second while the page is open.+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>+#import "Core/SGCore.h"+#import "Settings/SGPage.h"+#import "Settings/SGPageStyle.h"+#import "JamesDSPPage.h"++static NSString *const kAutoEqURL = @"https://github.com/jaakkopasanen/AutoEq";++static NSString *fileKeyOf(SGDSPFileKind kind) {+ if (kind == SGDSPFileImpulseResponse) return SGKeyDSPConvolverFile;+ return kind == SGDSPFileDDC ? SGKeyDSPDDCFile : SGKeyDSPLiveprogFile;+}++static NSString *switchKeyOf(SGDSPFileKind kind) {+ if (kind == SGDSPFileImpulseResponse) return SGKeyDSPConvolver;+ return kind == SGDSPFileDDC ? SGKeyDSPDDC : SGKeyDSPLiveprog;+}++NSString *SGDSPChosenFile(SGDSPFileKind kind) {+ NSString *name = SGDSPString(fileKeyOf(kind));+ return name.length ? name : @"None";+}++// ".eel", ".vdc", ".wav, .flac or .irs".+static NSString *extensionList(SGDSPFileKind kind) {+ NSMutableArray<NSString *> *dotted = [NSMutableArray array];+ for (NSString *extension in SGDSPFileExtensions(kind)) [dotted addObject:[@"." stringByAppendingString:extension]];+ if (dotted.count < 2) return dotted.firstObject ?: @"";+ NSString *last = dotted.lastObject;+ [dotted removeLastObject];+ return [NSString stringWithFormat:@"%@ or %@", [dotted componentsJoinedByString:@", "], last];+}++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];+}++static UITableViewCell *errorCell(UITableView *table, NSString *text) {+ UITableViewCell *cell = SGDequeueCell(table, @"error");+ SGFillCell(cell, @"Not applied", text, SGRed(), @"exclamationmark.triangle.fill");+ UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;+ content.secondaryTextProperties.color = SGRed();+ cell.contentConfiguration = content;+ return cell;+}++static UITableViewCell *tiledCell(UITableView *table, NSString *title, NSString *subtitle, NSString *symbol, UIColor *color) {+ UITableViewCell *cell = SGDequeueCell(table, @"action");+ SGFillCell(cell, title, subtitle, color, nil);+ UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;+ content.image = SGTileImage(symbol);+ content.imageToTextPadding = 14;+ cell.contentConfiguration = content;+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ cell.separatorInset = UIEdgeInsetsMake(0, 58, 0, 0);+ return cell;+}++#pragma mark - the error card++// A page of this file whose section 0 is the effect's error: one red row while there is one, nothing+// otherwise, the row coming and going without the page reloading.+@interface SGDSPErrorPage : SGPage+@property (nonatomic, copy) NSString *errorKey;+@end++@implementation SGDSPErrorPage {+ NSString *_error;+ NSTimer *_ticker;+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ SGInsetForBars(self.tableView);+}++- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ _error = SGDSPError(self.errorKey);+ [self.tableView reloadData];+ [_ticker invalidate];+ _ticker = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showError) userInfo:nil repeats:YES];+}++- (void)viewDidDisappear:(BOOL)animated {+ [super viewDidDisappear:animated];+ [_ticker invalidate];+ _ticker = nil;+}++- (void)showError {+ NSString *now = SGDSPError(self.errorKey);+ if (now == _error || [now isEqualToString:_error]) return;+ NSString *shown = _error;+ NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];+ [self.tableView performBatchUpdates:^{+ self->_error = now;+ if (shown && now) [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];+ else if (now) [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];+ else [self.tableView deleteRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];+ } completion:nil];+}++- (NSInteger)errorRows {+ return _error ? 1 : 0;+}++- (UITableViewCell *)errorCellIn:(UITableView *)table {+ return errorCell(table, _error);+}++- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {+ return section == 0 && !_error ? CGFLOAT_MIN : SGSectionGap;+}++- (UIView *)tableView:(UITableView *)table viewForFooterInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForFooterInSection:(NSInteger)section {+ return CGFLOAT_MIN;+}++@end++#pragma mark - a library++// The files of one kind, the chosen one ticked: a tap chooses a file and uses it straight away, and the+// page stays, so one after another can be heard. A swipe deletes one; Import file… copies one in from Files.+@interface SGDSPFilesPage : SGDSPErrorPage <UIDocumentPickerDelegate>+- (instancetype)initWithKind:(SGDSPFileKind)kind;+@end++@implementation SGDSPFilesPage {+ SGDSPFileKind _kind;+ NSArray<NSString *> *_files;+ UIView *_footer;+}++- (instancetype)initWithKind:(SGDSPFileKind)kind {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ _kind = kind;+ self.errorKey = switchKeyOf(kind);+ self.title = kind == SGDSPFileImpulseResponse ? @"Impulse responses" : kind == SGDSPFileDDC ? @"DDC files" : @"Scripts";+ return self;+}++- (void)viewDidLoad {+ [super viewDidLoad];+ _footer = SGNote(@"Choosing a file uses it straight away. Swipe left on one to delete it.");+ self.tableView.tableFooterView = _footer;+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ SGFitNote(self.tableView, _footer, 16, 24);+}++- (void)viewWillAppear:(BOOL)animated {+ _files = SGDSPLibraryFiles(_kind);+ [super viewWillAppear:animated];+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {+ return 3;+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ if (section == 0) return [self errorRows];+ if (section == 1) return MAX((NSInteger)_files.count, 1);+ return 1;+}++- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ if (path.section == 0) return [self errorCellIn:table];+ if (path.section == 2) {+ NSString *subtitle = [NSString stringWithFormat:@"A %@ file from Files", extensionList(_kind)];+ return tiledCell(table, @"Import file…", subtitle, @"square.and.arrow.down", nil);+ }+ UITableViewCell *cell = SGDequeueCell(table, @"file");+ if (!_files.count) {+ SGFillCell(cell, @"No files yet", nil, SGGrey(), nil);+ cell.accessibilityTraits = UIAccessibilityTraitNone;+ return cell;+ }+ NSString *name = _files[(NSUInteger)path.row];+ BOOL chosen = [name isEqualToString:SGDSPString(fileKeyOf(_kind))];+ SGFillCell(cell, name, nil, nil, nil);+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ if (chosen) {+ UIImageView *tick = SGSymbolView(@"checkmark", 13, UIImageSymbolWeightSemibold, 16);+ tick.tintColor = SGGreen();+ cell.accessoryView = tick;+ }+ cell.accessibilityTraits = chosen ? UIAccessibilityTraitButton | UIAccessibilityTraitSelected : UIAccessibilityTraitButton;+ return cell;+}++- (BOOL)tableView:(UITableView *)table shouldHighlightRowAtIndexPath:(NSIndexPath *)path {+ return path.section == 2 || (path.section == 1 && _files.count);+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ if (path.section == 2) {+ [self pickFile];+ return;+ }+ if (path.section != 1 || !_files.count) return;+ SGDSPSetString(fileKeyOf(_kind), _files[(NSUInteger)path.row]);+ [table reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];+}++- (UISwipeActionsConfiguration *)tableView:(UITableView *)table trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)path {+ if (path.section != 1 || !_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)) {+ [self deleteFile:name at:path];+ done(YES);+ }];+ delete.image = [UIImage systemImageNamed:@"trash"];+ return [UISwipeActionsConfiguration configurationWithActions:@[delete]];+}++// The chosen file going leaves the effect with none, rather than naming a file that is not there.+- (void)deleteFile:(NSString *)name at:(NSIndexPath *)path {+ if (!SGDSPDeleteFile(_kind, name)) {+ showAlert(self, @"Could not delete the file", nil);+ return;+ }+ if ([name isEqualToString:SGDSPString(fileKeyOf(_kind))]) SGDSPSetString(fileKeyOf(_kind), @"");+ _files = SGDSPLibraryFiles(_kind);+ if (_files.count) [self.tableView deleteRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationAutomatic];+ else [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];+}++// .eel, .vdc and .irs are nobody's registered types, so the picker offers any file and the name is+// checked after.+- (void)pickFile {+ UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[UTTypeData] asCopy:YES];+ picker.delegate = self;+ [self presentViewController:picker animated:YES completion:nil];+}++- (void)documentPicker:(UIDocumentPickerViewController *)picker didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {+ NSURL *url = urls.firstObject;+ if (!url) return;+ if (![SGDSPFileExtensions(_kind) containsObject:url.pathExtension.lowercaseString]) {+ showAlert(self, @"Not a file this effect takes", [NSString stringWithFormat:@"Pick a %@ file.", extensionList(_kind)]);+ return;+ }+ NSError *error = nil;+ NSString *name = SGDSPImportFile(_kind, url, &error);+ if (!name) {+ showAlert(self, @"Could not import the file", error.localizedDescription);+ return;+ }+ SGDSPSetString(fileKeyOf(_kind), name);+ _files = SGDSPLibraryFiles(_kind);+ [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];+}++@end++UIViewController *SGDSPLibraryPage(SGDSPFileKind kind) {+ return [[SGDSPFilesPage alloc] initWithKind:kind];+}++#pragma mark - the GraphicEQ text++// What the Graphic EQ holds until something is pasted: flat, JamesDSP's own starting point.+static NSString *const kFlatGraphicEq = @"GraphicEQ: 0.0 0.0;";++typedef NS_ENUM(NSInteger, SGGraphicEqRow) {+ SGGraphicEqSave,+ SGGraphicEqPaste,+ SGGraphicEqReset,+ SGGraphicEqRowCount,+};++@interface SGDSPGraphicEqEditor : SGDSPErrorPage <UITextViewDelegate>+@end++@implementation SGDSPGraphicEqEditor {+ UITextView *_text;+ UIView *_intro;+}++- (instancetype)init {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ self.title = @"Graphic EQ";+ self.errorKey = SGKeyDSPGraphicEq;+ return self;+}++- (void)viewDidLoad {+ [super viewDidLoad];+ _intro = SGNote(@"AutoEq's GraphicEQ format: \"GraphicEQ:\", then a frequency and a gain in dB per point, "+ "separated by semicolons. Paste the GraphicEQ file for your headphones, or edit the text and save.");+ self.tableView.tableHeaderView = _intro;+ self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;++ _text = [UITextView new];+ _text.font = [UIFont monospacedSystemFontOfSize:12 weight:UIFontWeightRegular];+ _text.textColor = UIColor.whiteColor;+ _text.backgroundColor = UIColor.clearColor;+ _text.textContainerInset = UIEdgeInsetsMake(12, 16, 12, 16);+ _text.textContainer.lineFragmentPadding = 0;+ _text.keyboardAppearance = UIKeyboardAppearanceDark;+ _text.autocorrectionType = UITextAutocorrectionTypeNo;+ _text.autocapitalizationType = UITextAutocapitalizationTypeNone;+ _text.spellCheckingType = UITextSpellCheckingTypeNo;+ _text.smartQuotesType = UITextSmartQuotesTypeNo;+ _text.smartDashesType = UITextSmartDashesTypeNo;+ _text.smartInsertDeleteType = UITextSmartInsertDeleteTypeNo;+ _text.accessibilityLabel = @"GraphicEQ";+ _text.delegate = self;+ _text.text = SGDSPString(SGKeyDSPGraphicEqNodes);+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ SGFitNote(self.tableView, _intro, 24, 0);+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {+ return 4;+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ if (section == 0) return [self errorRows];+ return section == 2 ? SGGraphicEqRowCount : 1;+}++- (CGFloat)tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {+ return path.section == 1 ? 188 : UITableViewAutomaticDimension;+}++- (BOOL)edited {+ return ![[self cleaned:_text.text] isEqualToString:SGDSPString(SGKeyDSPGraphicEqNodes)];+}++- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ if (path.section == 0) return [self errorCellIn:table];+ if (path.section == 1) {+ UITableViewCell *cell = SGDequeueCell(table, @"text");+ cell.backgroundColor = SGCardBackground();+ cell.selectionStyle = UITableViewCellSelectionStyleNone;+ _text.frame = cell.contentView.bounds;+ _text.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ [cell.contentView addSubview:_text];+ return cell;+ }+ if (path.section == 3) return tiledCell(table, @"AutoEq", @"GraphicEQ files for thousands of headphones", @"safari", nil);+ switch (path.row) {+ case SGGraphicEqSave: {+ BOOL edited = [self edited];+ UITableViewCell *cell = tiledCell(table, @"Save", edited ? @"Use the text above" : @"Nothing changed", @"checkmark", edited ? nil : SGGrey());+ cell.accessibilityTraits = edited ? UIAccessibilityTraitButton : UIAccessibilityTraitButton | UIAccessibilityTraitNotEnabled;+ return cell;+ }+ case SGGraphicEqPaste:+ return tiledCell(table, @"Paste", @"Replace the text with what you copied, and use it", @"doc.on.clipboard", nil);+ default:+ return tiledCell(table, @"Reset", @"Back to flat", @"arrow.counterclockwise", nil);+ }+}++- (BOOL)tableView:(UITableView *)table shouldHighlightRowAtIndexPath:(NSIndexPath *)path {+ return path.section == 3 || (path.section == 2 && (path.row != SGGraphicEqSave || [self edited]));+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ if (path.section == 3) {+ SGOpenURL(kAutoEqURL);+ return;+ }+ if (path.section != 2) return;+ if (path.row == SGGraphicEqSave) [self save:_text.text];+ else if (path.row == SGGraphicEqPaste) [self save:UIPasteboard.generalPasteboard.string];+ else [self save:kFlatGraphicEq];+}++// One line, trimmed: AutoEq's files end in a newline, and a copy out of a web page often has more.+- (NSString *)cleaned:(NSString *)text {+ NSCharacterSet *space = NSCharacterSet.whitespaceAndNewlineCharacterSet;+ NSArray<NSString *> *words = [text componentsSeparatedByCharactersInSet:space];+ words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];+ return [words componentsJoinedByString:@" "];+}++- (void)save:(NSString *)text {+ NSString *line = [self cleaned:text ?: @""];+ if (![line.lowercaseString hasPrefix:@"graphiceq:"]) {+ showAlert(self, text.length ? @"Not a GraphicEQ line" : @"Nothing to paste",+ @"It starts with \"GraphicEQ:\", then pairs of a frequency and a gain: GraphicEQ: 20 -1.2; 21 -1.1; …");+ return;+ }+ [_text resignFirstResponder];+ SGDSPSetString(SGKeyDSPGraphicEqNodes, line);+ _text.text = line;+ [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:SGGraphicEqSave inSection:2]] withRowAnimation:UITableViewRowAnimationNone];+}++- (void)textViewDidChange:(UITextView *)textView {+ [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:SGGraphicEqSave inSection:2]] withRowAnimation:UITableViewRowAnimationNone];+}++@end++UIViewController *SGDSPGraphicEqPage(void) {+ return [SGDSPGraphicEqEditor new];+}diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSPPage.h b/tweak/Sources/Shared/JamesDSP/JamesDSPPage.hnew file mode 100644index 00000000..98c6795a--- /dev/null+++ b/tweak/Sources/Shared/JamesDSP/JamesDSPPage.h@@ -0,0 +1,21 @@+// Mod Settings > Audio effects: JamesDSP's switch with what the engine is doing under it, then a card per+// effect in RootlessJamesDSP's order, each opening out into its controls while its switch is on. Everything+// on it goes through JamesDSP.h's setters, so it applies as it changes, a slider while it is dragged.+//+// JamesDSPPage.m the page: the switch, the status, the effects' cards, their sliders and choices+// SGDSPCurveView.m the equalizer's and the compressor's curve, with a handle to drag per band+// JamesDSPLibraryPage.m a file effect's library (the convolver's, ViPER DDC's, Liveprog's) and the GraphicEQ editor+//+// Main thread only.+#import <UIKit/UIKit.h>+#import "JamesDSP.h"++UIViewController *SGDSPSettingsPage(void);+// What the Mod Settings row reads out: Off, On, or how many effects are on.+NSString *SGDSPSummary(void);++// The pages the effects' rows push (JamesDSPLibraryPage.m).+UIViewController *SGDSPLibraryPage(SGDSPFileKind kind);+UIViewController *SGDSPGraphicEqPage(void);+// The choice of a file effect's library, "None" when there is none.+NSString *SGDSPChosenFile(SGDSPFileKind kind);diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSPPage.m b/tweak/Sources/Shared/JamesDSP/JamesDSPPage.mnew file mode 100644index 00000000..11c24a64--- /dev/null+++ b/tweak/Sources/Shared/JamesDSP/JamesDSPPage.m@@ -0,0 +1,765 @@+// The Audio effects page. It is not an SGModPage: its sliders store as they move, its cards open out+// into their controls as their switches go on, and its status line and the effects' errors come and go+// while it is open, none of which a page of fixed rows does. It keeps Settings/'s look all the same: the+// cards, the 13pt titles over 11pt subtitles, the tiles, the value and the chevron, the checkmark lists.+#import <CoreText/SFNTLayoutTypes.h>+#import "Core/SGCore.h"+#import "Settings/SGPage.h"+#import "Settings/SGPageStyle.h"+#import "JamesDSPPage.h"+#import "SGDSPCurveView.h"++typedef NS_ENUM(NSInteger, SGDSPRowKind) {+ SGDSPRowSlider, // a number, stored as the slider moves+ SGDSPRowChoice, // one of a list of names, stored as its index+ SGDSPRowPage, // a page of its own, its value beside the chevron+ SGDSPRowCurve, // the equalizer's or the compressor's gains+};++@interface SGDSPRow : NSObject+@property (nonatomic) SGDSPRowKind kind;+@property (nonatomic, copy) NSString *title;+@property (nonatomic, copy) NSString *key;+@property (nonatomic, copy) NSString *unit;+@property (nonatomic, copy) NSArray<NSString *> *names; // a choice's, or what a slider's steps read as+@property (nonatomic, copy) NSString *(^value)(void);+@property (nonatomic, copy) UIViewController *(^page)(void);+@end++@implementation SGDSPRow+@end++// An effect's card: the switch at its head and the rows it opens out into while the switch is on.+@interface SGDSPEffect : NSObject+@property (nonatomic, copy) NSString *key; // the switch; nil for output control, which is always on+@property (nonatomic, copy) NSString *title;+@property (nonatomic, copy) NSString *subtitle;+@property (nonatomic, copy) NSString *symbol;+@property (nonatomic, copy) NSArray<SGDSPRow *> *rows;+@end++@implementation SGDSPEffect+@end++#pragma mark - the effects++static SGDSPRow *row(SGDSPRowKind kind, NSString *title, NSString *key) {+ SGDSPRow *row = [SGDSPRow new];+ row.kind = kind;+ row.title = title;+ row.key = key;+ return row;+}++static SGDSPRow *slider(NSString *title, NSString *key, NSString *unit) {+ SGDSPRow *r = row(SGDSPRowSlider, title, key);+ r.unit = unit;+ return r;+}++static SGDSPRow *steps(NSString *title, NSString *key, NSArray<NSString *> *names) {+ SGDSPRow *r = row(SGDSPRowSlider, title, key);+ r.names = names;+ return r;+}++static SGDSPRow *choice(NSString *title, NSString *key, NSArray<NSString *> *names) {+ SGDSPRow *r = row(SGDSPRowChoice, title, key);+ r.names = names;+ return r;+}++static SGDSPRow *pageRow(NSString *title, NSString *(^value)(void), UIViewController *(^page)(void)) {+ SGDSPRow *r = row(SGDSPRowPage, title, nil);+ r.value = value;+ r.page = page;+ return r;+}++static SGDSPRow *fileRow(NSString *title, SGDSPFileKind kind) {+ return pageRow(title, ^NSString *{ return SGDSPChosenFile(kind); }, ^UIViewController *{ return SGDSPLibraryPage(kind); });+}++static SGDSPEffect *effect(NSString *key, NSString *title, NSString *subtitle, NSString *symbol, NSArray<SGDSPRow *> *rows) {+ SGDSPEffect *e = [SGDSPEffect new];+ e.key = key;+ e.title = title;+ e.subtitle = subtitle;+ e.symbol = symbol;+ e.rows = rows;+ return e;+}++// The response's points, or Flat when every gain is zero, the way the stored text reads before anything is pasted.+static NSString *graphicEqSummary(void) {+ NSString *text = SGDSPString(SGKeyDSPGraphicEqNodes);+ NSRange colon = [text rangeOfString:@":"];+ if (colon.location != NSNotFound) text = [text substringFromIndex:colon.location + 1];+ NSUInteger points = 0;+ BOOL flat = YES;+ NSCharacterSet *space = NSCharacterSet.whitespaceAndNewlineCharacterSet;+ for (NSString *pair in [text componentsSeparatedByString:@";"]) {+ NSArray<NSString *> *parts = [[pair stringByTrimmingCharactersInSet:space] componentsSeparatedByCharactersInSet:space];+ parts = [parts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];+ if (parts.count != 2) continue;+ points++;+ flat &= parts[1].doubleValue == 0;+ }+ return flat ? @"Flat" : [NSString stringWithFormat:@"%lu points", (unsigned long)points];+}++// RootlessJamesDSP's cards, in its order.+static NSArray<SGDSPEffect *> *effects(void) {+ return @[+ effect(nil, @"Output control", @"Gain and limiter, always on", @"speaker.wave.2", @[+ slider(@"Post gain", SGKeyDSPPostGain, @" dB"),+ slider(@"Limiter threshold", SGKeyDSPLimiterThreshold, @" dB"),+ slider(@"Limiter release", SGKeyDSPLimiterRelease, @" ms"),+ ]),+ effect(SGKeyDSPCompander, @"Dynamic range compressor", @"Evens out loud and quiet parts", @"rectangle.compress.vertical", @[+ row(SGDSPRowCurve, nil, SGKeyDSPCompanderGains),+ slider(@"Time constant", SGKeyDSPCompanderTime, @" s"),+ steps(@"Granularity", SGKeyDSPCompanderGranularity, @[@"Very low", @"Low", @"Medium", @"High", @"Extreme"]),+ choice(@"Transform", SGKeyDSPCompanderTransform, SGDSPCompanderTransformNames()),+ ]),+ effect(SGKeyDSPBass, @"Bass boost", @"Lifts the low end", @"hifispeaker", @[+ slider(@"Maximum gain", SGKeyDSPBassGain, @" dB"),+ ]),+ effect(SGKeyDSPEqualizer, @"Equalizer", @"15 bands, with JamesDSP's presets", @"slider.vertical.3", @[+ row(SGDSPRowCurve, nil, SGKeyDSPEqualizerGains),+ choice(@"Filter", SGKeyDSPEqualizerFilter, SGDSPEqualizerFilterNames()),+ choice(@"Interpolation", SGKeyDSPEqualizerInterpolation, SGDSPEqualizerInterpolationNames()),+ ]),+ effect(SGKeyDSPGraphicEq, @"Graphic EQ", @"Any curve, like AutoEq's corrections", @"chart.xyaxis.line", @[+ pageRow(@"Response", ^NSString *{ return graphicEqSummary(); }, ^UIViewController *{ return SGDSPGraphicEqPage(); }),+ ]),+ effect(SGKeyDSPConvolver, @"Convolver", @"Recorded rooms and speakers", @"waveform.path", @[+ fileRow(@"Impulse response", SGDSPFileImpulseResponse),+ choice(@"Optimization", SGKeyDSPConvolverMode, SGDSPConvolverModeNames()),+ ]),+ effect(SGKeyDSPDDC, @"ViPER DDC", @"Headphone correction presets", @"headphones", @[+ fileRow(@"DDC file", SGDSPFileDDC),+ ]),+ effect(SGKeyDSPLiveprog, @"Liveprog", @"Effects written as EEL scripts", @"chevron.left.forwardslash.chevron.right", @[+ fileRow(@"Script", SGDSPFileLiveprog),+ ]),+ effect(SGKeyDSPReverb, @"Reverb", @"A room around the music", @"building.columns", @[+ choice(@"Room", SGKeyDSPReverbPreset, SGDSPReverbPresetNames()),+ ]),+ effect(SGKeyDSPStereoWide, @"Stereo widening", @"A wider or narrower stereo image", @"arrow.left.and.right", @[+ slider(@"Width", SGKeyDSPStereoWideLevel, @"%"),+ ]),+ effect(SGKeyDSPCrossfeed, @"Crossfeed", @"Softer stereo on headphones", @"ear", @[+ choice(@"Preset", SGKeyDSPCrossfeedMode, SGDSPCrossfeedModeNames()),+ ]),+ effect(SGKeyDSPTube, @"Analog modelling", @"Tube amplifier warmth", @"flame", @[+ slider(@"Drive", SGKeyDSPTubeDrive, @" dB"),+ ]),+ ];+}++// The effects whose last change can fail, each reporting why under its own switch key.+static NSSet<NSString *> *reportingEffects(void) {+ return [NSSet setWithArray:@[SGKeyDSPGraphicEq, SGKeyDSPConvolver, SGKeyDSPDDC, SGKeyDSPLiveprog]];+}++NSString *SGDSPSummary(void) {+ if (!SGDSPSwitch(SGKeyDSP)) return @"Off";+ NSUInteger on = 0;+ for (SGDSPEffect *e in effects()) on += e.key && SGDSPSwitch(e.key);+ if (!on) return @"On";+ return on == 1 ? @"1 effect" : [NSString stringWithFormat:@"%lu effects", (unsigned long)on];+}++#pragma mark - numbers++// On the step's grid (every range starts on it), without the float noise of getting there.+static double snapped(NSString *key, double value) {+ SGDSPRange range = SGDSPRangeFor(key);+ if (range.step > 0) value = round(round(value / range.step) * range.step * 1e6) / 1e6;+ return MAX(range.min, MIN(range.max, value));+}++// "−3.5 dB", "+2 dB", "60 ms", "0.22 s", "60%": the step's decimals unless the number is whole, a sign+// where the range runs both ways, and a real minus.+static NSString *numberText(SGDSPRow *row, double value) {+ if (row.names.count) {+ NSInteger index = (NSInteger)lround(value);+ return row.names[(NSUInteger)MAX(0, MIN((NSInteger)row.names.count - 1, index))];+ }+ SGDSPRange range = SGDSPRangeFor(row.key);+ int decimals = range.step >= 1 ? 0 : range.step >= 0.1 ? 1 : 2;+ if (fabs(value - round(value)) < 1e-6) decimals = 0;+ NSString *number = [NSString stringWithFormat:@"%.*f", decimals, fabs(value)];+ NSString *sign = number.doubleValue == 0 ? @"" : value < 0 ? @"−" : range.min < 0 && range.max > 0 ? @"+" : @"";+ return [NSString stringWithFormat:@"%@%@%@", sign, number, row.unit ?: @""];+}++// Figures that do not shift sideways as they change, in whatever face the titles are in.+static UIFont *tabular(UIFont *font) {+ UIFontDescriptor *descriptor = [font.fontDescriptor fontDescriptorByAddingAttributes:@{+ UIFontDescriptorFeatureSettingsAttribute: @[@{UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType),+ UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector)}],+ }];+ return [UIFont fontWithDescriptor:descriptor size:font.pointSize];+}++#pragma mark - the slider row++// A step at a time for VoiceOver, or a twentieth of the range where the steps are too fine to swipe through.+@interface SGDSPSlider : UISlider+@property (nonatomic) float spokenStep;+@end++@implementation SGDSPSlider++- (void)accessibilityIncrement {+ self.value += self.spokenStep;+ [self sendActionsForControlEvents:UIControlEventValueChanged];+}++- (void)accessibilityDecrement {+ self.value -= self.spokenStep;+ [self sendActionsForControlEvents:UIControlEventValueChanged];+}++@end++// The title and the value over a slider in the accent colour, storing each step as the thumb reaches it.+@interface SGDSPSliderCell : UITableViewCell+- (void)showRow:(SGDSPRow *)row;+@end++@implementation SGDSPSliderCell {+ SGDSPRow *_row;+ UILabel *_title, *_value;+ SGDSPSlider *_slider;+ double _shown;+ BOOL _detents; // few enough steps that the thumb jumps between them as it is dragged+}++- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)identifier {+ if (!(self = [super initWithStyle:style reuseIdentifier:identifier])) return nil;+ self.selectionStyle = UITableViewCellSelectionStyleNone;+ _title = [UILabel new];+ _title.textColor = UIColor.whiteColor;+ _title.isAccessibilityElement = NO;+ _value = [UILabel new];+ _value.textColor = SGGrey();+ _value.textAlignment = NSTextAlignmentRight;+ _value.isAccessibilityElement = NO;+ _slider = [SGDSPSlider new];+ _slider.maximumTrackTintColor = [UIColor colorWithWhite:1 alpha:0.16];+ [_slider addTarget:self action:@selector(moved) forControlEvents:UIControlEventValueChanged];+ [_slider addTarget:self action:@selector(released) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];+ for (UIView *view in @[_title, _value, _slider]) [self.contentView addSubview:view];+ return self;+}++- (void)showRow:(SGDSPRow *)row {+ _row = row;+ SGDSPRange range = SGDSPRangeFor(row.key);+ NSInteger count = range.step > 0 ? (NSInteger)lround((range.max - range.min) / range.step) : 0;+ _detents = count > 0 && count <= 24;+ _title.font = SGTitleFont();+ _value.font = tabular(SGTitleFont());+ _title.text = row.title;+ _slider.minimumTrackTintColor = SGGreen();+ _slider.minimumValue = (float)range.min;+ _slider.maximumValue = (float)range.max;+ _slider.spokenStep = (float)(count > 0 && count <= 40 ? range.step : snapped(row.key, range.min + (range.max - range.min) / 20) - range.min);+ _shown = SGDSPNumber(row.key);+ _slider.value = (float)_shown;+ _slider.accessibilityLabel = row.title;+ [self showValue];+}++- (void)showValue {+ _value.text = numberText(_row, _shown);+ _slider.accessibilityValue = _value.text;+ [self setNeedsLayout];+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGFloat width = self.contentView.bounds.size.width, side = 16;+ [_value sizeToFit];+ CGFloat valueWidth = MAX(_value.bounds.size.width, 44);+ _value.frame = CGRectMake(width - side - valueWidth, 12, valueWidth, 18);+ _title.frame = CGRectMake(side, 12, CGRectGetMinX(_value.frame) - side - 8, 18);+ _slider.frame = CGRectMake(side, 36, width - 2 * side, 28);+}++- (void)moved {+ double value = snapped(_row.key, _slider.value);+ if (_detents) _slider.value = (float)value;+ if (value == _shown) return;+ _shown = value;+ SGDSPSetNumber(_row.key, value);+ [self showValue];+}++- (void)released {+ [_slider setValue:(float)_shown animated:YES];+}++@end++#pragma mark - the curve row++@interface SGDSPCurveCell : UITableViewCell+@property (nonatomic, strong) SGDSPCurveView *curve;+@end++@implementation SGDSPCurveCell+- (void)layoutSubviews {+ [super layoutSubviews];+ self.curve.frame = self.contentView.bounds;+}+@end++#pragma mark - a choice's list++// The names a choice picks from, a checkmark against the one set. Unlike Settings' own list it stays+// open after a pick, so one reverb room after another can be heard before going back.+@interface SGDSPChoicePage : SGPage+- (instancetype)initWithRow:(SGDSPRow *)row;+@end++@implementation SGDSPChoicePage {+ SGDSPRow *_row;+}++- (instancetype)initWithRow:(SGDSPRow *)row {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ self.title = row.title;+ _row = row;+ return self;+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ SGInsetForBars(self.tableView);+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ return (NSInteger)_row.names.count;+}++- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {+ return 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 {+ UITableViewCell *cell = SGDequeueCell(table, @"choice");+ SGFillCell(cell, _row.names[(NSUInteger)path.row], nil, nil, nil);+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ BOOL chosen = path.row == (NSInteger)lround(SGDSPNumber(_row.key));+ if (chosen) {+ UIImageView *tick = SGSymbolView(@"checkmark", 13, UIImageSymbolWeightSemibold, 16);+ tick.tintColor = SGGreen();+ cell.accessoryView = tick;+ }+ cell.accessibilityTraits = chosen ? UIAccessibilityTraitButton | UIAccessibilityTraitSelected : UIAccessibilityTraitButton;+ return cell;+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ SGDSPSetNumber(_row.key, path.row);+ [table reloadRowsAtIndexPaths:table.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone];+}++@end++#pragma mark - the page++// The value and the chevron of a row opening a page, as Settings' own rows draw them.+static UIView *valueAndChevron(NSString *text) {+ UILabel *label = [UILabel new];+ label.font = SGTitleFont();+ label.textColor = SGGrey();+ label.text = text;+ [label sizeToFit];+ UIImageView *chevron = SGSymbolView(@"chevron.right", 13, UIImageSymbolWeightSemibold, 16);+ CGFloat height = MAX(label.bounds.size.height, chevron.bounds.size.height);+ UIView *box = [[UIView alloc] initWithFrame:CGRectMake(0, 0, label.bounds.size.width + 6 + chevron.bounds.size.width, height)];+ label.center = CGPointMake(label.bounds.size.width / 2, height / 2);+ chevron.center = CGPointMake(box.bounds.size.width - chevron.bounds.size.width / 2, height / 2);+ [box addSubview:label];+ [box addSubview:chevron];+ return box;+}++@interface SGDSPPage : SGPage+@end++@implementation SGDSPPage {+ NSArray<SGDSPEffect *> *_effects;+ NSMutableSet<NSString *> *_open; // the effects showing their rows+ NSMutableDictionary<NSString *, NSString *> *_errors; // the errors showing, by switch key+ UIView *_intro;+ UIView *_credits;+ UITextView *_creditsText;+ NSTimer *_ticker;+}++- (instancetype)init {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ self.title = @"Audio effects";+ _effects = effects();+ _open = [NSMutableSet set];+ _errors = [NSMutableDictionary dictionary];+ return self;+}++- (void)viewDidLoad {+ [super viewDidLoad];+ _intro = SGNote(@"JamesDSP's audio effects on everything Spotify plays. Unlike the rest of Mod Settings, changes here apply straight away.");+ self.tableView.tableHeaderView = _intro;+ [self buildCredits];+ self.tableView.tableFooterView = _credits;+}++// JamesDSP's author and where its two apps live, in the grey of a note with the names as links.+- (void)buildCredits {+ NSDictionary *grey = @{NSFontAttributeName: SGSubtitleFont(), NSForegroundColorAttributeName: SGGrey()};+ NSMutableAttributedString *text = [[NSMutableAttributedString alloc]+ initWithString:@"JamesDSP by James Fung (james34602). Its engine, libjamesdsp, is free software under the GPL.\n" attributes:grey];+ NSArray<NSArray<NSString *> *> *links = @[+ @[@"JamesDSPManager", @"https://github.com/james34602/JamesDSPManager"],+ @[@"RootlessJamesDSP", @"https://github.com/timschneeb/RootlessJamesDSP"],+ ];+ [links enumerateObjectsUsingBlock:^(NSArray<NSString *> *link, NSUInteger i, BOOL *stop) {+ if (i) [text appendAttributedString:[[NSAttributedString alloc] initWithString:@" · " attributes:grey]];+ NSMutableDictionary *linked = [grey mutableCopy];+ linked[NSLinkAttributeName] = [NSURL URLWithString:link[1]];+ [text appendAttributedString:[[NSAttributedString alloc] initWithString:link[0] attributes:linked]];+ }];+ _creditsText = [UITextView new];+ _creditsText.attributedText = text;+ _creditsText.editable = NO;+ _creditsText.scrollEnabled = NO;+ _creditsText.backgroundColor = UIColor.clearColor;+ _creditsText.textContainerInset = UIEdgeInsetsZero;+ _creditsText.textContainer.lineFragmentPadding = 0;+ _creditsText.linkTextAttributes = @{NSForegroundColorAttributeName: UIColor.whiteColor};+ _credits = [UIView new];+ [_credits addSubview:_creditsText];+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ SGFitNote(self.tableView, _intro, 24, 0);+ // SGFitNote's way, for a text view rather than a label.+ UITableView *table = self.tableView;+ CGFloat inset = table.layoutMargins.left, width = table.bounds.size.width - 2 * inset;+ CGFloat height = ceil([_creditsText sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)].height);+ _creditsText.frame = CGRectMake(inset, 16, width, height);+ CGSize size = CGSizeMake(table.bounds.size.width, 16 + height + 24);+ if (CGSizeEqualToSize(_credits.bounds.size, size)) return;+ _credits.frame = (CGRect){_credits.frame.origin, size};+ table.tableFooterView = _credits;+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ SGInsetForBars(self.tableView);+}++- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ // A choice, a file or the GraphicEQ text may have changed on the page this one opened.+ [self readState];+ [self.tableView reloadData];+ // A cancelled back swipe appears the page again without it ever disappearing, so the old timer goes first.+ [_ticker invalidate];+ _ticker = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tick) userInfo:nil repeats:YES];+}++- (void)viewDidDisappear:(BOOL)animated {+ [super viewDidDisappear:animated];+ [_ticker invalidate];+ _ticker = nil;+}++- (void)readState {+ [_open removeAllObjects];+ [_errors removeAllObjects];+ for (SGDSPEffect *e in _effects) {+ if (!e.key || SGDSPSwitch(e.key)) [_open addObject:e.key ?: @""];+ if (e.key && SGDSPSwitch(e.key) && [reportingEffects() containsObject:e.key]) _errors[e.key] = SGDSPError(e.key);+ }+}++#pragma mark - rows++// Section 0 is JamesDSP's switch, then a card per effect, then the reset.+- (SGDSPEffect *)effectIn:(NSInteger)section {+ return section >= 1 && section <= (NSInteger)_effects.count ? _effects[(NSUInteger)section - 1] : nil;+}++- (BOOL)isOpen:(SGDSPEffect *)e {+ return [_open containsObject:e.key ?: @""];+}++- (NSInteger)rowCountOf:(SGDSPEffect *)e {+ if (![self isOpen:e]) return 1;+ return 1 + (NSInteger)e.rows.count + (e.key && _errors[e.key] ? 1 : 0);+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {+ return (NSInteger)_effects.count + 2;+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ SGDSPEffect *e = [self effectIn:section];+ return e ? [self rowCountOf:e] : 1;+}++// No views, but asked for all the same: without them the table keeps its own spacing, not the heights below.+- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {+ return SGSectionGap;+}++- (UIView *)tableView:(UITableView *)table viewForFooterInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForFooterInSection:(NSInteger)section {+ return CGFLOAT_MIN;+}++- (SGDSPRow *)rowAt:(NSIndexPath *)path {+ SGDSPEffect *e = [self effectIn:path.section];+ if (!e || path.row == 0 || path.row > (NSInteger)e.rows.count) return nil;+ return e.rows[(NSUInteger)path.row - 1];+}++- (CGFloat)tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {+ // The heads, the values and the errors size themselves; a nil row would read as a slider.+ SGDSPRow *row = [self rowAt:path];+ if (!row) return UITableViewAutomaticDimension;+ if (row.kind == SGDSPRowSlider) return 74;+ if (row.kind == SGDSPRowCurve) return [SGDSPCurveView heightForKey:row.key];+ return UITableViewAutomaticDimension;+}++- (UISwitch *)switchOn:(BOOL)on action:(SEL)action tag:(NSInteger)tag {+ UISwitch *toggle = [UISwitch new];+ toggle.onTintColor = SGGreen();+ toggle.on = on;+ toggle.tag = tag;+ [toggle addTarget:self action:action forControlEvents:UIControlEventValueChanged];+ return toggle;+}++- (void)fillHead:(UITableViewCell *)cell title:(NSString *)title subtitle:(NSString *)subtitle symbol:(NSString *)symbol {+ SGFillCell(cell, title, subtitle, nil, nil);+ UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;+ content.image = SGTileImage(symbol);+ content.imageToTextPadding = 14;+ content.secondaryTextProperties.numberOfLines = 1;+ cell.contentConfiguration = content;+ cell.separatorInset = UIEdgeInsetsMake(0, 58, 0, 0);+}++- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ if (path.section == 0) {+ UITableViewCell *cell = SGDequeueCell(table, @"master");+ [self fillHead:cell title:@"JamesDSP" subtitle:SGDSPStatus() symbol:@"waveform"];+ cell.accessoryView = [self switchOn:SGDSPSwitch(SGKeyDSP) action:@selector(masterToggled:) tag:0];+ return cell;+ }+ SGDSPEffect *e = [self effectIn:path.section];+ if (!e) {+ UITableViewCell *cell = SGDequeueCell(table, @"reset");+ SGFillCell(cell, @"Reset all effects", @"Every effect off, every value back to its default", SGRed(), @"arrow.counterclockwise");+ UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;+ content.secondaryTextProperties.color = SGRed();+ cell.contentConfiguration = content;+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ cell.separatorInset = UIEdgeInsetsMake(0, 48, 0, 0);+ return cell;+ }+ if (path.row == 0) {+ UITableViewCell *cell = SGDequeueCell(table, @"effect");+ [self fillHead:cell title:e.title subtitle:e.subtitle symbol:e.symbol];+ if (e.key) cell.accessoryView = [self switchOn:SGDSPSwitch(e.key) action:@selector(effectToggled:) tag:path.section];+ return cell;+ }+ SGDSPRow *row = [self rowAt:path];+ if (!row) return [self errorCell:table text:_errors[e.key]];+ switch (row.kind) {+ case SGDSPRowSlider: {+ SGDSPSliderCell *cell = [table dequeueReusableCellWithIdentifier:@"slider"] ?: [[SGDSPSliderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"slider"];+ cell.backgroundColor = SGCardBackground();+ [cell showRow:row];+ return cell;+ }+ case SGDSPRowCurve: {+ SGDSPCurveCell *cell = [table dequeueReusableCellWithIdentifier:row.key];+ if (!cell) {+ cell = [[SGDSPCurveCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:row.key];+ cell.selectionStyle = UITableViewCellSelectionStyleNone;+ cell.curve = [[SGDSPCurveView alloc] initWithKey:row.key];+ [cell.contentView addSubview:cell.curve];+ }+ cell.backgroundColor = SGCardBackground();+ [cell.curve reload];+ return cell;+ }+ case SGDSPRowChoice: {+ NSInteger index = (NSInteger)lround(SGDSPNumber(row.key));+ NSString *name = index >= 0 && index < (NSInteger)row.names.count ? row.names[(NSUInteger)index] : row.names.firstObject;+ return [self valueCell:table title:row.title value:name];+ }+ case SGDSPRowPage:+ return [self valueCell:table title:row.title value:row.value()];+ }+ return SGDequeueCell(table, @"row");+}++// The value on the right beside the chevron where it fits next to the title, and under the title+// where it does not: the compressor's transforms are longer than a narrow phone has room for.+- (UITableViewCell *)valueCell:(UITableView *)table title:(NSString *)title value:(NSString *)value {+ UITableViewCell *cell = SGDequeueCell(table, @"value");+ CGFloat card = table.bounds.size.width - table.layoutMargins.left - table.layoutMargins.right;+ UIView *accessory = valueAndChevron(value);+ CGFloat titleWidth = ceil([title sizeWithAttributes:@{NSFontAttributeName: SGTitleFont()}].width);+ BOOL fits = 16 + titleWidth + 16 + accessory.bounds.size.width + 16 <= card;+ SGFillCell(cell, title, fits ? nil : value, nil, nil);+ cell.accessoryView = fits ? accessory : SGSymbolView(@"chevron.right", 13, UIImageSymbolWeightSemibold, 16);+ cell.accessibilityValue = value;+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ cell.separatorInset = UIEdgeInsetsMake(0, 16, 0, 0);+ return cell;+}++// Red, the way Settings' warning rows are: the effect's last change did not take, and why.+- (UITableViewCell *)errorCell:(UITableView *)table text:(NSString *)text {+ UITableViewCell *cell = SGDequeueCell(table, @"error");+ SGFillCell(cell, @"Not applied", text, SGRed(), @"exclamationmark.triangle.fill");+ UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;+ content.secondaryTextProperties.color = SGRed();+ cell.contentConfiguration = content;+ cell.separatorInset = UIEdgeInsetsMake(0, 48, 0, 0);+ return cell;+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ if (path.section == (NSInteger)_effects.count + 1) {+ [self confirmReset];+ return;+ }+ SGDSPRow *row = [self rowAt:path];+ if (!row) return;+ if (row.kind == SGDSPRowChoice) [self.navigationController pushViewController:[[SGDSPChoicePage alloc] initWithRow:row] animated:YES];+ else if (row.kind == SGDSPRowPage) [self.navigationController pushViewController:row.page() animated:YES];+}++- (BOOL)tableView:(UITableView *)table shouldHighlightRowAtIndexPath:(NSIndexPath *)path {+ if (path.section == (NSInteger)_effects.count + 1) return YES;+ SGDSPRow *row = [self rowAt:path];+ return row && (row.kind == SGDSPRowChoice || row.kind == SGDSPRowPage);+}++#pragma mark - changes++- (void)masterToggled:(UISwitch *)toggle {+ SGDSPSetSwitch(SGKeyDSP, toggle.on);+ [self showStatus];+}++// The effect's rows come in under its switch, or go, rather than the page reloading around them; then the+// card is scrolled into view, as much of it as the screen holds.+- (void)effectToggled:(UISwitch *)toggle {+ NSInteger section = toggle.tag;+ SGDSPEffect *e = [self effectIn:section];+ if (!e.key) return;+ SGDSPSetSwitch(e.key, toggle.on);+ UITableView *table = self.tableView;+ NSInteger before = [self rowCountOf:e];+ [table performBatchUpdates:^{+ if (toggle.on) [self->_open addObject:e.key];+ else [self->_open removeObject:e.key];+ self->_errors[e.key] = toggle.on && [reportingEffects() containsObject:e.key] ? SGDSPError(e.key) : nil;+ NSInteger after = [self rowCountOf:e];+ NSMutableArray<NSIndexPath *> *paths = [NSMutableArray array];+ for (NSInteger i = 1; i < MAX(before, after); i++) [paths addObject:[NSIndexPath indexPathForRow:i inSection:section]];+ if (after > before) [table insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];+ else if (after < before) [table deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];+ } completion:^(BOOL finished) {+ if (!toggle.on) return;+ CGRect card = [table rectForSection:section];+ CGFloat room = table.bounds.size.height - table.adjustedContentInset.top - table.adjustedContentInset.bottom;+ card.size.height = MIN(card.size.height, room);+ [table scrollRectToVisible:card animated:YES];+ }];+}++// Once a second while the page shows: what the engine is doing, and whether an effect's change failed.+- (void)tick {+ [self showStatus];+ UITableView *table = self.tableView;+ [_effects enumerateObjectsUsingBlock:^(SGDSPEffect *e, NSUInteger i, BOOL *stop) {+ if (![reportingEffects() containsObject:e.key] || ![self isOpen:e]) return;+ NSString *shown = self->_errors[e.key], *now = SGDSPError(e.key);+ if (shown == now || [shown isEqualToString:now]) return;+ NSIndexPath *path = [NSIndexPath indexPathForRow:1 + (NSInteger)e.rows.count inSection:(NSInteger)i + 1];+ [table performBatchUpdates:^{+ self->_errors[e.key] = now;+ if (shown && now) [table reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];+ else if (now) [table insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];+ else [table deleteRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];+ } completion:nil];+ }];+}++// Written into the cell rather than reloaded, so the switch beside it is never swapped under a finger.+- (void)showStatus {+ UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];+ UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;+ NSString *status = SGDSPStatus();+ if (!content || [content.secondaryText isEqualToString:status]) return;+ content.secondaryText = status;+ cell.contentConfiguration = content;+}++- (void)confirmReset {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Reset all effects?"+ message:@"Every effect goes off, and every value, curve and file choice back to its default. JamesDSP's own switch and your imported files stay."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"Reset" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {+ SGDSPResetAll();+ [self readState];+ [UIView transitionWithView:self.tableView duration:0.25 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{+ [self.tableView reloadData];+ } completion:nil];+ }]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+}++@end++UIViewController *SGDSPSettingsPage(void) {+ return [SGDSPPage new];+}diff --git a/tweak/Sources/Shared/JamesDSP/SGDSPCurveView.h b/tweak/Sources/Shared/JamesDSP/SGDSPCurveView.hnew file mode 100644index 00000000..bb77b88b--- /dev/null+++ b/tweak/Sources/Shared/JamesDSP/SGDSPCurveView.h@@ -0,0 +1,14 @@+// The equalizer's 15 bands or the compressor's 7 points, drawn as the response they make over a grid of+// their range, with a handle per band: dragged up and down it stores as it moves, a double tap puts it back+// to zero, and VoiceOver adjusts it a step at a time. Over it, Reset, and for the equalizer JamesDSP's+// presets in a pull-down named after the one the bands match.+#import <UIKit/UIKit.h>++@interface SGDSPCurveView : UIView+// SGKeyDSPEqualizerGains or SGKeyDSPCompanderGains.+- (instancetype)initWithKey:(NSString *)key;+// The stored gains again, and the curve for the stored filter type.+- (void)reload;+// The height the table gives its row.++ (CGFloat)heightForKey:(NSString *)key;+@enddiff --git a/tweak/Sources/Shared/JamesDSP/SGDSPCurveView.m b/tweak/Sources/Shared/JamesDSP/SGDSPCurveView.mnew file mode 100644index 00000000..bc44fd43--- /dev/null+++ b/tweak/Sources/Shared/JamesDSP/SGDSPCurveView.m@@ -0,0 +1,566 @@+#import "Core/SGCore.h"+#import "Settings/SGPageStyle.h"+#import "SGDSPCurveView.h"+#import "JamesDSP.h"++enum { kPoints = 128 }; // along the curve, log spaced from 20 Hz to 20 kHz+static const CGFloat kBarHeight = 36; // the presets and Reset, over the plot+static const CGFloat kInset = 9; // above the top line and under the bottom one, where a handle at the limit sits+static const CGFloat kLabelsHeight = 26; // the bands' frequencies under the plot+static const CGFloat kSide = 16; // the row's margins, the same as the text rows'+static const CGFloat kGutter = 22; // the scale's numbers, right of the plot+static const CGFloat kGrab = 28; // how far above or below a handle a finger still takes it+static const CGFloat kHandle = 11; // a handle's diameter; the one being dragged grows++// "25", "630", "1.6k", "16k", the way JamesDSP labels its bands.+static NSString *bandName(double hz) {+ return hz < 1000 ? [NSString stringWithFormat:@"%g", hz] : [NSString stringWithFormat:@"%gk", hz / 1000];+}++static NSString *spokenBand(double hz) {+ return hz < 1000 ? [NSString stringWithFormat:@"%g hertz", hz] : [NSString stringWithFormat:@"%g kilohertz", hz / 1000];+}++// A real minus, and no sign on zero.+static NSString *signedNumber(double value, int decimals) {+ NSString *text = [NSString stringWithFormat:@"%.*f", decimals, fabs(value)];+ if (text.doubleValue == 0) return text;+ return [(value < 0 ? @"−" : @"+") stringByAppendingString:text];+}++@class SGDSPCurveView;++// A band as VoiceOver has it: adjustable, a step at a time, reading its gain out.+@interface SGDSPBandElement : UIAccessibilityElement+@property (nonatomic) NSInteger band;+@end++@interface SGDSPCurveView () <UIGestureRecognizerDelegate>+- (void)nudgeBand:(NSInteger)band by:(NSInteger)steps;+- (NSString *)spokenGainOf:(NSInteger)band;+@end++@implementation SGDSPBandElement++- (NSString *)accessibilityValue {+ return [(SGDSPCurveView *)self.accessibilityContainer spokenGainOf:self.band];+}++- (void)accessibilityIncrement {+ [(SGDSPCurveView *)self.accessibilityContainer nudgeBand:self.band by:1];+}++- (void)accessibilityDecrement {+ [(SGDSPCurveView *)self.accessibilityContainer nudgeBand:self.band by:-1];+}++@end++@implementation SGDSPCurveView {+ NSString *_key;+ BOOL _equalizer;+ const double *_bands;+ NSInteger _count;+ double _limit; // the gains run from -_limit to _limit+ double _step; // what a drag moves a gain by+ double _spokenStep; // what VoiceOver's swipe does+ int _decimals;+ NSString *_unit;+ NSMutableArray<NSNumber *> *_gains;++ CALayer *_plot; // the curve and its fill, cut off at the plot's edges+ CAShapeLayer *_grid, *_zero, *_fill, *_curve;+ NSMutableArray<CAShapeLayer *> *_handles;+ NSMutableArray<UILabel *> *_bandLabels;+ NSMutableArray<UILabel *> *_scale;+ UIButton *_presets, *_reset;+ UILabel *_name; // the compressor's, where the equalizer has its presets+ UILabel *_bubble;+ NSMutableArray<SGDSPBandElement *> *_elements;++ NSInteger _touched; // the band under the finger that went down, -1 for none+ NSInteger _dragging; // the band being dragged, -1 for none+ CGFloat _offset; // from the finger to the handle's centre, kept through the drag+ UISelectionFeedbackGenerator *_detent;+}+++ (CGFloat)heightForKey:(NSString *)key {+ CGFloat plot = [key isEqualToString:SGKeyDSPCompanderGains] ? 112 : 144;+ return kBarHeight + kInset + plot + kInset + kLabelsHeight;+}++- (instancetype)initWithKey:(NSString *)key {+ if (!(self = [super initWithFrame:CGRectZero])) return nil;+ _key = key;+ _equalizer = ![key isEqualToString:SGKeyDSPCompanderGains];+ _bands = _equalizer ? SGDSPEqualizerFrequencies : SGDSPCompanderFrequencies;+ _count = _equalizer ? 15 : 7;+ _limit = _equalizer ? SGDSPEqualizerGainLimit : SGDSPCompanderGainLimit;+ _step = _equalizer ? 0.1 : 0.01;+ _spokenStep = _equalizer ? 0.5 : 0.1;+ _decimals = _equalizer ? 1 : 2;+ _unit = _equalizer ? @" dB" : @"";+ _touched = _dragging = -1;+ _detent = [UISelectionFeedbackGenerator new];++ _grid = [self lineLayer:[UIColor colorWithWhite:1 alpha:0.08]];+ _zero = [self lineLayer:[UIColor colorWithWhite:1 alpha:0.24]];+ _plot = [CALayer layer];+ _plot.mask = [CALayer layer];+ _plot.mask.backgroundColor = UIColor.blackColor.CGColor;+ [self.layer addSublayer:_plot];+ _fill = [CAShapeLayer layer];+ _curve = [CAShapeLayer layer];+ _curve.fillColor = nil;+ _curve.lineWidth = 2;+ _curve.lineJoin = kCALineJoinRound;+ _curve.lineCap = kCALineCapRound;+ [_plot addSublayer:_fill];+ [_plot addSublayer:_curve];++ _scale = [NSMutableArray array];+ for (NSNumber *value in @[@(_limit), @0, @(-_limit)]) {+ UILabel *label = [self smallLabel];+ label.text = signedNumber(value.doubleValue, value.doubleValue == 0 || _equalizer ? 0 : 1);+ label.textAlignment = NSTextAlignmentRight;+ [_scale addObject:label];+ }++ _handles = [NSMutableArray array];+ _bandLabels = [NSMutableArray array];+ _elements = [NSMutableArray array];+ for (NSInteger i = 0; i < _count; i++) {+ CAShapeLayer *handle = [CAShapeLayer layer];+ handle.bounds = CGRectMake(0, 0, kHandle, kHandle);+ handle.path = [UIBezierPath bezierPathWithOvalInRect:handle.bounds].CGPath;+ handle.fillColor = UIColor.whiteColor.CGColor;+ handle.shadowColor = UIColor.blackColor.CGColor;+ handle.shadowOpacity = 0.35;+ handle.shadowRadius = 2;+ handle.shadowOffset = CGSizeMake(0, 1);+ [self.layer addSublayer:handle];+ [_handles addObject:handle];++ UILabel *label = [self smallLabel];+ label.text = bandName(_bands[i]);+ label.textAlignment = NSTextAlignmentCenter;+ [_bandLabels addObject:label];++ SGDSPBandElement *element = [[SGDSPBandElement alloc] initWithAccessibilityContainer:self];+ element.band = i;+ element.accessibilityLabel = spokenBand(_bands[i]);+ element.accessibilityTraits = UIAccessibilityTraitAdjustable;+ element.accessibilityHint = @"Double tap and hold, then drag up or down, or swipe up or down to adjust.";+ [_elements addObject:element];+ }++ _bubble = [UILabel new];+ _bubble.font = [UIFont monospacedDigitSystemFontOfSize:12 weight:UIFontWeightSemibold];+ _bubble.textColor = UIColor.whiteColor;+ _bubble.textAlignment = NSTextAlignmentCenter;+ _bubble.backgroundColor = [UIColor colorWithWhite:0.32 alpha:1];+ _bubble.layer.cornerRadius = 7;+ _bubble.layer.cornerCurve = kCACornerCurveContinuous;+ _bubble.clipsToBounds = YES;+ _bubble.alpha = 0;+ _bubble.isAccessibilityElement = NO;+ [self addSubview:_bubble];++ _reset = [self barButton:@"Reset" color:SGGrey()];+ [_reset addTarget:self action:@selector(resetTapped) forControlEvents:UIControlEventTouchUpInside];+ _reset.accessibilityHint = _equalizer ? @"Every band back to zero." : @"Every point back to zero.";+ if (_equalizer) {+ _presets = [self barButton:@"Custom" color:UIColor.whiteColor];+ UIButtonConfiguration *config = _presets.configuration;+ config.image = [UIImage systemImageNamed:@"chevron.up.chevron.down" withConfiguration:[UIImageSymbolConfiguration configurationWithPointSize:10 weight:UIImageSymbolWeightSemibold]];+ config.imagePlacement = NSDirectionalRectEdgeTrailing;+ config.imagePadding = 5;+ _presets.configuration = config;+ _presets.showsMenuAsPrimaryAction = YES;+ _presets.accessibilityLabel = @"Preset";+ } else {+ _name = [UILabel new];+ _name.text = @"Response";+ _name.textColor = UIColor.whiteColor;+ _name.accessibilityTraits = UIAccessibilityTraitHeader;+ [self addSubview:_name];+ }++ UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panned:)];+ pan.delegate = self;+ [self addGestureRecognizer:pan];+ UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapped:)];+ doubleTap.numberOfTapsRequired = 2;+ doubleTap.delegate = self;+ [self addGestureRecognizer:doubleTap];++ [self reload];+ return self;+}++- (CAShapeLayer *)lineLayer:(UIColor *)color {+ CAShapeLayer *layer = [CAShapeLayer layer];+ layer.strokeColor = color.CGColor;+ layer.fillColor = nil;+ layer.lineWidth = 1 / UIScreen.mainScreen.scale;+ [self.layer addSublayer:layer];+ return layer;+}++// Condensed, so fifteen of them fit under the bands of a 375pt phone with room between them.+- (UILabel *)smallLabel {+ UILabel *label = [UILabel new];+ label.font = [UIFont systemFontOfSize:9.5 weight:UIFontWeightMedium width:UIFontWidthCondensed];+ label.textColor = SGGrey();+ label.isAccessibilityElement = NO;+ [self addSubview:label];+ return label;+}++- (UIButton *)barButton:(NSString *)title color:(UIColor *)color {+ UIButtonConfiguration *config = [UIButtonConfiguration plainButtonConfiguration];+ config.contentInsets = NSDirectionalEdgeInsetsZero;+ config.baseForegroundColor = color;+ config.titleTextAttributesTransformer = ^NSDictionary *(NSDictionary *attributes) {+ NSMutableDictionary *styled = [attributes mutableCopy];+ styled[NSFontAttributeName] = SGTitleFont();+ return styled;+ };+ config.title = title;+ config.titleLineBreakMode = NSLineBreakByTruncatingTail;+ UIButton *button = [UIButton buttonWithConfiguration:config primaryAction:nil];+ button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeading;+ [self addSubview:button];+ return button;+}++#pragma mark - geometry++// Where the grid's top and bottom lines run: the limits.+- (CGRect)plotRect {+ CGSize size = self.bounds.size;+ CGFloat top = kBarHeight + kInset, bottom = size.height - kLabelsHeight - kInset;+ return CGRectMake(kSide, top, MAX(size.width - kSide - kGutter - kSide, 1), MAX(bottom - top, 1));+}++- (CGFloat)xFor:(double)hz {+ CGRect plot = [self plotRect];+ return CGRectGetMinX(plot) + log(hz / 20) / log(1000) * plot.size.width;+}++- (CGFloat)yFor:(double)value {+ CGRect plot = [self plotRect];+ return CGRectGetMidY(plot) - value / _limit * plot.size.height / 2;+}++- (double)valueFor:(CGFloat)y {+ CGRect plot = [self plotRect];+ double value = -(y - CGRectGetMidY(plot)) / (plot.size.height / 2) * _limit;+ value = round(value / _step) * _step;+ return MAX(-_limit, MIN(_limit, value));+}++// Half the distance between two bands, but never so thin that a finger misses.+- (CGFloat)reach {+ return MAX(([self xFor:_bands[1]] - [self xFor:_bands[0]]) / 2, 12);+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGRect plot = [self plotRect];+ CGFloat width = self.bounds.size.width;++ [_reset sizeToFit];+ _reset.frame = CGRectMake(width - kSide - _reset.bounds.size.width, 0, _reset.bounds.size.width, kBarHeight);+ // Measured here: a button's configuration catches up with a new title only on its next pass, so+ // sizeToFit would still be fitting the old name.+ if (_presets) {+ NSString *title = _presets.configuration.title ?: @"";+ CGFloat needed = ceil([title sizeWithAttributes:@{NSFontAttributeName: SGTitleFont()}].width) + 5 + 12;+ _presets.frame = CGRectMake(kSide, 0, MIN(needed, width / 2), kBarHeight);+ }+ _name.font = SGTitleFont();+ _name.frame = CGRectMake(kSide, 0, width / 2, kBarHeight);++ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ UIBezierPath *grid = [UIBezierPath bezierPath];+ for (NSNumber *value in @[@(_limit), @(_limit / 2), @(-_limit / 2), @(-_limit)]) {+ CGFloat y = [self yFor:value.doubleValue];+ [grid moveToPoint:CGPointMake(CGRectGetMinX(plot), y)];+ [grid addLineToPoint:CGPointMake(CGRectGetMaxX(plot), y)];+ }+ _grid.path = grid.CGPath;+ UIBezierPath *zero = [UIBezierPath bezierPath];+ [zero moveToPoint:CGPointMake(CGRectGetMinX(plot), [self yFor:0])];+ [zero addLineToPoint:CGPointMake(CGRectGetMaxX(plot), [self yFor:0])];+ _zero.path = zero.CGPath;+ _plot.frame = self.bounds;+ _plot.mask.frame = CGRectInset(plot, 0, -kInset);+ [CATransaction commit];++ NSArray<NSNumber *> *levels = @[@(_limit), @0, @(-_limit)];+ [_scale enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger i, BOOL *stop) {+ label.frame = CGRectMake(CGRectGetMaxX(plot), [self yFor:levels[i].doubleValue] - 6, kGutter, 12);+ }];+ CGFloat reach = [self reach];+ [_bandLabels enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger i, BOOL *stop) {+ CGFloat x = [self xFor:self->_bands[i]];+ label.frame = CGRectMake(x - 16, CGRectGetMaxY(plot) + kInset + 5, 32, 12);+ self->_elements[i].accessibilityFrameInContainerSpace = CGRectMake(x - reach, CGRectGetMinY(plot) - kInset, reach * 2, plot.size.height + 2 * kInset);+ }];+ [self redrawAnimated:NO];+}++#pragma mark - drawing++- (void)reload {+ _gains = [SGDSPGains(_key) mutableCopy];+ [self redrawAnimated:NO];+ [self refreshBar];+}++- (void)tintColorDidChange {+ [super tintColorDidChange];+ [self paint];+}++- (void)didMoveToWindow {+ [super didMoveToWindow];+ [self paint];+}++// The accent colour is read each time the row shows, so a colour picked since shows here too.+- (void)paint {+ UIColor *accent = SGGreen();+ _curve.strokeColor = accent.CGColor;+ _fill.fillColor = [accent colorWithAlphaComponent:0.16].CGColor;+}++- (void)redrawAnimated:(BOOL)animated {+ if (CGRectIsEmpty(self.bounds)) return;+ double frequencies[kPoints], values[kPoints];+ if (_equalizer) SGDSPEqualizerResponse(_gains, kPoints, frequencies, values);+ else SGDSPCompanderResponse(_gains, kPoints, frequencies, values);++ // Past the plot's edges the mask cuts the curve off; points kept near them keep a runaway value+ // from stretching the path.+ CGRect plot = [self plotRect];+ CGFloat low = CGRectGetMinY(plot) - 40, high = CGRectGetMaxY(plot) + 40, zero = [self yFor:0];+ UIBezierPath *line = [UIBezierPath bezierPath], *area = [UIBezierPath bezierPath];+ for (NSInteger i = 0; i < kPoints; i++) {+ double hz = isfinite(frequencies[i]) && frequencies[i] > 0 ? frequencies[i] : 20 * pow(1000, (double)i / (kPoints - 1));+ double value = isfinite(values[i]) ? values[i] : 0;+ CGPoint point = CGPointMake([self xFor:hz], MAX(low, MIN(high, [self yFor:value])));+ if (i == 0) {+ [line moveToPoint:point];+ [area moveToPoint:CGPointMake(point.x, zero)];+ } else {+ [line addLineToPoint:point];+ }+ [area addLineToPoint:point];+ if (i == kPoints - 1) [area addLineToPoint:CGPointMake(point.x, zero)];+ }+ [area closePath];++ // A shape layer's path has no implicit animation, so the curve morphs by hand, from wherever it is+ // now; the handles are plain layers and slide on their own.+ CAMediaTimingFunction *easing = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];+ if (animated) {+ [self morph:_curve to:line timing:easing];+ [self morph:_fill to:area timing:easing];+ }+ [CATransaction begin];+ if (animated) {+ [CATransaction setAnimationDuration:0.35];+ [CATransaction setAnimationTimingFunction:easing];+ } else {+ [CATransaction setDisableActions:YES];+ }+ _curve.path = line.CGPath;+ _fill.path = area.CGPath;+ [_handles enumerateObjectsUsingBlock:^(CAShapeLayer *handle, NSUInteger i, BOOL *stop) {+ handle.position = CGPointMake([self xFor:self->_bands[i]], [self yFor:self->_gains[i].doubleValue]);+ }];+ [CATransaction commit];+}++- (void)morph:(CAShapeLayer *)layer to:(UIBezierPath *)path timing:(CAMediaTimingFunction *)timing {+ CABasicAnimation *morph = [CABasicAnimation animationWithKeyPath:@"path"];+ morph.fromValue = (__bridge id)(((CAShapeLayer *)layer.presentationLayer).path ?: layer.path);+ morph.toValue = (__bridge id)path.CGPath;+ morph.duration = 0.35;+ morph.timingFunction = timing;+ [layer addAnimation:morph forKey:@"morph"];+}++// The presets' name and menu and whether there is anything to reset, once a change is done.+- (void)refreshBar {+ BOOL flat = YES;+ for (NSNumber *gain in _gains) flat &= gain.doubleValue == 0;+ _reset.enabled = !flat;+ if (!_presets) return;+ NSArray<NSString *> *names = SGDSPEqualizerPresetNames();+ NSInteger match = [self matchingPreset];+ UIButtonConfiguration *config = _presets.configuration;+ config.title = match >= 0 ? names[(NSUInteger)match] : @"Custom";+ _presets.configuration = config;+ _presets.accessibilityValue = config.title;+ NSMutableArray<UIAction *> *actions = [NSMutableArray array];+ __weak typeof(self) weakSelf = self;+ [names enumerateObjectsUsingBlock:^(NSString *name, NSUInteger i, BOOL *stop) {+ UIAction *action = [UIAction actionWithTitle:name image:nil identifier:nil handler:^(UIAction *a) {+ [weakSelf setGains:SGDSPEqualizerPreset((NSInteger)i) animated:YES];+ }];+ action.state = (NSInteger)i == match ? UIMenuElementStateOn : UIMenuElementStateOff;+ [actions addObject:action];+ }];+ _presets.menu = [UIMenu menuWithTitle:@"JamesDSP presets" children:actions];+ [self setNeedsLayout];+}++// Stored to two decimals, so a preset matches to within that.+- (NSInteger)matchingPreset {+ NSArray<NSString *> *names = SGDSPEqualizerPresetNames();+ for (NSUInteger p = 0; p < names.count; p++) {+ NSArray<NSNumber *> *preset = SGDSPEqualizerPreset((NSInteger)p);+ BOOL same = preset.count == _gains.count;+ for (NSUInteger i = 0; same && i < preset.count; i++) same = fabs(preset[i].doubleValue - _gains[i].doubleValue) < 0.006;+ if (same) return (NSInteger)p;+ }+ return -1;+}++- (void)setGains:(NSArray<NSNumber *> *)gains animated:(BOOL)animated {+ if (gains.count != (NSUInteger)_count) return;+ _gains = [gains mutableCopy];+ SGDSPSetGains(_key, _gains);+ [self redrawAnimated:animated];+ [self refreshBar];+}++- (void)resetTapped {+ NSMutableArray<NSNumber *> *flat = [NSMutableArray array];+ for (NSInteger i = 0; i < _count; i++) [flat addObject:@0];+ [self setGains:flat animated:YES];+}++#pragma mark - dragging++- (NSString *)gainText:(double)gain {+ return [signedNumber(gain, _decimals) stringByAppendingString:_unit];+}++- (NSString *)spokenGainOf:(NSInteger)band {+ double gain = _gains[(NSUInteger)band].doubleValue;+ NSString *number = [NSString stringWithFormat:@"%.*f", _decimals, gain];+ return _equalizer ? [number stringByAppendingString:@" decibels"] : number;+}++// The band whose handle is under `point`: the nearest by frequency, if the finger is close enough to its+// handle. Anywhere else on the plot a drag scrolls the page instead.+- (NSInteger)bandAt:(CGPoint)point {+ NSInteger nearest = -1;+ CGFloat distance = CGFLOAT_MAX;+ for (NSInteger i = 0; i < _count; i++) {+ CGFloat dx = fabs(point.x - [self xFor:_bands[i]]);+ if (dx < distance) {+ distance = dx;+ nearest = i;+ }+ }+ if (nearest < 0 || distance > [self reach]) return -1;+ return fabs(point.y - [self yFor:_gains[(NSUInteger)nearest].doubleValue]) <= kGrab ? nearest : -1;+}++- (BOOL)gestureRecognizer:(UIGestureRecognizer *)recognizer shouldReceiveTouch:(UITouch *)touch {+ _touched = [self bandAt:[touch locationInView:self]];+ return _touched >= 0;+}++- (void)setBand:(NSInteger)band to:(double)value {+ double old = _gains[(NSUInteger)band].doubleValue;+ if (value == old) return;+ // A tick as a band crosses zero, where it does nothing, and at either end.+ if ((old < 0) != (value < 0) || (old > 0) != (value > 0) || fabs(value) == _limit) [_detent selectionChanged];+ _gains[(NSUInteger)band] = @(value);+ SGDSPSetGains(_key, _gains);+ [self redrawAnimated:NO];+}++- (void)showBubbleFor:(NSInteger)band {+ _bubble.text = [self gainText:_gains[(NSUInteger)band].doubleValue];+ CGSize size = [_bubble sizeThatFits:CGSizeZero];+ size = CGSizeMake(ceil(size.width) + 14, 22);+ CGPoint handle = _handles[(NSUInteger)band].position;+ CGFloat x = MAX(4, MIN(self.bounds.size.width - size.width - 4, handle.x - size.width / 2));+ // Above the handle, where the finger dragging it is not; under it when the handle is at the top.+ CGFloat y = handle.y - 20 - size.height;+ if (y < 2) y = handle.y + 20;+ _bubble.frame = (CGRect){{x, y}, size};+}++- (void)highlight:(NSInteger)band on:(BOOL)on {+ CAShapeLayer *handle = _handles[(NSUInteger)band];+ [CATransaction begin];+ [CATransaction setAnimationDuration:0.18];+ handle.transform = on ? CATransform3DMakeScale(1.6, 1.6, 1) : CATransform3DIdentity;+ [CATransaction commit];+ _bandLabels[(NSUInteger)band].textColor = on ? UIColor.whiteColor : SGGrey();+ [UIView animateWithDuration:0.18 animations:^{ self->_bubble.alpha = on ? 1 : 0; }];+}++- (void)panned:(UIPanGestureRecognizer *)pan {+ CGPoint point = [pan locationInView:self];+ switch (pan.state) {+ case UIGestureRecognizerStateBegan:+ if (_touched < 0) return;+ _dragging = _touched;+ _offset = _handles[(NSUInteger)_dragging].position.y - point.y;+ [_detent prepare];+ [self showBubbleFor:_dragging];+ [self highlight:_dragging on:YES];+ break;+ case UIGestureRecognizerStateChanged:+ if (_dragging < 0) return;+ [self setBand:_dragging to:[self valueFor:point.y + _offset]];+ [self showBubbleFor:_dragging];+ break;+ default:+ if (_dragging < 0) return;+ [self highlight:_dragging on:NO];+ _dragging = -1;+ [self refreshBar];+ break;+ }+}++- (void)doubleTapped:(UITapGestureRecognizer *)tap {+ NSInteger band = [self bandAt:[tap locationInView:self]];+ if (band < 0 || _gains[(NSUInteger)band].doubleValue == 0) return;+ _gains[(NSUInteger)band] = @0;+ [self setGains:_gains animated:YES];+}++- (void)nudgeBand:(NSInteger)band by:(NSInteger)steps {+ double value = _gains[(NSUInteger)band].doubleValue + steps * _spokenStep;+ value = MAX(-_limit, MIN(_limit, round(value / _step) * _step));+ [self setBand:band to:value];+ [self refreshBar];+}++#pragma mark - accessibility++- (BOOL)isAccessibilityElement {+ return NO;+}++- (NSArray *)accessibilityElements {+ NSMutableArray *elements = [NSMutableArray array];+ [elements addObject:_presets ?: _name];+ [elements addObject:_reset];+ [elements addObjectsFromArray:_elements];+ return elements;+}++@end