Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Font offers iOS families and imports a whole family from Files
My-Name-Is-Jeff1ee10bf5dd72
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 4100d0d5..5d9edfec 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -592,9 +592,13 @@ preset, a pull-down of Spotify, Apple Music and Custom read off the colour storeexisted reads as Custom, Apple Music's red as Apple Music), and Accent colour, the hex and a swatch of the colour ineffect, which opens the system picker in a sheet that stores only from its checkmark, as Custom. The custom colour iskept aside while a preset is in place, so Custom brings it back. Last come the Font, under either look and on any-iOS, below 26 too, with Custom font among its choices (a .ttf or .otf imported from Files by the row under it,-copied to Application Support/Vitrine/Font and registered again at each launch, Spotify's font coming back when the-file is gone), and the App icon. Everything on the page applies after a restart. Redesigned UI, the main page's+iOS, below 26 too, a page of its own with each choice drawn in itself: Default (Spotify's), San Francisco, SF+Rounded, New York and SF Mono; More fonts, the families iOS carries of a fixed few (Avenir Next to American+Typewriter), each weight taken as the family's nearest face; and Your fonts, the files of one family (.ttf, .otf, .ttc or .otc, picked+together) added from Files, refused when their faces name more than one family, copied to Application Support/Vitrine/Font+and registered again at each launch, each weight taken as the family's nearest face, Spotify's font coming back when+the files are gone. Swiping the row deletes the family. An import from before families (one file under+spotifyglass.font.file) moves to spotifyglass.font.files and the family name on first use. Then the App icon. Everything on the page applies after a restart. Redesigned UI, the main page'sfirst row, is the one switch between the two looks (see Layers): it glows (Settings/SGGlowSwitch), its ⓘ says whatit changes, and flipping it offers to restart Spotify. The pages show only what the stored look has: a page openedafter flipping the switch already shows what the restart will bring, and the main page swaps Home & Library anddiff --git a/harness/appearance-page/main.m b/harness/appearance-page/main.mindex 96171d17..ceaada87 100644--- a/harness/appearance-page/main.m+++ b/harness/appearance-page/main.m@@ -10,7 +10,7 @@// cleared first), redesign (the redesign's rows), accent=<hex|-1>, raccent=<hex|-1>, font=<n>.// Actions: open=<section>.<row> (the row's menu opened as a tap does), menu=<section>.<row>:<n> (its nth item// picked), select=<section>.<row> (a tap on the row), color=<hex> (the open picker moved there), confirm (its-// checkmark), close (the sheet dismissed without it), import=<path> (that file handed to the font import as+// checkmark), close (the sheet dismissed without it), import=<path,path> (those files handed to the font import as// Files would), dismiss (whatever is presented goes), dump (the stored keys and every row with what it reads).#import <UIKit/UIKit.h>#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>@@ -50,6 +50,13 @@ static NSInteger hex(NSString *text) {- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {NSArray<NSString *> *args = NSProcessInfo.processInfo.arguments;NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ // The family grouping the font import goes by: one shared name passes, a mix, a missing name or no face does not.+ NSCAssert([SGFontSingleFamily(@[@"Inter", @"Inter", @"Inter"]) isEqualToString:@"Inter"], @"one family");+ NSCAssert([SGFontSingleFamily(@[@"Inter"]) isEqualToString:@"Inter"], @"one face");+ NSCAssert(!SGFontSingleFamily(@[@"Inter", @"Lato"]), @"two families");+ NSCAssert(!SGFontSingleFamily(@[@"Inter", @""]), @"a face without a family");+ NSCAssert(!SGFontSingleFamily(@[]), @"no faces");+ NSLog(@"[harness] family grouping ok");if (![args containsObject:@"keep"]) {for (NSString *key in store.dictionaryRepresentation.allKeys) {if ([key hasPrefix:@"spotifyglass.accent"] || [key hasPrefix:@"spotifyglass.redesign.accent"] || [key hasPrefix:@"spotifyglass.font"] ||@@ -128,7 +135,13 @@ static NSInteger hex(NSString *text) {[self.nav dismissViewControllerAnimated:YES completion:nil];} else if ([verb isEqualToString:@"import"]) {id picker = [NSClassFromString(@"SGFontPicker") new];- [picker documentPicker:[[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[UTTypeFont] asCopy:YES] didPickDocumentsAtURLs:@[[NSURL fileURLWithPath:value]]];+ NSMutableArray<NSURL *> *urls = [NSMutableArray array];+ for (NSString *path in [value componentsSeparatedByString:@","]) [urls addObject:[NSURL fileURLWithPath:path]];+ [picker documentPicker:[[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[UTTypeFont] asCopy:YES] didPickDocumentsAtURLs:urls];+ } else if ([verb isEqualToString:@"delete"]) {+ UIContextualAction *action = [table.delegate tableView:table trailingSwipeActionsConfigurationForRowAtIndexPath:[self pathFrom:value]].actions.firstObject;+ NSLog(@"[harness] swipe on %@ offers %@", value, action.title ?: @"nothing");+ if (action) action.handler(action, [UIView new], ^(BOOL done) {});} else if ([verb isEqualToString:@"dump"]) {NSDictionary *all = NSUserDefaults.standardUserDefaults.dictionaryRepresentation;for (NSString *key in [all.allKeys sortedArrayUsingSelector:@selector(compare:)]) {diff --git a/harness/appearance-page/stubs.m b/harness/appearance-page/stubs.mindex d05475f4..4753c07e 100644--- a/harness/appearance-page/stubs.m+++ b/harness/appearance-page/stubs.m@@ -16,9 +16,13 @@ NSInteger SGRAccentRGB(void) { NSInteger rgb = valid(SGInt(SGRKeyAccent, SGRDefaSGAppFont SGAppFontChosen(void) {NSInteger font = SGInt(SGKeyAppFont, SGAppFontSpotify);- return font >= SGAppFontSpotify && font <= SGAppFontCustom ? font : SGAppFontSpotify;+ return font >= SGAppFontSpotify && font <= SGAppFontFamily ? font : SGAppFontSpotify;}NSArray<NSString *> *SGAppFontNames(void) {- return @[@"Spotify", @"System", @"Rounded", @"Serif", @"Mono", @"Custom font"];+ return @[@"Default", @"San Francisco", @"SF Rounded", @"New York", @"SF Mono"];+}++NSArray<NSString *> *SGAppFontFamilies(void) {+ return @[@"Avenir Next", @"Georgia"];}diff --git a/tweak/Sources/Shared/Fonts/FontImport.m b/tweak/Sources/Shared/Fonts/FontImport.mindex 03226fe1..0f3a5ef1 100644--- a/tweak/Sources/Shared/Fonts/FontImport.m+++ b/tweak/Sources/Shared/Fonts/FontImport.m@@ -1,7 +1,7 @@-// A font of the user's own for Fonts.x: a .ttf or .otf picked in Files is copied into Application Support,-// one file at a time, registered with Core Text for this process and named by the PostScript name read from-// it. Like every other font choice it takes over when Spotify starts again, and Fonts.x registers the file-// again on each launch.+// A font family of the user's own for Fonts.x: the .ttf, .otf, .ttc or .otc files of one family picked together in+// Files are copied into Application Support, registered with Core Text for this process and named by the+// family name read from them. Like every other font choice it takes over when Spotify starts again, and+// Fonts.x registers the files again on each launch.#import <CoreText/CoreText.h>#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>#import "Core/SGCore.h"@@ -14,36 +14,76 @@ static NSURL *fontFolder(void) {return [[support URLByAppendingPathComponent:@"Vitrine" isDirectory:YES] URLByAppendingPathComponent:@"Font" isDirectory:YES];}-static NSURL *storedFile(void) {- NSString *file = [NSUserDefaults.standardUserDefaults stringForKey:SGKeyAppFontFile];- return file.length ? [fontFolder() URLByAppendingPathComponent:file.lastPathComponent] : nil;+// The family name of every face in the file, "" for a face without one; empty when Core Text finds no font. A+// collection gives one per face.+static NSArray<NSString *> *familiesIn(NSURL *url) {+ NSArray *faces = CFBridgingRelease(CTFontManagerCreateFontDescriptorsFromURL((__bridge CFURLRef)url));+ NSMutableArray<NSString *> *names = [NSMutableArray array];+ for (id face in faces) {+ NSString *name = CFBridgingRelease(CTFontDescriptorCopyAttribute((__bridge CTFontDescriptorRef)face, kCTFontFamilyNameAttribute));+ [names addObject:name ?: @""];+ }+ return names;}-// The first face's PostScript name, or nil when Core Text finds no font in the file. A collection or a-// family in one file gives its first face.-static NSString *faceName(NSURL *url) {- NSArray *faces = CFBridgingRelease(CTFontManagerCreateFontDescriptorsFromURL((__bridge CFURLRef)url));- if (!faces.count) return nil;- return CFBridgingRelease(CTFontDescriptorCopyAttribute((__bridge CTFontDescriptorRef)faces.firstObject, kCTFontNameAttribute));+// The one family name all the faces share, or nil when they differ, one has none, or there are no faces.+NSString *SGFontSingleFamily(NSArray<NSString *> *names) {+ NSSet<NSString *> *distinct = [NSSet setWithArray:names];+ return distinct.count == 1 && distinct.anyObject.length ? distinct.anyObject : nil;}-// A face iOS already carries under the same name (Chalkduster, say) is refused as a duplicate and is there-// all the same, so what counts is whether the name makes a font afterwards.-static NSString *registerFile(NSURL *url) {- NSString *name = url ? faceName(url) : nil;- if (!name) return nil;- CFErrorRef error = NULL;- if (!CTFontManagerRegisterFontsForURL((__bridge CFURLRef)url, kCTFontManagerScopeProcess, &error)) {- NSError *failure = CFBridgingRelease(error);- SGLog(@"fonts: %@ not registered: %@", url.lastPathComponent, failure.localizedDescription);+// An import from before families is one file under SGKeyAppFontFile and a PostScript name under+// SGKeyAppFontName. It becomes a list of one file and its family name, on first use after the update.+static void migrate(void) {+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ NSString *file = [store stringForKey:SGKeyAppFontFile];+ if (!file.length) return;+ NSString *family = familiesIn([fontFolder() URLByAppendingPathComponent:file.lastPathComponent]).firstObject;+ if (family.length) {+ [store setObject:@[file] forKey:SGKeyAppFontFiles];+ [store setObject:family forKey:SGKeyAppFontName];}- return [UIFont fontWithName:name size:12] ? name : nil;+ [store removeObjectForKey:SGKeyAppFontFile];+}++// The imported files still in the folder.+static NSArray<NSURL *> *storedFiles(void) {+ migrate();+ NSMutableArray<NSURL *> *urls = [NSMutableArray array];+ for (NSString *file in [NSUserDefaults.standardUserDefaults arrayForKey:SGKeyAppFontFiles]) {+ NSURL *url = [fontFolder() URLByAppendingPathComponent:file.lastPathComponent];+ if ([NSFileManager.defaultManager fileExistsAtPath:url.path]) [urls addObject:url];+ }+ return urls;+}++static NSString *importedFamily(void) {+ return storedFiles().count ? [NSUserDefaults.standardUserDefaults stringForKey:SGKeyAppFontName] : nil;}+// A face iOS already carries under the same name (Chalkduster, say) is refused as a duplicate and is there+// all the same, so what counts is whether the family has faces afterwards. Files that are gone are skipped.NSString *SGRegisterCustomFont(void) {- NSString *name = registerFile(storedFile());- if (name) [NSUserDefaults.standardUserDefaults setObject:name forKey:SGKeyAppFontName];- return name;+ NSString *family = importedFamily();+ for (NSURL *url in storedFiles()) {+ CFErrorRef error = NULL;+ if (!CTFontManagerRegisterFontsForURL((__bridge CFURLRef)url, kCTFontManagerScopeProcess, &error)) {+ NSError *failure = CFBridgingRelease(error);+ SGLog(@"fonts: %@ not registered: %@", url.lastPathComponent, failure.localizedDescription);+ }+ }+ return family && [UIFont fontNamesForFamilyName:family].count ? family : nil;+}++// The imported files unregistered and deleted, and the choice forgotten.+static void removeImported(void) {+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ for (NSURL *url in storedFiles()) {+ CTFontManagerUnregisterFontsForURL((__bridge CFURLRef)url, kCTFontManagerScopeProcess, NULL);+ [NSFileManager.defaultManager removeItemAtURL:url error:nil];+ }+ for (NSString *key in @[SGKeyAppFontFiles, SGKeyAppFontName]) [store removeObjectForKey:key];+ if (SGAppFontChosen() == SGAppFontCustom) SGSetInt(SGKeyAppFont, SGAppFontSpotify);}static void tell(NSString *title, NSString *message, BOOL restart) {@@ -57,68 +97,265 @@ static void tell(NSString *title, NSString *message, BOOL restart) {[SGTopController() presentViewController:alert animated:YES completion:nil];}-// The file is checked before the one in use is touched, so a file Core Text will not read changes nothing.-static void import(NSURL *picked) {- BOOL scoped = [picked startAccessingSecurityScopedResource];- NSString *name = faceName(picked);- NSURL *folder = fontFolder(), *old = storedFile();- NSString *file = [@"Custom" stringByAppendingPathExtension:picked.pathExtension.length ? picked.pathExtension.lowercaseString : @"ttf"];- NSURL *target = [folder URLByAppendingPathComponent:file];+// The files are checked and copied aside before the ones in use are touched, so files Core Text will not read,+// of more than one family, or that fail to copy change nothing.+static void import(NSArray<NSURL *> *picked) {+ NSMutableArray<NSURL *> *scoped = [NSMutableArray array];+ NSMutableArray<NSString *> *families = [NSMutableArray array];+ BOOL fonts = YES;+ for (NSURL *url in picked) {+ if ([url startAccessingSecurityScopedResource]) [scoped addObject:url];+ NSArray<NSString *> *names = familiesIn(url);+ fonts = fonts && names.count;+ [families addObjectsFromArray:names];+ }+ NSString *family = fonts ? SGFontSingleFamily(families) : nil;NSFileManager *files = NSFileManager.defaultManager;- BOOL copied = NO;- if (name) {- if (old) {- CTFontManagerUnregisterFontsForURL((__bridge CFURLRef)old, kCTFontManagerScopeProcess, NULL);- [files removeItemAtURL:old error:nil];+ NSURL *incoming = [fontFolder() URLByAppendingPathComponent:@"Incoming" isDirectory:YES];+ NSMutableArray<NSString *> *copied = [NSMutableArray array];+ if (family) {+ [files removeItemAtURL:incoming error:nil];+ [files createDirectoryAtURL:incoming withIntermediateDirectories:YES attributes:nil error:nil];+ for (NSURL *url in picked) {+ NSString *file = url.lastPathComponent;+ if ([files copyItemAtURL:url toURL:[incoming URLByAppendingPathComponent:file] error:nil]) [copied addObject:file];}- [files removeItemAtURL:target error:nil];- [files createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:nil];- copied = [files copyItemAtURL:picked toURL:target error:nil];- }- if (scoped) [picked stopAccessingSecurityScopedResource];- name = copied ? registerFile(target) : nil;- if (!name) {- tell(@"Font not imported", @"Choose a valid .ttf or .otf font file.", NO);- return;}+ for (NSURL *url in scoped) [url stopAccessingSecurityScopedResource];NSUserDefaults *store = NSUserDefaults.standardUserDefaults;- [store setObject:file forKey:SGKeyAppFontFile];- [store setObject:name forKey:SGKeyAppFontName];- SGSetInt(SGKeyAppFont, SGAppFontCustom);- tell(@"Font imported", [NSString stringWithFormat:@"%@ becomes the app's font when Spotify starts again.", name], YES);+ if (family && copied.count == picked.count) {+ removeImported();+ for (NSString *file in copied) {+ NSURL *target = [fontFolder() URLByAppendingPathComponent:file];+ [files removeItemAtURL:target error:nil];+ [files moveItemAtURL:[incoming URLByAppendingPathComponent:file] toURL:target error:nil];+ }+ [files removeItemAtURL:incoming error:nil];+ [store setObject:copied forKey:SGKeyAppFontFiles];+ [store setObject:family forKey:SGKeyAppFontName];+ if (SGRegisterCustomFont()) {+ SGSetInt(SGKeyAppFont, SGAppFontCustom);+ tell(@"Font imported", [NSString stringWithFormat:@"%@ becomes the app's font when Spotify starts again.", family], YES);+ return;+ }+ }+ [files removeItemAtURL:incoming error:nil];+ if (family && copied.count == picked.count) removeImported(); // copied in but Core Text took none of it+ tell(@"Font not imported", fonts && !family ? @"These files are more than one family. Pick the files of one family together."+ : @"Choose valid .ttf, .otf, .ttc or .otc font files.", NO);}@interface SGFontPicker : NSObject <UIDocumentPickerDelegate>+@property (nonatomic, copy) void (^done)(void); // the page's refresh, once the files are in or refused@end@implementation SGFontPicker- (void)documentPicker:(UIDocumentPickerViewController *)picker didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {- NSURL *picked = urls.firstObject;// The alert waits for the picker to be gone, or it has nothing to present over.- dispatch_async(dispatch_get_main_queue(), ^{ if (picked) import(picked); });+ dispatch_async(dispatch_get_main_queue(), ^{+ if (urls.count) import(urls);+ if (self.done) self.done();+ });}@end-static void pickFont(void) {+static void pickFont(void (^done)(void)) {static SGFontPicker *delegate;if (!delegate) delegate = [SGFontPicker new];UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[UTTypeFont] asCopy:YES];+ delegate.done = done;picker.delegate = delegate;- picker.allowsMultipleSelection = NO;+ picker.allowsMultipleSelection = YES;[SGTopController() presentViewController:picker animated:YES completion:nil];}+#pragma mark - the page++// Each choice is drawn in its own font. Core Text makes it, so the font chosen now (Fonts.x hooks UIFont) does+// not dress every row in itself.+static UIFont *previewFont(NSString *nameOrFamily, BOOL family, CGFloat size) {+ CTFontRef font = NULL;+ if (family) {+ CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)@{(id)kCTFontFamilyNameAttribute: nameOrFamily});+ font = CTFontCreateWithFontDescriptor(descriptor, size, NULL);+ CFRelease(descriptor);+ } else if (nameOrFamily) {+ font = CTFontCreateWithName((__bridge CFStringRef)nameOrFamily, size, NULL);+ }+ return font ? (__bridge_transfer UIFont *)font : nil;+}++static UIFont *builtInFont(SGAppFont choice, CGFloat size) {+ if (choice == SGAppFontSpotify) return previewFont(@"SpotifyMixUI-Regular", NO, size);+ UIFontDescriptor *system = ((__bridge_transfer UIFont *)CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, size, NULL)).fontDescriptor;+ UIFontDescriptorSystemDesign design = choice == SGAppFontRounded ? UIFontDescriptorSystemDesignRounded+ : choice == SGAppFontSerif ? UIFontDescriptorSystemDesignSerif+ : choice == SGAppFontMono ? UIFontDescriptorSystemDesignMonospaced : UIFontDescriptorSystemDesignDefault;+ UIFontDescriptor *descriptor = [system fontDescriptorWithDesign:design] ?: system;+ return (__bridge_transfer UIFont *)CTFontCreateWithFontDescriptor((__bridge CTFontDescriptorRef)descriptor, size, NULL);+}++static NSString *chosenLabel(void) {+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ SGAppFont font = SGAppFontChosen();+ if (font == SGAppFontCustom) return importedFamily() ?: @"Your font";+ if (font == SGAppFontFamily) return [store stringForKey:SGKeyAppFontFamily] ?: SGAppFontNames()[0];+ return SGAppFontNames()[font];+}++typedef NS_ENUM(NSInteger, SGFontSection) { SGFontBuiltIn, SGFontMore, SGFontYours };++@interface SGFontPage : SGPage+@end++@implementation SGFontPage {+ NSArray<NSString *> *_families;+ UIView *_footer;+}++- (instancetype)init {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ self.title = @"Font";+ _families = SGAppFontFamilies();+ SGRegisterCustomFont(); // so the imported family can be drawn here, whichever font is chosen+ return self;+}++// A one-face import says why bold comes out regular; otherwise the note says how to bring the bold along.+- (void)refreshFooter {+ NSString *own = self.styleCount == 1+ ? @"A font of your own is a .ttf or .otf file from Files. This one has a single style, so bold text comes out regular. Pick all the files of a family together to keep bold. "+ : @"A font of your own comes from Files: a .ttf or .otf file, or all the files of one family picked together, so bold and italic stay. ";+ _footer = SGNote([own stringByAppendingString:@"Text Spotify draws itself may keep its own font. Changes apply after you restart Spotify."]);+ self.tableView.tableFooterView = _footer;+}++- (void)viewDidLoad {+ [super viewDidLoad];+ [self refreshFooter];+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ SGFitNote(self.tableView, _footer, 8, 24);+}++- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ [self refresh];+}++- (void)refresh {+ [self refreshFooter];+ [self.tableView reloadData];+}++// The imported family, while there is one, then the row that adds one.+- (NSString *)importedName {+ return importedFamily();+}++// How many faces the imported family has on this iPhone.+- (NSUInteger)styleCount {+ NSString *name = self.importedName;+ return name ? [UIFont fontNamesForFamilyName:name].count : 0;+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {+ return 3;+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ if (section == SGFontBuiltIn) return (NSInteger)SGAppFontNames().count;+ if (section == SGFontMore) return (NSInteger)_families.count;+ return self.importedName.length ? 2 : 1;+}++- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {+ return section == SGFontBuiltIn ? nil : SGSectionHeader(table, section == SGFontMore ? @"More fonts" : @"Your fonts");+}++- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {+ return section == SGFontBuiltIn ? SGSectionGap : SGSectionHeaderHeight;+}++- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ UITableViewCell *cell = SGDequeueCell(table, @"font");+ CGFloat size = SGTitleFont().pointSize;+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ SGAppFont chosen = SGAppFontChosen();+ NSString *title, *subtitle = nil;+ UIFont *font;+ BOOL selected;+ if (path.section == SGFontBuiltIn) {+ title = SGAppFontNames()[(NSUInteger)path.row];+ font = builtInFont(path.row, size);+ selected = chosen == path.row;+ } else if (path.section == SGFontMore) {+ title = _families[(NSUInteger)path.row];+ font = previewFont(title, YES, size);+ selected = chosen == SGAppFontFamily && [title isEqualToString:[store stringForKey:SGKeyAppFontFamily]];+ } else if (path.row == 0 && self.importedName.length) {+ title = self.importedName;+ font = previewFont(title, YES, size);+ selected = chosen == SGAppFontCustom;+ subtitle = [NSString stringWithFormat:@"%lu style%@", (unsigned long)self.styleCount, self.styleCount == 1 ? @"" : @"s"];+ } else {+ SGFillCell(cell, @"Add a font file", nil, SGGreen(), nil);+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ cell.accessibilityTraits = UIAccessibilityTraitButton;+ return cell;+ }+ SGFillCell(cell, title, subtitle, nil, nil);+ UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;+ if (font) content.textProperties.font = [[UIFontMetrics metricsForTextStyle:UIFontTextStyleBody] scaledFontForFont:font maximumPointSize:18];+ cell.contentConfiguration = content;+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ if (selected) {+ UIImageView *tick = SGSymbolView(@"checkmark", 13, UIImageSymbolWeightSemibold, 16);+ tick.tintColor = SGGreen();+ cell.accessoryView = tick;+ }+ cell.accessibilityTraits = selected ? UIAccessibilityTraitButton | UIAccessibilityTraitSelected : UIAccessibilityTraitButton;+ return cell;+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ if (path.section == SGFontBuiltIn) {+ SGSetInt(SGKeyAppFont, path.row);+ } else if (path.section == SGFontMore) {+ [NSUserDefaults.standardUserDefaults setObject:_families[(NSUInteger)path.row] forKey:SGKeyAppFontFamily];+ SGSetInt(SGKeyAppFont, SGAppFontFamily);+ } else if (path.row == 0 && self.importedName.length) {+ SGSetInt(SGKeyAppFont, SGAppFontCustom);+ } else {+ __weak SGFontPage *page = self;+ pickFont(^{ [page refresh]; });+ return;+ }+ [table reloadData];+}++// Swiping the imported family away deletes its files; Default comes back if it was the choice.+- (UISwipeActionsConfiguration *)tableView:(UITableView *)table trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)path {+ if (path.section != SGFontYours || path.row != 0 || !self.importedName.length) return nil;+ UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"Delete"+ handler:^(UIContextualAction *action, UIView *view, void (^done)(BOOL)) {+ removeImported();+ [self refresh];+ done(YES);+ }];+ delete.image = [UIImage systemImageNamed:@"trash"];+ return [UISwipeActionsConfiguration configurationWithActions:@[delete]];+}++@end+NSArray<SGModRow *> *SGAppFontRows(void) {- SGModRow *font = SGChoiceRow(@"Font", nil, SGKeyAppFont, SGAppFontNames(), SGAppFontSpotify);- NSString *(^choice)(void) = font.value;- font.value = ^NSString *{- NSString *name = [NSUserDefaults.standardUserDefaults stringForKey:SGKeyAppFontName];- return SGAppFontChosen() == SGAppFontCustom && name.length ? name : choice();- };- font.choiceFooter = @"Custom font uses a .ttf or .otf file of your own, imported from Files. It has one weight, so bold text comes out regular, and text Spotify draws itself may keep its own font.";- SGModRow *import = SGActionRow(@"Import custom font", nil, ^{ pickFont(); });- import.visible = ^BOOL { return SGAppFontChosen() == SGAppFontCustom; };- return @[SGWithSymbol(font, @"textformat"), SGWithSymbol(import, @"square.and.arrow.down")];+ SGModRow *font = SGPageRow(@"Font", ^UIViewController *{ return [SGFontPage new]; });+ font.value = ^NSString *{ return chosenLabel(); };+ return @[font];}diff --git a/tweak/Sources/Shared/Fonts/Fonts.h b/tweak/Sources/Shared/Fonts/Fonts.hindex 9bffac2d..5bf53627 100644--- a/tweak/Sources/Shared/Fonts/Fonts.h+++ b/tweak/Sources/Shared/Fonts/Fonts.h@@ -3,9 +3,13 @@#import <UIKit/UIKit.h>#define SGKeyAppFont @"spotifyglass.font"-// The imported font: its file's name in Application Support/Vitrine/Font, and the PostScript name read from it.-#define SGKeyAppFontFile @"spotifyglass.font.file"+// The imported family: its files' names in Application Support/Vitrine/Font, and the family name read from them.+// SGKeyAppFontFile is the single file of an import from before families, moved to the list on first use.+#define SGKeyAppFontFiles @"spotifyglass.font.files"#define SGKeyAppFontName @"spotifyglass.font.name"+#define SGKeyAppFontFile @"spotifyglass.font.file"+// The family chosen under More fonts, by its name ("Avenir Next").+#define SGKeyAppFontFamily @"spotifyglass.font.family"typedef NS_ENUM(NSInteger, SGAppFont) {SGAppFontSpotify, // Spotify's own, untouched@@ -13,14 +17,18 @@ typedef NS_ENUM(NSInteger, SGAppFont) {SGAppFontRounded, // SF RoundedSGAppFontSerif, // New YorkSGAppFontMono, // SF Mono- SGAppFontCustom, // a .ttf or .otf imported from Files+ SGAppFontCustom, // the family imported from Files+ SGAppFontFamily, // a family iOS carries, named by SGKeyAppFontFamily};SGAppFont SGAppFontChosen(void);-NSArray<NSString *> *SGAppFontNames(void);-// Registers the imported font with Core Text for this process and answers its PostScript name, or nil when-// there is no file or Core Text will not take it.+NSArray<NSString *> *SGAppFontNames(void); // the five built in, by SGAppFont+NSArray<NSString *> *SGAppFontFamilies(void); // More fonts: the families this iPhone has of a fixed few+// Registers the imported files with Core Text for this process and answers the family name, or nil when no+// file is left or Core Text will not take them.NSString *SGRegisterCustomFont(void);+// The family name the faces share, or nil when they differ, one has none, or there are none.+NSString *SGFontSingleFamily(NSArray<NSString *> *names);@class SGModRow;-NSArray<SGModRow *> *SGAppFontRows(void); // the Font choice and, while Custom font is chosen, the import+NSArray<SGModRow *> *SGAppFontRows(void); // the Font row, opening the page of choicesdiff --git a/tweak/Sources/Shared/Fonts/Fonts.x b/tweak/Sources/Shared/Fonts/Fonts.xindex c18f18db..db45db61 100644--- a/tweak/Sources/Shared/Fonts/Fonts.x+++ b/tweak/Sources/Shared/Fonts/Fonts.x@@ -2,13 +2,13 @@// script in SpotifyShared's Fonts.bundle), the system's in one of its designs, or a font file imported from// Files (FontImport.m). Spotify asks for its fonts by name, so a name from its two families comes back as the// system font at the same size, with the weight its name ends in. The rounded, serif and monospaced designs-// reach the system font too, so the mod's own text follows. An imported font takes the system font's place-// at the same size; it is one face, so every weight comes out in it. Read at launch.+// reach the system font too, so the mod's own text follows. An imported family and a family iOS carries+// take its place at the same size, each weight as the family's nearest face. Read at launch.#import "Core/SGCore.h"#import "Shared/Fonts/Fonts.h"static SGAppFont sg_font;-static NSString *sg_custom; // the imported font's PostScript name, once Core Text has it for this launch+static NSString *sg_family; // the chosen family: one iOS carries, or the imported one once Core Text has itstatic BOOL spotifys(NSString *name) {return [name hasPrefix:@"CircularSp"] || [name hasPrefix:@"SpotifyMix"] || [name hasPrefix:@"Circular"];@@ -33,21 +33,25 @@ static UIFontDescriptorSystemDesign designOf(SGAppFont font) {}}-// Nil if the imported font has gone since launch, so whoever asked gets the font they would have had.-static UIFont *custom(CGFloat size) {- return [UIFont fontWithName:sg_custom size:size];+// The family's upright face nearest the weight, so an italic file in the family never stands in for regular+// text. Its name is not Spotify's, so the descriptor hook passes it through.+static UIFont *family(CGFloat size, UIFontWeight weight) {+ UIFontDescriptor *descriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:@{+ UIFontDescriptorFamilyAttribute: sg_family,+ UIFontDescriptorTraitsAttribute: @{UIFontWeightTrait: @(weight), UIFontSlantTrait: @0},+ }];+ return [UIFont fontWithDescriptor:descriptor size:size];}static UIFont *designed(UIFont *font) {if (sg_font < SGAppFontRounded || !font) return font;- if (sg_font == SGAppFontCustom) return custom(font.pointSize) ?: font;+ if (sg_font >= SGAppFontCustom) return family(font.pointSize, [font.fontDescriptor.fontAttributes[UIFontDescriptorTraitsAttribute][UIFontWeightTrait] doubleValue]) ?: font;UIFontDescriptor *descriptor = [font.fontDescriptor fontDescriptorWithDesign:designOf(sg_font)];return descriptor ? [UIFont fontWithDescriptor:descriptor size:font.pointSize] : font;}-// Nil only for an imported font that has gone, which leaves Spotify's own in place.static UIFont *systemFor(NSString *name, CGFloat size) {- if (sg_font == SGAppFontCustom) return custom(size);+ if (sg_font >= SGAppFontCustom) return family(size, weightOf(name));return designed([UIFont systemFontOfSize:size weight:weightOf(name)]);}@@ -85,11 +89,18 @@ static UIFont *systemFor(NSString *name, CGFloat size) {SGAppFont SGAppFontChosen(void) {NSInteger font = SGInt(SGKeyAppFont, SGAppFontSpotify);- return font >= SGAppFontSpotify && font <= SGAppFontCustom ? font : SGAppFontSpotify;+ return font >= SGAppFontSpotify && font <= SGAppFontFamily ? font : SGAppFontSpotify;}NSArray<NSString *> *SGAppFontNames(void) {- return @[@"Spotify", @"System", @"Rounded", @"Serif", @"Mono", @"Custom font"];+ return @[@"Default", @"San Francisco", @"SF Rounded", @"New York", @"SF Mono"];+}++NSArray<NSString *> *SGAppFontFamilies(void) {+ NSArray<NSString *> *all = @[@"Avenir Next", @"Helvetica Neue", @"Futura", @"Gill Sans", @"Optima", @"Georgia", @"Charter", @"Palatino", @"American Typewriter"];+ return [all filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString *name, NSDictionary *bindings) {+ return [UIFont fontNamesForFamilyName:name].count > 0;+ }]];}%ctor {@@ -99,13 +110,21 @@ NSArray<NSString *> *SGAppFontNames(void) {// runs. A file that is gone (a restored backup, a reinstall) leaves Spotify's font and keeps the choice,// so importing again is all it takes; Circular imported as a file of its own needs nothing done either.if (sg_font == SGAppFontCustom) {- sg_custom = SGRegisterCustomFont();- if (!sg_custom || spotifys(sg_custom)) {+ sg_family = SGRegisterCustomFont();+ if (!sg_family || spotifys(sg_family)) {SGLog(@"fonts: the imported font is not there, Spotify's stays");return;}}+ if (sg_font == SGAppFontFamily) {+ NSString *name = [NSUserDefaults.standardUserDefaults stringForKey:SGKeyAppFontFamily];+ if (![SGAppFontFamilies() containsObject:name]) {+ SGLog(@"fonts: the family %@ is not on this iPhone, Spotify's stays", name);+ return;+ }+ sg_family = name;+ }%init;if (sg_font >= SGAppFontRounded) %init(Designs);- SGLog(@"fonts: %@ in place of Spotify's", sg_custom ?: SGAppFontNames()[sg_font]);+ SGLog(@"fonts: %@ in place of Spotify's", sg_family ?: SGAppFontNames()[sg_font]);}