├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── .gitignore ├── Preview.png ├── Tweak ├── Liddell.plist ├── Makefile ├── Liddell.h ├── Liddell-Swift.h ├── Liddell.m └── MarqueeLabel.swift ├── Preferences ├── Resources │ ├── Icon.png │ ├── Icon@2x.png │ ├── Info.plist │ ├── Credits.plist │ └── Root.plist ├── Controllers │ ├── LiddellCreditsListController.m │ ├── LiddellCreditsListController.h │ ├── LiddellRootListController.h │ └── LiddellRootListController.m ├── Makefile ├── Cells │ ├── CallaLinkCell.h │ ├── CallaSingleContactCell.h │ ├── CallaLinkCell.m │ └── CallaSingleContactCell.m ├── layout │ └── Library │ │ └── PreferenceLoader │ │ └── Preferences │ │ └── LiddellPreferences.plist └── PreferenceKeys.h ├── Makefile ├── control ├── README.md └── COPYING /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | ko_fi: traurige 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .theos 3 | packages/ 4 | .vscode 5 | -------------------------------------------------------------------------------- /Preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rrk567301/Liddell/HEAD/Preview.png -------------------------------------------------------------------------------- /Tweak/Liddell.plist: -------------------------------------------------------------------------------- 1 | { Filter = { Bundles = ( "com.apple.springboard" ); }; } 2 | -------------------------------------------------------------------------------- /Preferences/Resources/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rrk567301/Liddell/HEAD/Preferences/Resources/Icon.png -------------------------------------------------------------------------------- /Preferences/Resources/Icon@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rrk567301/Liddell/HEAD/Preferences/Resources/Icon@2x.png -------------------------------------------------------------------------------- /Preferences/Controllers/LiddellCreditsListController.m: -------------------------------------------------------------------------------- 1 | // 2 | // LiddellCreditsListController.m 3 | // Liddell 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #include "LiddellCreditsListController.h" 9 | 10 | @implementation LiddellCreditsListController 11 | @end 12 | -------------------------------------------------------------------------------- /Tweak/Makefile: -------------------------------------------------------------------------------- 1 | TWEAK_NAME = Liddell 2 | Liddell_FILES = Liddell.m MarqueeLabel.swift 3 | Liddell_CFLAGS = -fobjc-arc -DTHEOS_LEAN_AND_MEAN 4 | Liddell_FRAMEWORKS = UIKit 5 | Liddell_LIBRARIES = kitten gcuniversal 6 | 7 | include $(THEOS)/makefiles/common.mk 8 | include $(THEOS_MAKE_PATH)/tweak.mk 9 | -------------------------------------------------------------------------------- /Preferences/Controllers/LiddellCreditsListController.h: -------------------------------------------------------------------------------- 1 | // 2 | // LiddellCreditsListController.m 3 | // Liddell 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #import 9 | #import 10 | 11 | @interface LiddellCreditsListController : PSListController 12 | @end 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest a feature that can help make Liddell even better 4 | title: '' 5 | labels: enhancement 6 | assignees: Traurige 7 | 8 | --- 9 | 10 | **Describe the requested feature:** 11 | 12 | **System information:** 13 | - iOS version: 14 | - Device: 15 | - Jailbreak: 16 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | export ARCHS = arm64 arm64e 2 | export SYSROOT = $(THEOS)/sdks/iPhoneOS14.4.sdk 3 | 4 | ifneq ($(THEOS_PACKAGE_SCHEME), rootless) 5 | export TARGET = iphone:clang:14.4:14.0 6 | else 7 | export TARGET = iphone:clang:14.4:15.0 8 | endif 9 | 10 | INSTALL_TARGET_PROCESSES = SpringBoard 11 | SUBPROJECTS = Tweak Preferences 12 | 13 | include $(THEOS)/makefiles/common.mk 14 | include $(THEOS_MAKE_PATH)/aggregate.mk 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report a bug to help improve Liddell 4 | title: '' 5 | labels: bug 6 | assignees: Traurige 7 | 8 | --- 9 | 10 | **Describe the bug:** 11 | 12 | **Steps to reproduce the behavior:** 13 | 14 | **Crash log:** 15 | Upload your log file to pastebin and paste the link here. 16 | 17 | **System information:** 18 | - iOS version: 19 | - Device: 20 | - Jailbreak: 21 | -------------------------------------------------------------------------------- /control: -------------------------------------------------------------------------------- 1 | Package: dev.traurige.liddell 2 | Name: Liddell 3 | Depends: firmware (>= 14.0), mobilesubstrate, preferenceloader, dev.traurige.libkitten (>= 1.3.3), com.mrgcgamer.libgcuniversal 4 | Conflicts: love.litten.liddell 5 | Version: 1.4.3 6 | Architecture: iphoneos-arm 7 | Description: Little and colorful notification banners 8 | Maintainer: Traurige 9 | Author: Traurige 10 | Section: Tweaks 11 | -------------------------------------------------------------------------------- /Preferences/Controllers/LiddellRootListController.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | #import 4 | #import "../PreferenceKeys.h" 5 | #import 6 | 7 | @interface LiddellRootListController : PSListController 8 | @end 9 | 10 | @interface NSTask : NSObject 11 | @property(copy)NSArray* arguments; 12 | @property(copy)NSString* launchPath; 13 | - (void)launch; 14 | @end 15 | -------------------------------------------------------------------------------- /Preferences/Makefile: -------------------------------------------------------------------------------- 1 | BUNDLE_NAME = LiddellPreferences 2 | LiddellPreferences_FILES = $(wildcard Controllers/*.m Cells/*.m) 3 | LiddellPreferences_FRAMEWORKS = UIKit 4 | LiddellPreferences_PRIVATE_FRAMEWORKS = Preferences 5 | LiddellPreferences_LIBRARIES = gcuniversal 6 | LiddellPreferences_INSTALL_PATH = /Library/PreferenceBundles 7 | LiddellPreferences_CFLAGS = -fobjc-arc -DTHEOS_LEAN_AND_MEAN 8 | 9 | include $(THEOS)/makefiles/common.mk 10 | include $(THEOS_MAKE_PATH)/bundle.mk 11 | -------------------------------------------------------------------------------- /Preferences/Cells/CallaLinkCell.h: -------------------------------------------------------------------------------- 1 | // 2 | // CallaLinkCell.h 3 | // Calla Utils 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #import 9 | #import 10 | 11 | @interface CallaLinkCell : PSTableCell 12 | @property(nonatomic, retain)UILabel* label; 13 | @property(nonatomic, retain)UILabel* subtitleLabel; 14 | @property(nonatomic, retain)UIView* tapRecognizerView; 15 | @property(nonatomic, retain)UITapGestureRecognizer* tap; 16 | @property(nonatomic, retain)NSString* title; 17 | @property(nonatomic, retain)NSString* subtitle; 18 | @property(nonatomic, retain)NSString* url; 19 | @end 20 | -------------------------------------------------------------------------------- /Preferences/layout/Library/PreferenceLoader/Preferences/LiddellPreferences.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | entry 6 | 7 | bundle 8 | LiddellPreferences 9 | cell 10 | PSLinkCell 11 | detail 12 | LiddellRootListController 13 | icon 14 | Icon.png 15 | isController 16 | 17 | label 18 | Liddell 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Preferences/Cells/CallaSingleContactCell.h: -------------------------------------------------------------------------------- 1 | // 2 | // CallaSingleContactCell.h 3 | // Calla Utils 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #import 9 | #import 10 | 11 | @interface CallaSingleContactCell : PSTableCell 12 | @property(nonatomic, retain)UIImageView* avatarImageView; 13 | @property(nonatomic, retain)UILabel* displayNameLabel; 14 | @property(nonatomic, retain)UILabel* usernameLabel; 15 | @property(nonatomic, retain)UIView* tapRecognizerView; 16 | @property(nonatomic, retain)UITapGestureRecognizer* tap; 17 | @property(nonatomic, retain)NSString* displayName; 18 | @property(nonatomic, retain)NSString* username; 19 | @property(nonatomic, retain)NSString* url; 20 | - (void)openUserProfile; 21 | @end 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Liddell 2 | Little and colorful notification banners 3 | 4 | ## Preview 5 | Preview 6 | 7 | ## Installation 8 | 1. Download the latest `deb` from the [releases](https://github.com/Traurige/Liddell/releases) 9 | 2. Install Liddell 10 | 11 | ## Compatibility 12 | iPhone, iPad and iPod running iOS/iPadOS 14 or later 13 | 14 | ## Compiling 15 | - [Theos](https://theos.dev/) is required to compile the project 16 | - Depends on [libKitten](https://github.com/Traurige/libKitten) and [libGCUniversal](https://github.com/MrGcGamer/LibGcUniversalDocumentation) 17 | - You may want to edit the root `Makefile` to use your Theos SDK and toolchain 18 | 19 | ## License 20 | [GPLv3](https://github.com/Traurige/Liddell/blob/main/COPYING) 21 | -------------------------------------------------------------------------------- /Preferences/Resources/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | English 7 | CFBundleExecutable 8 | LiddellPreferences 9 | CFBundleIdentifier 10 | dev.traurige.liddell.preferences 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundlePackageType 14 | BNDL 15 | CFBundleShortVersionString 16 | 1.0.0 17 | CFBundleSignature 18 | ???? 19 | CFBundleVersion 20 | 1.0 21 | NSPrincipalClass 22 | LiddellRootListController 23 | 24 | 25 | -------------------------------------------------------------------------------- /Preferences/Resources/Credits.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | items 6 | 7 | 8 | cell 9 | PSGroupCell 10 | footerText 11 | Code idea/base - @Nepeta 12 | isStaticText 13 | 14 | 15 | 16 | 17 | cell 18 | PSGroupCell 19 | footerText 20 | Marquee Label - @cbpowell 21 | isStaticText 22 | 23 | 24 | 25 | 26 | cell 27 | PSGroupCell 28 | footerText 29 | Icon - @74k1_ 30 | isStaticText 31 | 32 | 33 | 34 | title 35 | Credits 36 | 37 | 38 | -------------------------------------------------------------------------------- /Preferences/Controllers/LiddellRootListController.m: -------------------------------------------------------------------------------- 1 | #include "LiddellRootListController.h" 2 | 3 | @implementation LiddellRootListController 4 | - (NSArray *)specifiers { 5 | if (!_specifiers) { 6 | _specifiers = [self loadSpecifiersFromPlistName:@"Root" target:self]; 7 | } 8 | 9 | return _specifiers; 10 | } 11 | 12 | - (void)setPreferenceValue:(id)value specifier:(PSSpecifier *)specifier { 13 | [super setPreferenceValue:value specifier:specifier]; 14 | 15 | if ([[specifier propertyForKey:@"key"] isEqualToString:kPreferenceKeyEnabled]) { 16 | [self promptToRespring]; 17 | } 18 | } 19 | 20 | - (void)promptToRespring { 21 | UIAlertController* resetAlert = [UIAlertController alertControllerWithTitle:@"Liddell" message:@"This option requires a respring to apply. Do you want to respring now?" preferredStyle:UIAlertControllerStyleAlert]; 22 | 23 | UIAlertAction* yesAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) { 24 | [self respring]; 25 | }]; 26 | 27 | UIAlertAction* noAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:nil]; 28 | 29 | [resetAlert addAction:yesAction]; 30 | [resetAlert addAction:noAction]; 31 | 32 | [self presentViewController:resetAlert animated:YES completion:nil]; 33 | } 34 | 35 | - (void)respring { 36 | NSTask* task = [[NSTask alloc] init]; 37 | [task setLaunchPath:ROOT_PATH_NS(@"/usr/bin/killall")]; 38 | [task setArguments:@[@"backboardd"]]; 39 | [task launch]; 40 | } 41 | 42 | - (void)resetPrompt { 43 | UIAlertController* resetAlert = [UIAlertController alertControllerWithTitle:@"Liddell" message:@"Are you sure you want to reset your preferences?" preferredStyle:UIAlertControllerStyleAlert]; 44 | 45 | UIAlertAction* yesAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) { 46 | [self resetPreferences]; 47 | }]; 48 | 49 | UIAlertAction* noAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:nil]; 50 | 51 | [resetAlert addAction:yesAction]; 52 | [resetAlert addAction:noAction]; 53 | 54 | [self presentViewController:resetAlert animated:YES completion:nil]; 55 | } 56 | 57 | - (void)resetPreferences { 58 | NSUserDefaults* userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"dev.traurige.liddell.preferences"]; 59 | for (NSString* key in [userDefaults dictionaryRepresentation]) { 60 | [userDefaults removeObjectForKey:key]; 61 | } 62 | 63 | [self reloadSpecifiers]; 64 | CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), (CFStringRef)@"dev.traurige.liddell.preferences.reload", nil, nil, YES); 65 | } 66 | 67 | - (void)showTestBanner { 68 | CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), (CFStringRef)@"dev.traurige.liddell.test_banner", nil, nil, true); 69 | } 70 | @end 71 | -------------------------------------------------------------------------------- /Preferences/Cells/CallaLinkCell.m: -------------------------------------------------------------------------------- 1 | // 2 | // CallaLinkCell.m 3 | // Calla Utils 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #import "CallaLinkCell.h" 9 | 10 | @implementation CallaLinkCell 11 | - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier specifier:(PSSpecifier *)specifier { 12 | self = [super initWithStyle:style reuseIdentifier:reuseIdentifier specifier:specifier]; 13 | 14 | if (self) { 15 | [self setTitle:[specifier properties][@"label"]]; 16 | [self setSubtitle:[specifier properties][@"subtitle"]]; 17 | [self setUrl:[specifier properties][@"url"]]; 18 | 19 | // title label 20 | [self setLabel:[[UILabel alloc] init]]; 21 | [[self label] setText:[self title]]; 22 | [[self label] setFont:[UIFont systemFontOfSize:17]]; 23 | [[self label] setTextColor:[UIColor systemBlueColor]]; 24 | [self addSubview:[self label]]; 25 | 26 | [[self label] setTranslatesAutoresizingMaskIntoConstraints:NO]; 27 | [NSLayoutConstraint activateConstraints:@[ 28 | [[[self label] centerYAnchor] constraintEqualToAnchor:[self centerYAnchor] constant:-10], 29 | [[[self label] leadingAnchor] constraintEqualToAnchor:[self leadingAnchor] constant:16], 30 | [[[self label] trailingAnchor] constraintEqualToAnchor:[self trailingAnchor] constant:-16] 31 | ]]; 32 | 33 | 34 | // subtitle label 35 | [self setSubtitleLabel:[[UILabel alloc] init]]; 36 | [[self subtitleLabel] setText:[NSString stringWithFormat:@"%@", [self subtitle]]]; 37 | [[self subtitleLabel] setFont:[UIFont systemFontOfSize:11]]; 38 | [[self subtitleLabel] setTextColor:[[UIColor labelColor] colorWithAlphaComponent:0.6]]; 39 | [self addSubview:[self subtitleLabel]]; 40 | 41 | [[self subtitleLabel] setTranslatesAutoresizingMaskIntoConstraints:NO]; 42 | [NSLayoutConstraint activateConstraints:@[ 43 | [[[self subtitleLabel] centerYAnchor] constraintEqualToAnchor:[self centerYAnchor] constant:10], 44 | [[[self subtitleLabel] leadingAnchor] constraintEqualToAnchor:[self leadingAnchor] constant:16], 45 | [[[self subtitleLabel] trailingAnchor] constraintEqualToAnchor:[self trailingAnchor] constant:-16] 46 | ]]; 47 | 48 | 49 | // tap view 50 | [self setTapRecognizerView:[[UIView alloc] init]]; 51 | [self addSubview:[self tapRecognizerView]]; 52 | 53 | [[self tapRecognizerView] setTranslatesAutoresizingMaskIntoConstraints:NO]; 54 | [NSLayoutConstraint activateConstraints:@[ 55 | [[[self tapRecognizerView] topAnchor] constraintEqualToAnchor:[self topAnchor]], 56 | [[[self tapRecognizerView] leadingAnchor] constraintEqualToAnchor:[self leadingAnchor]], 57 | [[[self tapRecognizerView] trailingAnchor] constraintEqualToAnchor:[self trailingAnchor]], 58 | [[[self tapRecognizerView] bottomAnchor] constraintEqualToAnchor:[self bottomAnchor]] 59 | ]]; 60 | 61 | 62 | // tap 63 | [self setTap:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openUrl)]]; 64 | [[self tapRecognizerView] addGestureRecognizer:[self tap]]; 65 | } 66 | 67 | return self; 68 | } 69 | 70 | - (void)openUrl { 71 | [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[self url]] options:@{} completionHandler:nil]; 72 | } 73 | @end 74 | -------------------------------------------------------------------------------- /Tweak/Liddell.h: -------------------------------------------------------------------------------- 1 | // 2 | // Liddell.h 3 | // Liddell 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #import 9 | #import 10 | #import "Liddell-Swift.h" 11 | #import 12 | #import "GcUniversal/GcColorPickerUtils.h" 13 | #import "../Preferences/PreferenceKeys.h" 14 | 15 | dispatch_queue_t bbQueue; 16 | 17 | NSUserDefaults* preferences; 18 | BOOL pfEnabled; 19 | BOOL pfShowIcon; 20 | BOOL pfShowTitle; 21 | BOOL pfShowMessage; 22 | CGFloat pfHeight; 23 | CGFloat pfCornerRadius; 24 | CGFloat pfOffset; 25 | CGFloat pfScrollRate; 26 | NSUInteger pfBackgroundColor; 27 | NSString* pfCustomBackgroundColor; 28 | NSUInteger pfBlurMode; 29 | CGFloat pfIconCornerRadius; 30 | NSUInteger pfTextColor; 31 | NSString* pfCustomTextColor; 32 | NSUInteger pfTextContent; 33 | NSUInteger pfTitleFontSize; 34 | NSUInteger pfContentFontSize; 35 | NSUInteger pfBorderWidth; 36 | NSUInteger pfBorderColor; 37 | NSString* pfCustomBorderColor; 38 | 39 | @interface MTPlatterView : UIView 40 | @end 41 | 42 | @interface MTTitledPlatterView : MTPlatterView 43 | @end 44 | 45 | @interface NCNotificationShortLookView : MTTitledPlatterView 46 | @property(nonatomic, copy)NSArray* icons; 47 | @property(nonatomic, copy)UIImage* prominentIcon; 48 | @property(nonatomic, copy)UIImage* subordinateIcon; 49 | @property(nonatomic, copy)NSString* primaryText; 50 | @property(nonatomic, copy)NSString* secondaryText; 51 | @property(nonatomic, retain)UIView* liddellView; 52 | @property(nonatomic, retain)UIBlurEffect* liddellBlur; 53 | @property(nonatomic, retain)UIVisualEffectView* liddellBlurView; 54 | @property(nonatomic, retain)UIImageView* liddellIconView; 55 | @property(nonatomic, retain)UILabel* liddellTitleLabel; 56 | @property(nonatomic, retain)MarqueeLabel* liddellContentLabel; 57 | @end 58 | 59 | @interface NCNotificationContent : NSObject 60 | @property(nonatomic, copy, readonly)NSString* header; 61 | @end 62 | 63 | @interface NCNotificationRequest : NSObject 64 | @property(nonatomic, readonly)NCNotificationContent* content; 65 | @end 66 | 67 | @interface NCNotificationShortLookViewController : UIViewController 68 | @property(nonatomic, retain)NCNotificationRequest* notificationRequest; 69 | @end 70 | 71 | @interface UIView (Liddell) 72 | - (id)_viewControllerForAncestor; 73 | @end 74 | 75 | @interface BBAction : NSObject 76 | + (id)actionWithLaunchBundleID:(id)arg1 callblock:(id)arg2; 77 | @end 78 | 79 | @interface BBBulletin : NSObject 80 | @property(nonatomic, copy)NSString* title; 81 | @property(nonatomic, copy)NSString* message; 82 | @property(nonatomic, copy)NSString* sectionID; 83 | @property(nonatomic, copy)NSString* bulletinID; 84 | @property(nonatomic, copy)NSString* recordID; 85 | @property(nonatomic, retain)NSDate* date; 86 | @end 87 | 88 | @interface BBServer : NSObject 89 | - (void)publishBulletin:(id)arg1 destinations:(unsigned long long)arg2; 90 | @end 91 | 92 | @interface BBObserver : NSObject 93 | @end 94 | 95 | @interface DispatchObject : OS_object 96 | @end 97 | 98 | @interface DispatchQueue : DispatchObject 99 | @end 100 | 101 | @interface OS_dispatch_queue_serial : DispatchQueue 102 | @end 103 | 104 | @interface SBHIconModel : NSObject 105 | @property(nonatomic, copy, readonly)NSSet* visibleIconIdentifiers; 106 | @end 107 | 108 | @interface SBIconModel : SBHIconModel 109 | @end 110 | 111 | @interface SBIconController : UIViewController 112 | - (SBIconModel *)model; 113 | @end 114 | 115 | @interface SBApplicationController : NSObject 116 | + (instancetype)sharedInstance; 117 | - (NSArray *)allInstalledApplications; 118 | @end 119 | 120 | @interface SBApplication : NSObject 121 | @property(nonatomic, readonly)NSString* bundleIdentifier; 122 | @end 123 | -------------------------------------------------------------------------------- /Preferences/PreferenceKeys.h: -------------------------------------------------------------------------------- 1 | // 2 | // PreferenceKeys.h 3 | // Liddell 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | static NSString* const kPreferenceKeyEnabled = @"Enabled"; 9 | static NSString* const kPreferenceKeyShowIcon = @"ShowIcon"; 10 | static NSString* const kPreferenceKeyShowTitle = @"ShowTitle"; 11 | static NSString* const kPreferenceKeyShowMessage = @"ShowMessage"; 12 | static NSString* const kPreferenceKeyHeight = @"Height"; 13 | static NSString* const kPreferenceKeyCornerRadius = @"CornerRadius"; 14 | static NSString* const kPreferenceKeyOffset = @"Offset"; 15 | static NSString* const kPreferenceKeyScrollRate = @"ScrollRate"; 16 | static NSString* const kPreferenceKeyBackgroundColor = @"BackgroundColor"; 17 | static NSString* const kPreferenceKeyCustomBackgroundColor = @"CustomBackgroundColor"; 18 | static NSString* const kPreferenceKeyBlurMode = @"BlurMode"; 19 | static NSString* const kPreferenceKeyIconCornerRadius = @"IconCornerRadius"; 20 | static NSString* const kPreferenceKeyTextColor = @"TextColor"; 21 | static NSString* const kPreferenceKeyCustomTextColor = @"CustomTextColor"; 22 | static NSString* const kPreferenceKeyTextContent = @"TextContent"; 23 | static NSString* const kPreferenceKeyTitleFontSize = @"TitleFontSize"; 24 | static NSString* const kPreferenceKeyContentFontSize = @"ContentFontSize"; 25 | static NSString* const kPreferenceKeyBorderWidth = @"BorderWidth"; 26 | static NSString* const kPreferenceKeyBorderColor = @"BorderColor"; 27 | static NSString* const kPreferenceKeyCustomBorderColor = @"CustomBorderColor"; 28 | 29 | static const NSUInteger kBackgroundColorTypeNone = 0; 30 | static const NSUInteger kBackgroundColorTypeAdaptive = 1; 31 | static const NSUInteger kBackgroundColorTypeCustom = 2; 32 | static const NSUInteger kBackgroundBlurTypeNone = 0; 33 | static const NSUInteger kBackgroundBlurTypeLight = 1; 34 | static const NSUInteger kBackgroundBlurTypeDark = 2; 35 | static const NSUInteger kBackgroundBlurTypeAdaptive = 3; 36 | static const NSUInteger kTextColorTypeBackground = 0; 37 | static const NSUInteger kTextColorTypeAdaptive = 1; 38 | static const NSUInteger kTextColorTypeCustom = 2; 39 | static const NSUInteger kTextColorContentTypeTitle = 0; 40 | static const NSUInteger kTextColorContentTypeContent = 1; 41 | static const NSUInteger kTextColorContentTypeBoth = 2; 42 | static const NSUInteger kBorderColorTypeAdaptive = 0; 43 | static const NSUInteger kBorderColorTypeCustom = 1; 44 | 45 | static BOOL const kPreferenceKeyEnabledDefaultValue = YES; 46 | static BOOL const kPreferenceKeyShowIconDefaultValue = YES; 47 | static BOOL const kPreferenceKeyShowTitleDefaultValue = YES; 48 | static BOOL const kPreferenceKeyShowMessageDefaultValue = YES; 49 | static CGFloat const kPreferenceKeyHeightDefaultValue = 40; 50 | static CGFloat const kPreferenceKeyCornerRadiusDefaultValue = 8; 51 | static CGFloat const kPreferenceKeyOffsetDefaultValue = 0; 52 | static CGFloat const kPreferenceKeyScrollRateDefaultValue = 50; 53 | static NSUInteger const kPreferenceKeyBackgroundColorDefaultValue = kBackgroundColorTypeNone; 54 | static NSString* const kPreferenceKeyCustomBackgroundColorDefaultValue = @"000000"; 55 | static NSUInteger const kPreferenceKeyBlurModeDefaultValue = kBackgroundBlurTypeAdaptive; 56 | static CGFloat const kPreferenceKeyIconCornerRadiusDefaultValue = 0; 57 | static NSUInteger const kPreferenceKeyTextColorDefaultValue = kTextColorTypeBackground; 58 | static NSString* const kPreferenceKeyCustomTextColorDefaultValue = @"FFFFFF"; 59 | static NSUInteger const kPreferenceKeyTextContentDefaultValue = kTextColorContentTypeBoth; 60 | static CGFloat const kPreferenceKeyTitleFontSizeDefaultValue = 15; 61 | static CGFloat const kPreferenceKeyContentFontSizeDefaultValue = 14; 62 | static CGFloat const kPreferenceKeyBorderWidthDefaultValue = 0; 63 | static NSUInteger const kPreferenceKeyBorderColorDefaultValue = kBorderColorTypeAdaptive; 64 | static NSString* const kPreferenceKeyCustomBorderColorDefaultValue = @"FFFFFF"; 65 | -------------------------------------------------------------------------------- /Preferences/Cells/CallaSingleContactCell.m: -------------------------------------------------------------------------------- 1 | // 2 | // CallaSingleContactCell.m 3 | // Calla Utils 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #import "CallaSingleContactCell.h" 9 | 10 | @implementation CallaSingleContactCell 11 | - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier specifier:(PSSpecifier *)specifier { 12 | self = [super initWithStyle:style reuseIdentifier:reuseIdentifier specifier:specifier]; 13 | 14 | if (self) { 15 | [self setDisplayName:[specifier properties][@"DisplayName"]]; 16 | [self setUsername:[specifier properties][@"Username"]]; 17 | [self setUrl:[specifier properties][@"Url"]]; 18 | 19 | // avatar image view 20 | [self setAvatarImageView:[[UIImageView alloc] init]]; 21 | 22 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{ 23 | UIImage* avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.traurige.dev/v1/avatar?username=%@", [self username]]]]]; 24 | dispatch_async(dispatch_get_main_queue(), ^{ 25 | [UIView transitionWithView:[self avatarImageView] duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ 26 | [[self avatarImageView] setImage:avatar]; 27 | } completion:nil]; 28 | }); 29 | }); 30 | 31 | [[self avatarImageView] setContentMode:UIViewContentModeScaleAspectFill]; 32 | [[self avatarImageView] setClipsToBounds:YES]; 33 | [[[self avatarImageView] layer] setCornerRadius:21.5]; 34 | [[[self avatarImageView] layer] setBorderWidth:2]; 35 | [[[self avatarImageView] layer] setBorderColor:[[[UIColor labelColor] colorWithAlphaComponent:0.1] CGColor]]; 36 | [self addSubview:[self avatarImageView]]; 37 | 38 | [[self avatarImageView] setTranslatesAutoresizingMaskIntoConstraints:NO]; 39 | [NSLayoutConstraint activateConstraints:@[ 40 | [[[self avatarImageView] centerYAnchor] constraintEqualToAnchor:[self centerYAnchor]], 41 | [[[self avatarImageView] leadingAnchor] constraintEqualToAnchor:[self leadingAnchor] constant:16], 42 | [[[self avatarImageView] widthAnchor] constraintEqualToConstant:43], 43 | [[[self avatarImageView] heightAnchor] constraintEqualToConstant:43] 44 | ]]; 45 | 46 | 47 | // display name label 48 | [self setDisplayNameLabel:[[UILabel alloc] init]]; 49 | [[self displayNameLabel] setText:[self displayName]]; 50 | [[self displayNameLabel] setFont:[UIFont systemFontOfSize:17 weight:UIFontWeightSemibold]]; 51 | [[self displayNameLabel] setTextColor:[UIColor labelColor]]; 52 | [self addSubview:[self displayNameLabel]]; 53 | 54 | [[self displayNameLabel] setTranslatesAutoresizingMaskIntoConstraints:NO]; 55 | [NSLayoutConstraint activateConstraints:@[ 56 | [[[self displayNameLabel] topAnchor] constraintEqualToAnchor:[[self avatarImageView] topAnchor] constant:4], 57 | [[[self displayNameLabel] leadingAnchor] constraintEqualToAnchor:[[self avatarImageView] trailingAnchor] constant:8], 58 | [[[self displayNameLabel] trailingAnchor] constraintEqualToAnchor:[self trailingAnchor] constant:-16] 59 | ]]; 60 | 61 | 62 | // username label 63 | [self setUsernameLabel:[[UILabel alloc] init]]; 64 | [[self usernameLabel] setText:[NSString stringWithFormat:@"@%@", [self username]]]; 65 | [[self usernameLabel] setFont:[UIFont systemFontOfSize:11 weight:UIFontWeightRegular]]; 66 | [[self usernameLabel] setTextColor:[[UIColor labelColor] colorWithAlphaComponent:0.6]]; 67 | [self addSubview:[self usernameLabel]]; 68 | 69 | [[self usernameLabel] setTranslatesAutoresizingMaskIntoConstraints:NO]; 70 | [NSLayoutConstraint activateConstraints:@[ 71 | [[[self usernameLabel] leadingAnchor] constraintEqualToAnchor:[[self avatarImageView] trailingAnchor] constant:8], 72 | [[[self usernameLabel] trailingAnchor] constraintEqualToAnchor:[[self displayNameLabel] trailingAnchor]], 73 | [[[self usernameLabel] bottomAnchor] constraintEqualToAnchor:[[self avatarImageView] bottomAnchor] constant:-4] 74 | ]]; 75 | 76 | 77 | // tap view 78 | [self setTapRecognizerView:[[UIView alloc] init]]; 79 | [self addSubview:[self tapRecognizerView]]; 80 | 81 | [[self tapRecognizerView] setTranslatesAutoresizingMaskIntoConstraints:NO]; 82 | [NSLayoutConstraint activateConstraints:@[ 83 | [[[self tapRecognizerView] topAnchor] constraintEqualToAnchor:[self topAnchor]], 84 | [[[self tapRecognizerView] leadingAnchor] constraintEqualToAnchor:[self leadingAnchor]], 85 | [[[self tapRecognizerView] trailingAnchor] constraintEqualToAnchor:[self trailingAnchor]], 86 | [[[self tapRecognizerView] bottomAnchor] constraintEqualToAnchor:[self bottomAnchor]] 87 | ]]; 88 | 89 | 90 | // tap 91 | [self setTap:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openUserProfile)]]; 92 | [[self tapRecognizerView] addGestureRecognizer:[self tap]]; 93 | } 94 | 95 | return self; 96 | } 97 | 98 | - (void)openUserProfile { 99 | [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[self url]] options:@{} completionHandler:nil]; 100 | } 101 | @end 102 | -------------------------------------------------------------------------------- /Preferences/Resources/Root.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | items 6 | 7 | 8 | cell 9 | PSGroupCell 10 | 11 | 12 | cellClass 13 | CallaSingleContactCell 14 | DisplayName 15 | Alexandra 16 | Username 17 | Traurige 18 | Url 19 | https://github.com/Traurige 20 | height 21 | 58 22 | 23 | 24 | cell 25 | PSSwitchCell 26 | default 27 | 28 | defaults 29 | dev.traurige.liddell.preferences 30 | key 31 | Enabled 32 | label 33 | Enable Liddell 34 | PostNotification 35 | dev.traurige.liddell.preferences.reload 36 | 37 | 38 | 39 | cell 40 | PSGroupCell 41 | label 42 | Visibility 43 | 44 | 45 | cell 46 | PSSwitchCell 47 | default 48 | 49 | defaults 50 | dev.traurige.liddell.preferences 51 | key 52 | ShowIcon 53 | label 54 | Show Icon 55 | PostNotification 56 | dev.traurige.liddell.preferences.reload 57 | 58 | 59 | cell 60 | PSSwitchCell 61 | default 62 | 63 | defaults 64 | dev.traurige.liddell.preferences 65 | key 66 | ShowTitle 67 | label 68 | Show Title 69 | PostNotification 70 | dev.traurige.liddell.preferences.reload 71 | 72 | 73 | cell 74 | PSSwitchCell 75 | default 76 | 77 | defaults 78 | dev.traurige.liddell.preferences 79 | key 80 | ShowMessage 81 | label 82 | Show Message 83 | PostNotification 84 | dev.traurige.liddell.preferences.reload 85 | 86 | 87 | 88 | cell 89 | PSGroupCell 90 | label 91 | Style 92 | 93 | 94 | cell 95 | PSStaticTextCell 96 | label 97 | Height 98 | 99 | 100 | cell 101 | PSSliderCell 102 | default 103 | 40 104 | defaults 105 | dev.traurige.liddell.preferences 106 | key 107 | Height 108 | min 109 | 20 110 | max 111 | 50 112 | showValue 113 | 114 | isSegmented 115 | 116 | PostNotification 117 | dev.traurige.liddell.preferences.reload 118 | 119 | 120 | cell 121 | PSStaticTextCell 122 | label 123 | Corner Radius 124 | 125 | 126 | cell 127 | PSSliderCell 128 | default 129 | 8 130 | defaults 131 | dev.traurige.liddell.preferences 132 | key 133 | CornerRadius 134 | min 135 | 0 136 | max 137 | 25 138 | showValue 139 | 140 | isSegmented 141 | 142 | PostNotification 143 | dev.traurige.liddell.preferences.reload 144 | 145 | 146 | cell 147 | PSStaticTextCell 148 | label 149 | Offset 150 | 151 | 152 | cell 153 | PSSliderCell 154 | default 155 | 0 156 | defaults 157 | dev.traurige.liddell.preferences 158 | key 159 | Offset 160 | min 161 | 0 162 | max 163 | 20 164 | showValue 165 | 166 | isSegmented 167 | 168 | PostNotification 169 | dev.traurige.liddell.preferences.reload 170 | 171 | 172 | cell 173 | PSStaticTextCell 174 | label 175 | Scroll Rate 176 | 177 | 178 | cell 179 | PSSliderCell 180 | default 181 | 50 182 | defaults 183 | dev.traurige.liddell.preferences 184 | key 185 | ScrollRate 186 | min 187 | 0 188 | max 189 | 200 190 | showValue 191 | 192 | isSegmented 193 | 194 | PostNotification 195 | dev.traurige.liddell.preferences.reload 196 | 197 | 198 | 199 | cell 200 | PSGroupCell 201 | label 202 | Background 203 | 204 | 205 | cell 206 | PSStaticTextCell 207 | label 208 | Background Color 209 | 210 | 211 | cell 212 | PSSegmentCell 213 | default 214 | 0 215 | defaults 216 | dev.traurige.liddell.preferences 217 | key 218 | BackgroundColor 219 | validValues 220 | 221 | 0 222 | 1 223 | 2 224 | 225 | validTitles 226 | 227 | None 228 | Adaptive 229 | Custom 230 | 231 | alignment 232 | 3 233 | PostNotification 234 | dev.traurige.liddell.preferences.reload 235 | 236 | 237 | cell 238 | PSLinkCell 239 | cellClass 240 | GcColorPickerCell 241 | label 242 | Custom Background Color: 243 | defaults 244 | dev.traurige.liddell.preferences 245 | key 246 | CustomBackgroundColor 247 | supportsAlpha 248 | 249 | fallback 250 | 000000 251 | PostNotification 252 | dev.traurige.liddell.preferences.reload 253 | 254 | 255 | cell 256 | PSLinkListCell 257 | default 258 | 3 259 | detail 260 | PSListItemsController 261 | defaults 262 | dev.traurige.liddell.preferences 263 | label 264 | Blur: 265 | key 266 | BlurMode 267 | validValues 268 | 269 | 0 270 | 1 271 | 2 272 | 3 273 | 274 | validTitles 275 | 276 | None 277 | Light 278 | Dark 279 | Adaptive 280 | 281 | PostNotification 282 | dev.traurige.liddell.preferences.reload 283 | 284 | 285 | 286 | cell 287 | PSGroupCell 288 | label 289 | Icon 290 | footerText 291 | Use -1 for a round icon. 292 | isStaticText 293 | 294 | 295 | 296 | cell 297 | PSStaticTextCell 298 | label 299 | Corner Radius 300 | 301 | 302 | cell 303 | PSSliderCell 304 | default 305 | 0 306 | defaults 307 | dev.traurige.liddell.preferences 308 | key 309 | IconCornerRadius 310 | min 311 | -1 312 | max 313 | 18 314 | showValue 315 | 316 | isSegmented 317 | 318 | PostNotification 319 | dev.traurige.liddell.preferences.reload 320 | 321 | 322 | 323 | cell 324 | PSGroupCell 325 | label 326 | Text 327 | 328 | 329 | cell 330 | PSStaticTextCell 331 | label 332 | Text Color 333 | 334 | 335 | cell 336 | PSSegmentCell 337 | default 338 | 0 339 | defaults 340 | dev.traurige.liddell.preferences 341 | key 342 | TextColor 343 | validValues 344 | 345 | 0 346 | 1 347 | 2 348 | 349 | validTitles 350 | 351 | Background 352 | Adaptive 353 | Custom 354 | 355 | alignment 356 | 2 357 | PostNotification 358 | dev.traurige.liddell.preferences.reload 359 | 360 | 361 | cell 362 | PSLinkCell 363 | cellClass 364 | GcColorPickerCell 365 | label 366 | Custom Text Color: 367 | defaults 368 | dev.traurige.liddell.preferences 369 | key 370 | CustomTextColor 371 | supportsAlpha 372 | 373 | fallback 374 | FFFFFF 375 | PostNotification 376 | dev.traurige.liddell.preferences.reload 377 | 378 | 379 | cell 380 | PSStaticTextCell 381 | label 382 | Content 383 | 384 | 385 | cell 386 | PSSegmentCell 387 | default 388 | 2 389 | defaults 390 | dev.traurige.liddell.preferences 391 | key 392 | TextContent 393 | validValues 394 | 395 | 0 396 | 1 397 | 2 398 | 399 | validTitles 400 | 401 | Title 402 | Content 403 | Both 404 | 405 | alignment 406 | 3 407 | PostNotification 408 | dev.traurige.liddell.preferences.reload 409 | 410 | 411 | cell 412 | PSStaticTextCell 413 | label 414 | Title Font Size 415 | 416 | 417 | cell 418 | PSSliderCell 419 | default 420 | 15 421 | defaults 422 | dev.traurige.liddell.preferences 423 | key 424 | TitleFontSize 425 | min 426 | 10 427 | max 428 | 25 429 | showValue 430 | 431 | isSegmented 432 | 433 | segmentCount 434 | 15 435 | PostNotification 436 | dev.traurige.liddell.preferences.reload 437 | 438 | 439 | cell 440 | PSStaticTextCell 441 | label 442 | Content Font Size 443 | 444 | 445 | cell 446 | PSSliderCell 447 | default 448 | 14 449 | defaults 450 | dev.traurige.liddell.preferences 451 | key 452 | ContentFontSize 453 | min 454 | 10 455 | max 456 | 25 457 | showValue 458 | 459 | isSegmented 460 | 461 | segmentCount 462 | 15 463 | PostNotification 464 | dev.traurige.liddell.preferences.reload 465 | 466 | 467 | 468 | cell 469 | PSGroupCell 470 | label 471 | Border 472 | 473 | 474 | cell 475 | PSStaticTextCell 476 | label 477 | Border Width 478 | 479 | 480 | cell 481 | PSSliderCell 482 | default 483 | 0 484 | defaults 485 | dev.traurige.liddell.preferences 486 | key 487 | BorderWidth 488 | min 489 | 0 490 | max 491 | 3 492 | showValue 493 | 494 | isSegmented 495 | 496 | segmentCount 497 | 3 498 | PostNotification 499 | dev.traurige.liddell.preferences.reload 500 | 501 | 502 | cell 503 | PSStaticTextCell 504 | label 505 | Border Color 506 | 507 | 508 | cell 509 | PSSegmentCell 510 | default 511 | 0 512 | defaults 513 | dev.traurige.liddell.preferences 514 | key 515 | BorderColor 516 | validValues 517 | 518 | 0 519 | 1 520 | 521 | validTitles 522 | 523 | Adaptive 524 | Custom 525 | 526 | alignment 527 | 3 528 | PostNotification 529 | dev.traurige.liddell.preferences.reload 530 | 531 | 532 | cell 533 | PSLinkCell 534 | cellClass 535 | GcColorPickerCell 536 | label 537 | Custom Border Color: 538 | defaults 539 | dev.traurige.liddell.preferences 540 | key 541 | CustomBorderColor 542 | supportsAlpha 543 | 544 | fallback 545 | FFFFFF 546 | PostNotification 547 | dev.traurige.liddell.preferences.reload 548 | 549 | 550 | 551 | cell 552 | PSGroupCell 553 | label 554 | Tools 555 | 556 | 557 | cell 558 | PSButtonCell 559 | label 560 | Respring 561 | action 562 | respring 563 | 564 | 565 | cell 566 | PSButtonCell 567 | label 568 | Reset Preferences 569 | action 570 | resetPrompt 571 | 572 | 573 | cell 574 | PSButtonCell 575 | label 576 | Test Banner 577 | action 578 | showTestBanner 579 | 580 | 581 | 582 | cell 583 | PSGroupCell 584 | footerText 585 | Thanks to you and everyone who has helped in any way. 586 | isStaticText 587 | 588 | 589 | 590 | cell 591 | PSLinkCell 592 | label 593 | Credits 594 | detail 595 | LiddellCreditsListController 596 | 597 | 598 | 599 | cell 600 | PSGroupCell 601 | footerText 602 | Liddell by Traurige, inspired by Nepeta's Nanobanners 603 | isStaticText 604 | 605 | 606 | 607 | cellClass 608 | CallaLinkCell 609 | label 610 | Source Code 611 | subtitle 612 | It's on GitHub 613 | url 614 | https://github.com/Traurige/Liddell 615 | height 616 | 52 617 | 618 | 619 | cellClass 620 | CallaLinkCell 621 | label 622 | Bug/Feature 623 | subtitle 624 | Submit an issue 625 | url 626 | https://github.com/Traurige/Liddell/issues/new/choose 627 | height 628 | 52 629 | 630 | 631 | cellClass 632 | CallaLinkCell 633 | label 634 | Donate 635 | subtitle 636 | I got a Ko-fi 637 | url 638 | https://ko-fi.com/traurige 639 | height 640 | 52 641 | 642 | 643 | title 644 | Liddell 645 | 646 | 647 | -------------------------------------------------------------------------------- /Tweak/Liddell-Swift.h: -------------------------------------------------------------------------------- 1 | // Generated by Apple Swift version 5.5.1 (swiftlang-1300.0.31.4 clang-1300.0.29.6) 2 | #ifndef LIDDELL_SWIFT_H 3 | #define LIDDELL_SWIFT_H 4 | #pragma clang diagnostic push 5 | #pragma clang diagnostic ignored "-Wgcc-compat" 6 | 7 | #if !defined(__has_include) 8 | # define __has_include(x) 0 9 | #endif 10 | #if !defined(__has_attribute) 11 | # define __has_attribute(x) 0 12 | #endif 13 | #if !defined(__has_feature) 14 | # define __has_feature(x) 0 15 | #endif 16 | #if !defined(__has_warning) 17 | # define __has_warning(x) 0 18 | #endif 19 | 20 | #if __has_include() 21 | # include 22 | #endif 23 | 24 | #pragma clang diagnostic ignored "-Wauto-import" 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #if !defined(SWIFT_TYPEDEFS) 31 | # define SWIFT_TYPEDEFS 1 32 | # if __has_include() 33 | # include 34 | # elif !defined(__cplusplus) 35 | typedef uint_least16_t char16_t; 36 | typedef uint_least32_t char32_t; 37 | # endif 38 | typedef float swift_float2 __attribute__((__ext_vector_type__(2))); 39 | typedef float swift_float3 __attribute__((__ext_vector_type__(3))); 40 | typedef float swift_float4 __attribute__((__ext_vector_type__(4))); 41 | typedef double swift_double2 __attribute__((__ext_vector_type__(2))); 42 | typedef double swift_double3 __attribute__((__ext_vector_type__(3))); 43 | typedef double swift_double4 __attribute__((__ext_vector_type__(4))); 44 | typedef int swift_int2 __attribute__((__ext_vector_type__(2))); 45 | typedef int swift_int3 __attribute__((__ext_vector_type__(3))); 46 | typedef int swift_int4 __attribute__((__ext_vector_type__(4))); 47 | typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2))); 48 | typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3))); 49 | typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4))); 50 | #endif 51 | 52 | #if !defined(SWIFT_PASTE) 53 | # define SWIFT_PASTE_HELPER(x, y) x##y 54 | # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) 55 | #endif 56 | #if !defined(SWIFT_METATYPE) 57 | # define SWIFT_METATYPE(X) Class 58 | #endif 59 | #if !defined(SWIFT_CLASS_PROPERTY) 60 | # if __has_feature(objc_class_property) 61 | # define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__ 62 | # else 63 | # define SWIFT_CLASS_PROPERTY(...) 64 | # endif 65 | #endif 66 | 67 | #if __has_attribute(objc_runtime_name) 68 | # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) 69 | #else 70 | # define SWIFT_RUNTIME_NAME(X) 71 | #endif 72 | #if __has_attribute(swift_name) 73 | # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) 74 | #else 75 | # define SWIFT_COMPILE_NAME(X) 76 | #endif 77 | #if __has_attribute(objc_method_family) 78 | # define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X))) 79 | #else 80 | # define SWIFT_METHOD_FAMILY(X) 81 | #endif 82 | #if __has_attribute(noescape) 83 | # define SWIFT_NOESCAPE __attribute__((noescape)) 84 | #else 85 | # define SWIFT_NOESCAPE 86 | #endif 87 | #if __has_attribute(ns_consumed) 88 | # define SWIFT_RELEASES_ARGUMENT __attribute__((ns_consumed)) 89 | #else 90 | # define SWIFT_RELEASES_ARGUMENT 91 | #endif 92 | #if __has_attribute(warn_unused_result) 93 | # define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) 94 | #else 95 | # define SWIFT_WARN_UNUSED_RESULT 96 | #endif 97 | #if __has_attribute(noreturn) 98 | # define SWIFT_NORETURN __attribute__((noreturn)) 99 | #else 100 | # define SWIFT_NORETURN 101 | #endif 102 | #if !defined(SWIFT_CLASS_EXTRA) 103 | # define SWIFT_CLASS_EXTRA 104 | #endif 105 | #if !defined(SWIFT_PROTOCOL_EXTRA) 106 | # define SWIFT_PROTOCOL_EXTRA 107 | #endif 108 | #if !defined(SWIFT_ENUM_EXTRA) 109 | # define SWIFT_ENUM_EXTRA 110 | #endif 111 | #if !defined(SWIFT_CLASS) 112 | # if __has_attribute(objc_subclassing_restricted) 113 | # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA 114 | # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA 115 | # else 116 | # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA 117 | # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA 118 | # endif 119 | #endif 120 | #if !defined(SWIFT_RESILIENT_CLASS) 121 | # if __has_attribute(objc_class_stub) 122 | # define SWIFT_RESILIENT_CLASS(SWIFT_NAME) SWIFT_CLASS(SWIFT_NAME) __attribute__((objc_class_stub)) 123 | # define SWIFT_RESILIENT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_class_stub)) SWIFT_CLASS_NAMED(SWIFT_NAME) 124 | # else 125 | # define SWIFT_RESILIENT_CLASS(SWIFT_NAME) SWIFT_CLASS(SWIFT_NAME) 126 | # define SWIFT_RESILIENT_CLASS_NAMED(SWIFT_NAME) SWIFT_CLASS_NAMED(SWIFT_NAME) 127 | # endif 128 | #endif 129 | 130 | #if !defined(SWIFT_PROTOCOL) 131 | # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA 132 | # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA 133 | #endif 134 | 135 | #if !defined(SWIFT_EXTENSION) 136 | # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) 137 | #endif 138 | 139 | #if !defined(OBJC_DESIGNATED_INITIALIZER) 140 | # if __has_attribute(objc_designated_initializer) 141 | # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) 142 | # else 143 | # define OBJC_DESIGNATED_INITIALIZER 144 | # endif 145 | #endif 146 | #if !defined(SWIFT_ENUM_ATTR) 147 | # if defined(__has_attribute) && __has_attribute(enum_extensibility) 148 | # define SWIFT_ENUM_ATTR(_extensibility) __attribute__((enum_extensibility(_extensibility))) 149 | # else 150 | # define SWIFT_ENUM_ATTR(_extensibility) 151 | # endif 152 | #endif 153 | #if !defined(SWIFT_ENUM) 154 | # define SWIFT_ENUM(_type, _name, _extensibility) enum _name : _type _name; enum SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type 155 | # if __has_feature(generalized_swift_name) 156 | # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type 157 | # else 158 | # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) SWIFT_ENUM(_type, _name, _extensibility) 159 | # endif 160 | #endif 161 | #if !defined(SWIFT_UNAVAILABLE) 162 | # define SWIFT_UNAVAILABLE __attribute__((unavailable)) 163 | #endif 164 | #if !defined(SWIFT_UNAVAILABLE_MSG) 165 | # define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg))) 166 | #endif 167 | #if !defined(SWIFT_AVAILABILITY) 168 | # define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__))) 169 | #endif 170 | #if !defined(SWIFT_WEAK_IMPORT) 171 | # define SWIFT_WEAK_IMPORT __attribute__((weak_import)) 172 | #endif 173 | #if !defined(SWIFT_DEPRECATED) 174 | # define SWIFT_DEPRECATED __attribute__((deprecated)) 175 | #endif 176 | #if !defined(SWIFT_DEPRECATED_MSG) 177 | # define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__))) 178 | #endif 179 | #if __has_feature(attribute_diagnose_if_objc) 180 | # define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning"))) 181 | #else 182 | # define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg) 183 | #endif 184 | #if !defined(IBSegueAction) 185 | # define IBSegueAction 186 | #endif 187 | #if __has_feature(modules) 188 | #if __has_warning("-Watimport-in-framework-header") 189 | #pragma clang diagnostic ignored "-Watimport-in-framework-header" 190 | #endif 191 | @import CoreGraphics; 192 | @import QuartzCore; 193 | @import UIKit; 194 | #endif 195 | 196 | #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" 197 | #pragma clang diagnostic ignored "-Wduplicate-method-arg" 198 | #if __has_warning("-Wpragma-clang-attribute") 199 | # pragma clang diagnostic ignored "-Wpragma-clang-attribute" 200 | #endif 201 | #pragma clang diagnostic ignored "-Wunknown-pragmas" 202 | #pragma clang diagnostic ignored "-Wnullability" 203 | 204 | #if __has_attribute(external_source_symbol) 205 | # pragma push_macro("any") 206 | # undef any 207 | # pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="Liddell",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol)) 208 | # pragma pop_macro("any") 209 | #endif 210 | 211 | 212 | @class NSNumber; 213 | @class NSCoder; 214 | @class UIWindow; 215 | @class CAAnimation; 216 | @class CALayer; 217 | @class NSNotification; 218 | @class UIGestureRecognizer; 219 | @class UIView; 220 | @class NSString; 221 | @class NSAttributedString; 222 | @class UIFont; 223 | @class UIColor; 224 | 225 | IB_DESIGNABLE 226 | SWIFT_CLASS("_TtC7Liddell12MarqueeLabel") 227 | @interface MarqueeLabel : UILabel 228 | /// A boolean property that sets whether the MarqueeLabel should behave like a normal UILabel. 229 | /// When set to true the MarqueeLabel will behave and look like a normal UILabel, and will not begin any scrolling animations. 230 | /// Changes to this property take effect immediately, removing any in-flight animation as well as any edge fade. Note that MarqueeLabel 231 | /// will respect the current values of the lineBreakMode and textAlignmentproperties while labelized. 232 | /// To simply prevent automatic scrolling, use the holdScrolling property. 233 | /// Defaults to false. 234 | /// seealso: 235 | /// holdScrolling 236 | /// seealso: 237 | /// lineBreakMode 238 | /// note: 239 | /// The label will not automatically scroll when this property is set to true. 240 | /// warning: 241 | /// The UILabel default setting for the lineBreakMode property is NSLineBreakByTruncatingTail, which truncates 242 | /// the text adds an ellipsis glyph (…). Set the lineBreakMode property to NSLineBreakByClipping in order to avoid the 243 | /// ellipsis, especially if using an edge transparency fade. 244 | @property (nonatomic) IBInspectable BOOL labelize; 245 | /// A boolean property that sets whether the MarqueeLabel should hold (prevent) automatic label scrolling. 246 | /// When set to true, MarqueeLabel will not automatically scroll even its text is larger than the specified frame, 247 | /// although the specified edge fades will remain. 248 | /// To set MarqueeLabel to act like a normal UILabel, use the labelize property. 249 | /// Defaults to false. 250 | /// note: 251 | /// The label will not automatically scroll when this property is set to true. 252 | /// seealso: 253 | /// labelize 254 | @property (nonatomic) IBInspectable BOOL holdScrolling; 255 | /// A boolean property that sets whether the MarqueeLabel should scroll, even if the specificed test string 256 | /// can be fully contained within the label frame. 257 | /// If this property is set to true, the MarqueeLabel will automatically scroll regardless of text string 258 | /// length, although this can still be overridden by the tapToScroll and holdScrolling properties. 259 | /// Defaults to false. 260 | /// warning: 261 | /// Forced scrolling may have unexpected edge cases or have unusual characteristics compared to the 262 | /// ‘normal’ scrolling feature. 263 | /// seealso: 264 | /// holdScrolling 265 | /// seealso: 266 | /// tapToScroll 267 | @property (nonatomic) IBInspectable BOOL forceScrolling; 268 | /// A boolean property that sets whether the MarqueeLabel should only begin a scroll when tapped. 269 | /// If this property is set to true, the MarqueeLabel will only begin a scroll animation cycle when tapped. The label will 270 | /// not automatically being a scroll. This setting overrides the setting of the holdScrolling property. 271 | /// Defaults to false. 272 | /// note: 273 | /// The label will not automatically scroll when this property is set to false. 274 | /// seealso: 275 | /// holdScrolling 276 | @property (nonatomic) IBInspectable BOOL tapToScroll; 277 | @property (nonatomic) IBInspectable CGFloat scrollDuration SWIFT_DEPRECATED_MSG("Use speed property instead"); 278 | @property (nonatomic) IBInspectable CGFloat scrollRate; 279 | /// A buffer (offset) between the leading edge of the label text and the label frame. 280 | /// This property adds additional space between the leading edge of the label text and the label frame. The 281 | /// leading edge is the edge of the label text facing the direction of scroll (i.e. the edge that animates 282 | /// offscreen first during scrolling). 283 | /// Defaults to 0. 284 | /// note: 285 | /// The value set to this property affects label positioning at all times (including when labelize is set to true), 286 | /// including when the text string length is short enough that the label does not need to scroll. 287 | /// note: 288 | /// For Continuous-type labels, the smallest value of leadingBuffer, trailingBuffer, and fadeLength 289 | /// is used as spacing between the two label instances. Zero is an allowable value for all three properties. 290 | /// seealso: 291 | /// trailingBuffer 292 | @property (nonatomic) IBInspectable CGFloat leadingBuffer; 293 | /// A buffer (offset) between the trailing edge of the label text and the label frame. 294 | /// This property adds additional space (buffer) between the trailing edge of the label text and the label frame. The 295 | /// trailing edge is the edge of the label text facing away from the direction of scroll (i.e. the edge that animates 296 | /// offscreen last during scrolling). 297 | /// Defaults to 0. 298 | /// note: 299 | /// The value set to this property has no effect when the labelize property is set to true. 300 | /// note: 301 | /// For Continuous-type labels, the smallest value of leadingBuffer, trailingBuffer, and fadeLength 302 | /// is used as spacing between the two label instances. Zero is an allowable value for all three properties. 303 | /// seealso: 304 | /// leadingBuffer 305 | @property (nonatomic) IBInspectable CGFloat trailingBuffer; 306 | /// The length of transparency fade at the left and right edges of the frame. 307 | /// This propery sets the size (in points) of the view edge transparency fades on the left and right edges of a MarqueeLabel. The 308 | /// transparency fades from an alpha of 1.0 (fully visible) to 0.0 (fully transparent) over this distance. Values set to this property 309 | /// will be sanitized to prevent a fade length greater than 1/2 of the frame width. 310 | /// Defaults to 0. 311 | @property (nonatomic) IBInspectable CGFloat fadeLength; 312 | /// The length of delay in seconds that the label pauses at the completion of a scroll. 313 | @property (nonatomic) IBInspectable CGFloat animationDelay; 314 | - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; 315 | /// Returns a newly initialized MarqueeLabel instance. 316 | /// The default scroll duration of 7.0 seconds and fade length of 0.0 are used. 317 | /// \param frame A rectangle specifying the initial location and size of the view in its superview’s coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll. 318 | /// 319 | /// 320 | /// returns: 321 | /// An initialized MarqueeLabel object or nil if the object couldn’t be created. 322 | - (nonnull instancetype)initWithFrame:(CGRect)frame; 323 | - (void)awakeFromNib; 324 | - (void)prepareForInterfaceBuilder SWIFT_AVAILABILITY(ios,introduced=8.0); 325 | - (void)layoutSubviews; 326 | - (void)willMoveToWindow:(UIWindow * _Nullable)newWindow; 327 | - (void)didMoveToWindow; 328 | - (CGSize)sizeThatFits:(CGSize)size SWIFT_WARN_UNUSED_RESULT; 329 | - (void)animationDidStop:(CAAnimation * _Nonnull)anim finished:(BOOL)flag; 330 | SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly) Class _Nonnull layerClass;) 331 | + (Class _Nonnull)layerClass SWIFT_WARN_UNUSED_RESULT; 332 | - (void)drawLayer:(CALayer * _Nonnull)layer inContext:(CGContextRef _Nonnull)ctx; 333 | - (void)restartForViewController:(NSNotification * _Nonnull)notification; 334 | - (void)labelizeForController:(NSNotification * _Nonnull)notification; 335 | - (void)animateForController:(NSNotification * _Nonnull)notification; 336 | /// Immediately resets the label to the home position, cancelling any in-flight scroll animation, and restarts the scroll animation if the appropriate conditions are met. 337 | /// seealso: 338 | /// resetLabel 339 | /// seealso: 340 | /// triggerScrollStart 341 | - (void)restartLabel; 342 | /// Immediately resets the label to the home position, cancelling any in-flight scroll animation. 343 | /// The text is immediately returned to the home position. Scrolling will not resume automatically after a call to this method. 344 | /// To re-initiate scrolling use a call to restartLabel or triggerScrollStart, or make a change to a UILabel property such as text, bounds/frame, 345 | /// font, font size, etc. 346 | /// seealso: 347 | /// restartLabel 348 | /// seealso: 349 | /// triggerScrollStart 350 | - (void)shutdownLabel; 351 | - (void)labelWasTapped:(UIGestureRecognizer * _Nonnull)recognizer; 352 | - (UIView * _Nonnull)viewForBaselineLayout SWIFT_WARN_UNUSED_RESULT; 353 | @property (nonatomic, readonly, strong) UIView * _Nonnull viewForLastBaselineLayout; 354 | @property (nonatomic, copy) NSString * _Nullable text; 355 | @property (nonatomic, strong) NSAttributedString * _Nullable attributedText; 356 | @property (nonatomic, strong) UIFont * _Null_unspecified font; 357 | @property (nonatomic, strong) UIColor * _Null_unspecified textColor; 358 | @property (nonatomic, strong) UIColor * _Nullable backgroundColor; 359 | @property (nonatomic, strong) UIColor * _Nullable shadowColor; 360 | @property (nonatomic) CGSize shadowOffset; 361 | @property (nonatomic, strong) UIColor * _Nullable highlightedTextColor; 362 | @property (nonatomic, getter=isHighlighted) BOOL highlighted; 363 | @property (nonatomic, getter=isEnabled) BOOL enabled; 364 | @property (nonatomic) NSInteger numberOfLines; 365 | @property (nonatomic) UIBaselineAdjustment baselineAdjustment; 366 | @property (nonatomic, readonly) CGSize intrinsicContentSize; 367 | @property (nonatomic, strong) UIColor * _Null_unspecified tintColor; 368 | - (void)tintColorDidChange; 369 | @property (nonatomic) UIViewContentMode contentMode; 370 | @property (nonatomic) BOOL isAccessibilityElement; 371 | @end 372 | 373 | 374 | 375 | #if __has_attribute(external_source_symbol) 376 | # pragma clang attribute pop 377 | #endif 378 | #pragma clang diagnostic pop 379 | #endif 380 | -------------------------------------------------------------------------------- /Tweak/Liddell.m: -------------------------------------------------------------------------------- 1 | // 2 | // Liddell.m 3 | // Liddell 4 | // 5 | // Created by Alexandra (@Traurige) 6 | // 7 | 8 | #import "Liddell.h" 9 | 10 | BBServer* bbServer; 11 | 12 | #pragma mark - Notification class properties 13 | 14 | static UIView* liddellView(NCNotificationShortLookView* self, SEL _cmd) { 15 | return (UIView *)objc_getAssociatedObject(self, (void *)liddellView); 16 | }; 17 | static void setLiddellView(NCNotificationShortLookView* self, SEL _cmd, UIView* rawValue) { 18 | objc_setAssociatedObject(self, (void *)liddellView, rawValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 19 | } 20 | 21 | static UIBlurEffect* liddellBlur(NCNotificationShortLookView* self, SEL _cmd) { 22 | return (UIBlurEffect *)objc_getAssociatedObject(self, (void *)liddellBlur); 23 | }; 24 | static void setLiddellBlur(NCNotificationShortLookView* self, SEL _cmd, UIBlurEffect* rawValue) { 25 | objc_setAssociatedObject(self, (void *)liddellBlur, rawValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 26 | } 27 | 28 | static UIVisualEffectView* liddellBlurView(NCNotificationShortLookView* self, SEL _cmd) { 29 | return (UIVisualEffectView *)objc_getAssociatedObject(self, (void *)liddellBlurView); 30 | }; 31 | static void setLiddellBlurView(NCNotificationShortLookView* self, SEL _cmd, UIVisualEffectView* rawValue) { 32 | objc_setAssociatedObject(self, (void *)liddellBlurView, rawValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 33 | } 34 | 35 | static UIImageView* liddellIconView(NCNotificationShortLookView* self, SEL _cmd) { 36 | return (UIImageView *)objc_getAssociatedObject(self, (void *)liddellIconView); 37 | }; 38 | static void setLiddellIconView(NCNotificationShortLookView* self, SEL _cmd, UIImageView* rawValue) { 39 | objc_setAssociatedObject(self, (void *)liddellIconView, rawValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 40 | } 41 | 42 | static UILabel* liddellTitleLabel(NCNotificationShortLookView* self, SEL _cmd) { 43 | return (UILabel *)objc_getAssociatedObject(self, (void *)liddellTitleLabel); 44 | }; 45 | static void setLiddellTitleLabel(NCNotificationShortLookView* self, SEL _cmd, UILabel* rawValue) { 46 | objc_setAssociatedObject(self, (void *)liddellTitleLabel, rawValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 47 | } 48 | 49 | static UILabel* liddellContentLabel(NCNotificationShortLookView* self, SEL _cmd) { 50 | return (UILabel *)objc_getAssociatedObject(self, (void *)liddellContentLabel); 51 | }; 52 | static void setLiddellContentLabel(NCNotificationShortLookView* self, SEL _cmd, UILabel* rawValue) { 53 | objc_setAssociatedObject(self, (void *)liddellContentLabel, rawValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 54 | } 55 | 56 | #pragma mark - Notification class hooks 57 | 58 | void (* orig_NCNotificationShortLookView_didMoveToWindow)(NCNotificationShortLookView* self, SEL _cmd); 59 | void override_NCNotificationShortLookView_didMoveToWindow(NCNotificationShortLookView* self, SEL _cmd) { 60 | orig_NCNotificationShortLookView_didMoveToWindow(self, _cmd); 61 | 62 | if (![[self _viewControllerForAncestor] respondsToSelector:@selector(delegate)]) { 63 | return; 64 | } 65 | 66 | if (![[[self _viewControllerForAncestor] delegate] isKindOfClass:objc_getClass("SBNotificationBannerDestination")]) { 67 | return; 68 | } 69 | 70 | // get the notification title 71 | // the title property of the hooked class is always uppercase for some reason 72 | UIViewController* controller; 73 | NCNotificationRequest* request; 74 | if ([[[self nextResponder] nextResponder] nextResponder]) { 75 | controller = (UIViewController *)[[[self nextResponder] nextResponder] nextResponder]; 76 | if ([controller isKindOfClass:objc_getClass("NCNotificationShortLookViewController")] && [((NCNotificationShortLookViewController *) controller) notificationRequest]) { 77 | request = [((NCNotificationShortLookViewController *) controller) notificationRequest]; 78 | } 79 | } 80 | 81 | if (!request || ![request content]) { 82 | return; 83 | } 84 | 85 | NCNotificationContent* content = [request content]; 86 | 87 | // remove the original notification 88 | for (UIView* subview in [self subviews]) { 89 | if (subview == [self liddellView]) { 90 | continue; 91 | } 92 | [subview removeFromSuperview]; 93 | } 94 | 95 | UIImage* icon; 96 | if ([[[UIDevice currentDevice] systemVersion] floatValue] < 15.0) { 97 | icon = [self icons][0]; 98 | } else { 99 | icon = [self prominentIcon] ?: [self subordinateIcon]; 100 | } 101 | 102 | // liddell view 103 | if (![self liddellView]) { 104 | [self setLiddellView:[[UIView alloc] init]]; 105 | [[self liddellView] setClipsToBounds:YES]; 106 | [[[self liddellView] layer] setCornerRadius:pfCornerRadius]; 107 | 108 | if (pfBackgroundColor == kBackgroundColorTypeAdaptive) { 109 | [[self liddellView] setBackgroundColor:[[libKitten backgroundColor:icon] colorWithAlphaComponent:1]]; 110 | } else if (pfBackgroundColor == kBackgroundColorTypeCustom) { 111 | [[self liddellView] setBackgroundColor:[GcColorPickerUtils colorWithHex:pfCustomBackgroundColor]]; 112 | } 113 | 114 | if (pfBorderWidth != 0) { 115 | [[[self liddellView] layer] setBorderWidth:pfBorderWidth]; 116 | if (pfBorderColor == kBorderColorTypeAdaptive) { 117 | [[[self liddellView] layer] setBorderColor:[[[libKitten primaryColor:icon] colorWithAlphaComponent:1] CGColor]]; 118 | } else if (pfBorderColor == kBorderColorTypeCustom) { 119 | [[[self liddellView] layer] setBorderColor:[[GcColorPickerUtils colorWithHex:pfCustomBorderColor] CGColor]]; 120 | } 121 | } 122 | 123 | [self addSubview:[self liddellView]]; 124 | 125 | [[self liddellView] setTranslatesAutoresizingMaskIntoConstraints:NO]; 126 | [NSLayoutConstraint activateConstraints:@[ 127 | [[[self liddellView] topAnchor] constraintEqualToAnchor:[self topAnchor] constant:pfOffset], 128 | [[[self liddellView] leadingAnchor] constraintEqualToAnchor:[self leadingAnchor]], 129 | [[[self liddellView] trailingAnchor] constraintEqualToAnchor:[self trailingAnchor]], 130 | [[[self liddellView] heightAnchor] constraintEqualToConstant:pfHeight] 131 | ]]; 132 | } 133 | 134 | 135 | // blur view 136 | if (pfBlurMode != kBackgroundBlurTypeNone && ![self liddellBlurView]) { 137 | if (pfBlurMode == kBackgroundBlurTypeLight) { 138 | [self setLiddellBlur:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; 139 | } else if (pfBlurMode == kBackgroundBlurTypeDark) { 140 | [self setLiddellBlur:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]]; 141 | } else if (pfBlurMode == kBackgroundBlurTypeAdaptive) { 142 | [self setLiddellBlur:[UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular]]; 143 | } 144 | 145 | [self setLiddellBlurView:[[UIVisualEffectView alloc] initWithEffect:[self liddellBlur]]]; 146 | [[self liddellView] addSubview:[self liddellBlurView]]; 147 | 148 | [[self liddellBlurView] setTranslatesAutoresizingMaskIntoConstraints:NO]; 149 | [NSLayoutConstraint activateConstraints:@[ 150 | [[[self liddellBlurView] topAnchor] constraintEqualToAnchor:[[self liddellView] topAnchor]], 151 | [[[self liddellBlurView] leadingAnchor] constraintEqualToAnchor:[[self liddellView] leadingAnchor]], 152 | [[[self liddellBlurView] trailingAnchor] constraintEqualToAnchor:[[self liddellView] trailingAnchor]], 153 | [[[self liddellBlurView] bottomAnchor] constraintEqualToAnchor:[[self liddellView] bottomAnchor]] 154 | ]]; 155 | } 156 | 157 | 158 | // icon view 159 | if (pfShowIcon && ![self liddellIconView]) { 160 | [self setLiddellIconView:[[UIImageView alloc] init]]; 161 | [[self liddellIconView] setImage:icon]; 162 | [[self liddellIconView] setContentMode:UIViewContentModeScaleAspectFit]; 163 | [[self liddellIconView] setClipsToBounds:YES]; 164 | 165 | if (pfIconCornerRadius == -1) { 166 | [[[self liddellIconView] layer] setCornerRadius:(pfHeight - 13) / 2]; 167 | } else { 168 | [[[self liddellIconView] layer] setCornerRadius:pfIconCornerRadius]; 169 | } 170 | 171 | [[self liddellView] addSubview:[self liddellIconView]]; 172 | 173 | [[self liddellIconView] setTranslatesAutoresizingMaskIntoConstraints:NO]; 174 | [NSLayoutConstraint activateConstraints:@[ 175 | [[[self liddellIconView] leadingAnchor] constraintEqualToAnchor:[[self liddellView] leadingAnchor] constant:8], 176 | [[[self liddellIconView] centerYAnchor] constraintEqualToAnchor:[[self liddellView] centerYAnchor]], 177 | [[[self liddellIconView] heightAnchor] constraintEqualToConstant:pfHeight - 13], 178 | [[[self liddellIconView] widthAnchor] constraintEqualToConstant:pfHeight - 13] 179 | ]]; 180 | } 181 | 182 | 183 | // title label 184 | if (pfShowTitle && ![self liddellTitleLabel]) { 185 | [self setLiddellTitleLabel:[[UILabel alloc] init]]; 186 | [[self liddellTitleLabel] setText:[content header]]; 187 | [[self liddellTitleLabel] setFont:[UIFont boldSystemFontOfSize:pfTitleFontSize]]; 188 | if (pfTextContent == kTextColorContentTypeTitle || pfTextContent == kTextColorContentTypeBoth) { 189 | if (pfTextColor == kTextColorTypeBackground) { 190 | if (pfBackgroundColor == kBackgroundColorTypeNone) { 191 | if (![[[self liddellBlurView] effect] isEqual:[UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular]]) { 192 | if ([[[self liddellBlurView] effect] isEqual:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]]) { 193 | [[self liddellTitleLabel] setTextColor:[UIColor whiteColor]]; 194 | } else if ([[[self liddellBlurView] effect] isEqual:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]) { 195 | [[self liddellTitleLabel] setTextColor:[UIColor blackColor]]; 196 | } 197 | } else { 198 | [[self liddellTitleLabel] setTextColor:[UIColor labelColor]]; 199 | } 200 | } else { 201 | if ([libKitten isDarkColor:[[self liddellView] backgroundColor]]) { 202 | [[self liddellTitleLabel] setTextColor:[UIColor whiteColor]]; 203 | } else if (![libKitten isDarkColor:[[self liddellView] backgroundColor]]) { 204 | [[self liddellTitleLabel] setTextColor:[UIColor blackColor]]; 205 | } 206 | } 207 | } else if (pfTextColor == kTextColorTypeAdaptive) { 208 | [[self liddellTitleLabel] setTextColor:[libKitten secondaryColor:icon]]; 209 | } else if (pfTextColor == kTextColorTypeCustom) { 210 | [[self liddellTitleLabel] setTextColor:[GcColorPickerUtils colorWithHex:pfCustomTextColor]]; 211 | } 212 | } 213 | [[self liddellView] addSubview:[self liddellTitleLabel]]; 214 | 215 | [[self liddellTitleLabel] setTranslatesAutoresizingMaskIntoConstraints:NO]; 216 | if (pfShowIcon && [self liddellIconView]) { 217 | [NSLayoutConstraint activateConstraints:@[ 218 | [[[self liddellTitleLabel] leadingAnchor] constraintEqualToAnchor:[[self liddellIconView] trailingAnchor] constant:8], 219 | [[[self liddellTitleLabel] centerYAnchor] constraintEqualToAnchor:[[self liddellView] centerYAnchor]] 220 | ]]; 221 | } else { 222 | [NSLayoutConstraint activateConstraints:@[ 223 | [[[self liddellTitleLabel] leadingAnchor] constraintEqualToAnchor:[[self liddellView] leadingAnchor] constant:8], 224 | [[[self liddellTitleLabel] centerYAnchor] constraintEqualToAnchor:[[self liddellView] centerYAnchor]] 225 | ]]; 226 | } 227 | } 228 | 229 | 230 | // content label 231 | if (pfShowMessage && ![self liddellContentLabel]) { 232 | [self setLiddellContentLabel:[[MarqueeLabel alloc] init]]; 233 | 234 | // some apps send notifications starting with a line break, which causes the message to be hidden 235 | if ([self primaryText] && [self secondaryText]) { 236 | [[self liddellContentLabel] setText:[NSString stringWithFormat:@"%@: %@", [self primaryText], [self secondaryText]]]; 237 | } else { 238 | [[self liddellContentLabel] setText:[[self secondaryText] stringByReplacingOccurrencesOfString:@"\n" withString:@": "]]; 239 | } 240 | 241 | [[self liddellContentLabel] setFont:[UIFont systemFontOfSize:pfContentFontSize]]; 242 | if (pfTextContent == kTextColorContentTypeContent || pfTextContent == kTextColorContentTypeBoth) { 243 | if (pfTextColor == kTextColorContentTypeTitle) { 244 | if (pfBackgroundColor == kBackgroundColorTypeNone) { 245 | if (![[[self liddellBlurView] effect] isEqual:[UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular]]) { 246 | if ([[[self liddellBlurView] effect] isEqual:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]]) { 247 | [[self liddellContentLabel] setTextColor:[UIColor whiteColor]]; 248 | } else if ([[[self liddellBlurView] effect] isEqual:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]) { 249 | [[self liddellContentLabel] setTextColor:[UIColor blackColor]]; 250 | } 251 | } else { 252 | [[self liddellContentLabel] setTextColor:[UIColor labelColor]]; 253 | } 254 | } else { 255 | if ([libKitten isDarkColor:[[self liddellView] backgroundColor]]) { 256 | [[self liddellContentLabel] setTextColor:[UIColor whiteColor]]; 257 | } else if (![libKitten isDarkColor:[[self liddellView] backgroundColor]]) { 258 | [[self liddellContentLabel] setTextColor:[UIColor blackColor]]; 259 | } 260 | } 261 | } else if (pfTextColor == kTextColorTypeAdaptive) { 262 | [[self liddellContentLabel] setTextColor:[libKitten secondaryColor:icon]]; 263 | } else if (pfTextColor == kTextColorTypeCustom) { 264 | [[self liddellContentLabel] setTextColor:[GcColorPickerUtils colorWithHex:pfCustomTextColor]]; 265 | } 266 | } 267 | [[self liddellContentLabel] setScrollRate:pfScrollRate]; 268 | [[self liddellContentLabel] setFadeLength:5]; 269 | [[self liddellView] addSubview:[self liddellContentLabel]]; 270 | 271 | [[self liddellContentLabel] setTranslatesAutoresizingMaskIntoConstraints:NO]; 272 | if ((pfShowIcon && pfShowTitle) || (!pfShowIcon && pfShowTitle)) { 273 | [NSLayoutConstraint activateConstraints:@[ 274 | [[[self liddellContentLabel] leadingAnchor] constraintEqualToAnchor:[[self liddellTitleLabel] trailingAnchor] constant:8], 275 | [[[self liddellContentLabel] trailingAnchor] constraintEqualToAnchor:[[self liddellView] trailingAnchor] constant:-12], 276 | [[[self liddellContentLabel] centerYAnchor] constraintEqualToAnchor:[[self liddellView] centerYAnchor]] 277 | ]]; 278 | } else if (pfShowIcon && !pfShowTitle) { 279 | [NSLayoutConstraint activateConstraints:@[ 280 | [[[self liddellContentLabel] leadingAnchor] constraintEqualToAnchor:[[self liddellIconView] trailingAnchor] constant:8], 281 | [[[self liddellContentLabel] trailingAnchor] constraintEqualToAnchor:[[self liddellView] trailingAnchor] constant:-12], 282 | [[[self liddellContentLabel] centerYAnchor] constraintEqualToAnchor:[[self liddellView] centerYAnchor]] 283 | ]]; 284 | } else if (!(pfShowIcon && [self liddellIconView]) && !(pfShowTitle && [self liddellTitleLabel])) { 285 | [NSLayoutConstraint activateConstraints:@[ 286 | [[[self liddellContentLabel] leadingAnchor] constraintEqualToAnchor:[[self liddellView] leadingAnchor] constant:8], 287 | [[[self liddellContentLabel] trailingAnchor] constraintEqualToAnchor:[[self liddellView] trailingAnchor] constant:-12], 288 | [[[self liddellContentLabel] centerYAnchor] constraintEqualToAnchor:[[self liddellView] centerYAnchor]] 289 | ]]; 290 | } 291 | } 292 | 293 | // the title is hidden behind the content label if the content label is too long 294 | // bringing it to the front fixes that issue 295 | [[self liddellView] bringSubviewToFront:[self liddellTitleLabel]]; 296 | } 297 | 298 | void (* orig_NCNotificationShortLookView__setGrabberVisible)(NCNotificationShortLookView* self, SEL _cmd, BOOL visible); 299 | void override_NCNotificationShortLookView__setGrabberVisible(NCNotificationShortLookView* self, SEL _cmd, BOOL visible) { 300 | orig_NCNotificationShortLookView__setGrabberVisible(self, _cmd, NO); 301 | } 302 | 303 | BBServer* (* orig_BBServer_initWithQueue)(BBServer* self, SEL _cmd, OS_dispatch_queue_serial* queue); 304 | BBServer* override_BBServer_initWithQueue(BBServer* self, SEL _cmd, OS_dispatch_queue_serial* queue) { 305 | bbServer = orig_BBServer_initWithQueue(self, _cmd, queue); 306 | bbQueue = [self valueForKey:@"_queue"]; 307 | return bbServer; 308 | } 309 | 310 | #pragma mark - Notification callbacks 311 | 312 | static void show_test_banner() { 313 | BBBulletin* bulletin = [[objc_getClass("BBBulletin") alloc] init]; 314 | NSProcessInfo* processInfo = [NSProcessInfo processInfo]; 315 | 316 | SBIconModel* model = [(SBIconController *)[objc_getClass("SBIconController") sharedInstance] model]; 317 | NSArray* bundleIdentifiers = [[model visibleIconIdentifiers] allObjects]; 318 | 319 | [bulletin setTitle:@"Liddell"]; 320 | [bulletin setMessage:@"Little test banner coming your way!"]; 321 | [bulletin setSectionID:bundleIdentifiers[arc4random_uniform([bundleIdentifiers count])]]; 322 | [bulletin setBulletinID:[processInfo globallyUniqueString]]; 323 | [bulletin setRecordID:[processInfo globallyUniqueString]]; 324 | [bulletin setDate:[NSDate date]]; 325 | 326 | if ([bbServer respondsToSelector:@selector(publishBulletin:destinations:)]) { 327 | dispatch_sync(bbQueue, ^{ 328 | [bbServer publishBulletin:bulletin destinations:15]; 329 | }); 330 | } 331 | } 332 | 333 | #pragma mark - Preferences 334 | 335 | static void load_preferences() { 336 | preferences = [[NSUserDefaults alloc] initWithSuiteName:@"dev.traurige.liddell.preferences"]; 337 | 338 | [preferences registerDefaults:@{ 339 | kPreferenceKeyEnabled: @(kPreferenceKeyEnabledDefaultValue), 340 | kPreferenceKeyShowIcon: @(kPreferenceKeyShowIconDefaultValue), 341 | kPreferenceKeyShowTitle: @(kPreferenceKeyShowTitleDefaultValue), 342 | kPreferenceKeyShowMessage: @(kPreferenceKeyShowMessageDefaultValue), 343 | kPreferenceKeyHeight: @(kPreferenceKeyHeightDefaultValue), 344 | kPreferenceKeyCornerRadius: @(kPreferenceKeyCornerRadiusDefaultValue), 345 | kPreferenceKeyOffset: @(kPreferenceKeyOffsetDefaultValue), 346 | kPreferenceKeyScrollRate: @(kPreferenceKeyScrollRateDefaultValue), 347 | kPreferenceKeyBackgroundColor: @(kPreferenceKeyBackgroundColorDefaultValue), 348 | kPreferenceKeyCustomBackgroundColor: kPreferenceKeyCustomBackgroundColorDefaultValue, 349 | kPreferenceKeyBlurMode: @(kPreferenceKeyBlurModeDefaultValue), 350 | kPreferenceKeyIconCornerRadius: @(kPreferenceKeyIconCornerRadiusDefaultValue), 351 | kPreferenceKeyTextColor: @(kPreferenceKeyTextColorDefaultValue), 352 | kPreferenceKeyCustomTextColor: kPreferenceKeyCustomTextColorDefaultValue, 353 | kPreferenceKeyTextContent: @(kPreferenceKeyTextContentDefaultValue), 354 | kPreferenceKeyTitleFontSize: @(kPreferenceKeyTitleFontSizeDefaultValue), 355 | kPreferenceKeyContentFontSize: @(kPreferenceKeyContentFontSizeDefaultValue), 356 | kPreferenceKeyBorderWidth: @(kPreferenceKeyBorderWidthDefaultValue), 357 | kPreferenceKeyBorderColor: @(kPreferenceKeyBorderColorDefaultValue), 358 | kPreferenceKeyCustomBorderColor: kPreferenceKeyCustomBorderColorDefaultValue 359 | }]; 360 | 361 | pfEnabled = [[preferences objectForKey:kPreferenceKeyEnabled] boolValue]; 362 | pfShowIcon = [[preferences objectForKey:kPreferenceKeyShowIcon] boolValue]; 363 | pfShowTitle = [[preferences objectForKey:kPreferenceKeyShowTitle] boolValue]; 364 | pfShowMessage = [[preferences objectForKey:kPreferenceKeyShowMessage] boolValue]; 365 | pfHeight = [[preferences objectForKey:kPreferenceKeyHeight] floatValue]; 366 | pfCornerRadius = [[preferences objectForKey:kPreferenceKeyCornerRadius] floatValue]; 367 | pfOffset = [[preferences objectForKey:kPreferenceKeyOffset] floatValue]; 368 | pfScrollRate = [[preferences objectForKey:kPreferenceKeyScrollRate] floatValue]; 369 | pfBackgroundColor = [[preferences objectForKey:kPreferenceKeyBackgroundColor] intValue]; 370 | pfCustomBackgroundColor = [preferences objectForKey:kPreferenceKeyCustomBackgroundColor]; 371 | pfBlurMode = [[preferences objectForKey:kPreferenceKeyBlurMode] intValue]; 372 | pfIconCornerRadius = [[preferences objectForKey:kPreferenceKeyIconCornerRadius] floatValue]; 373 | pfTextColor = [[preferences objectForKey:kPreferenceKeyTextColor] intValue]; 374 | pfCustomTextColor = [preferences objectForKey:kPreferenceKeyCustomTextColor]; 375 | pfTextContent = [[preferences objectForKey:kPreferenceKeyTextContent] intValue]; 376 | pfTitleFontSize = [[preferences objectForKey:kPreferenceKeyTitleFontSize] floatValue]; 377 | pfContentFontSize = [[preferences objectForKey:kPreferenceKeyContentFontSize] floatValue]; 378 | pfBorderWidth = [[preferences objectForKey:kPreferenceKeyBorderWidth] floatValue]; 379 | pfBorderColor = [[preferences objectForKey:kPreferenceKeyBorderColor] intValue]; 380 | pfCustomBorderColor = [preferences objectForKey:kPreferenceKeyCustomBorderColor]; 381 | } 382 | 383 | #pragma mark - Constructor 384 | 385 | __attribute__((constructor)) static void initialize() { 386 | load_preferences(); 387 | 388 | if (!pfEnabled) { 389 | return; 390 | } 391 | 392 | class_addProperty(NSClassFromString(@"NCNotificationShortLookView"), "liddellView", (objc_property_attribute_t[]){{"T", "@\"UIView\""}, {"N", ""}, {"V", "_liddellView"}}, 3); 393 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(liddellView), (IMP)&liddellView, "@@:"); 394 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(setLiddellView:), (IMP)&setLiddellView, "v@:@"); 395 | class_addProperty(NSClassFromString(@"NCNotificationShortLookView"), "liddellBlur", (objc_property_attribute_t[]){{"T", "@\"UIBlurEffect\""}, {"N", ""}, {"V", "_liddellBlur"}}, 3); 396 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(liddellBlur), (IMP)&liddellBlur, "@@:"); 397 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(setLiddellBlur:), (IMP)&setLiddellBlur, "v@:@"); 398 | class_addProperty(NSClassFromString(@"NCNotificationShortLookView"), "liddellBlurView", (objc_property_attribute_t[]){{"T", "@\"UIVisualEffectView\""}, {"N", ""}, {"V", "_liddellBlurView"}}, 3); 399 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(liddellBlurView), (IMP)&liddellBlurView, "@@:"); 400 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(setLiddellBlurView:), (IMP)&setLiddellBlurView, "v@:@"); 401 | class_addProperty(NSClassFromString(@"NCNotificationShortLookView"), "liddellIconView", (objc_property_attribute_t[]){{"T", "@\"UIImageView\""}, {"N", ""}, {"V", "_liddellIconView"}}, 3); 402 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(liddellIconView), (IMP)&liddellIconView, "@@:"); 403 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(setLiddellIconView:), (IMP)&setLiddellIconView, "v@:@"); 404 | class_addProperty(NSClassFromString(@"NCNotificationShortLookView"), "liddellTitleLabel", (objc_property_attribute_t[]){{"T", "@\"UILabel\""}, {"N", ""}, {"V", "_liddellTitleLabel"}}, 3); 405 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(liddellTitleLabel), (IMP)&liddellTitleLabel, "@@:"); 406 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(setLiddellTitleLabel:), (IMP)&setLiddellTitleLabel, "v@:@"); 407 | class_addProperty(NSClassFromString(@"NCNotificationShortLookView"), "liddellContentLabel", (objc_property_attribute_t[]){{"T", "@\"UILabel\""}, {"N", ""}, {"V", "_liddellContentLabel"}}, 3); 408 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(liddellContentLabel), (IMP)&liddellContentLabel, "@@:"); 409 | class_addMethod(NSClassFromString(@"NCNotificationShortLookView"), @selector(setLiddellContentLabel:), (IMP)&setLiddellContentLabel, "v@:@"); 410 | 411 | MSHookMessageEx(NSClassFromString(@"NCNotificationShortLookView"), @selector(didMoveToWindow), (IMP)&override_NCNotificationShortLookView_didMoveToWindow, (IMP *)&orig_NCNotificationShortLookView_didMoveToWindow); 412 | MSHookMessageEx(NSClassFromString(@"NCNotificationShortLookView"), @selector(_setGrabberVisible:), (IMP)&override_NCNotificationShortLookView__setGrabberVisible, (IMP *)&orig_NCNotificationShortLookView__setGrabberVisible); 413 | MSHookMessageEx(NSClassFromString(@"BBServer"), @selector(initWithQueue:), (IMP)&override_BBServer_initWithQueue, (IMP *)&orig_BBServer_initWithQueue); 414 | 415 | CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, (CFNotificationCallback)show_test_banner, (CFStringRef)@"dev.traurige.liddell.test_banner", NULL, (CFNotificationSuspensionBehavior)kNilOptions); 416 | CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, (CFNotificationCallback)load_preferences, (CFStringRef)@"dev.traurige.liddell.preferences.reload", NULL, (CFNotificationSuspensionBehavior)kNilOptions); 417 | } 418 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Tweak/MarqueeLabel.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MarqueeLabel.swift 3 | // 4 | // Created by Charles Powell on 8/6/14. 5 | // Copyright (c) 2015 Charles Powell. All rights reserved. 6 | // 7 | 8 | import UIKit 9 | import QuartzCore 10 | 11 | @IBDesignable 12 | 13 | open class MarqueeLabel: UILabel, CAAnimationDelegate { 14 | 15 | /** 16 | An enum that defines the types of `MarqueeLabel` scrolling 17 | 18 | - Left: Scrolls left after the specified delay, and does not return to the original position. 19 | - LeftRight: Scrolls left first, then back right to the original position. 20 | - Right: Scrolls right after the specified delay, and does not return to the original position. 21 | - RightLeft: Scrolls right first, then back left to the original position. 22 | - Continuous: Continuously scrolls left (with a pause at the original position if animationDelay is set). 23 | - ContinuousReverse: Continuously scrolls right (with a pause at the original position if animationDelay is set). 24 | */ 25 | public enum MarqueeType: CaseIterable { 26 | case left 27 | case leftRight 28 | case right 29 | case rightLeft 30 | case continuous 31 | case continuousReverse 32 | } 33 | 34 | // 35 | // MARK: - Public properties 36 | // 37 | 38 | /** 39 | Defines the direction and method in which the `MarqueeLabel` instance scrolls. 40 | `MarqueeLabel` supports six default types of scrolling: `Left`, `LeftRight`, `Right`, `RightLeft`, `Continuous`, and `ContinuousReverse`. 41 | 42 | Given the nature of how text direction works, the options for the `type` property require specific text alignments 43 | and will set the textAlignment property accordingly. 44 | 45 | - `LeftRight` and `Left` types are ONLY compatible with a label text alignment of `NSTextAlignment.left`. 46 | - `RightLeft` and `Right` types are ONLY compatible with a label text alignment of `NSTextAlignment.right`. 47 | - `Continuous` and `ContinuousReverse` allow the use of `NSTextAlignment.left`, `.right`, or `.center` alignments, 48 | however the text alignment only has an effect when label text is short enough that scrolling is not required. 49 | When scrolling, the labels are effectively center-aligned. 50 | 51 | Defaults to `Continuous`. 52 | 53 | - Note: Note that any `leadingBuffer` value will affect the text alignment location relative to the frame position, 54 | including with `.center` alignment, where the center alignment location will be shifted left (for `.continuous`) or 55 | right (for `.continuousReverse`) by one-half (1/2) the `.leadingBuffer` amount. Use the `.trailingBuffer` property to 56 | add a buffer between text "loops" without affecting alignment location. 57 | 58 | - SeeAlso: textAlignment 59 | - SeeAlso: leadingBuffer 60 | */ 61 | open var type: MarqueeType = .continuous { 62 | didSet { 63 | if type == oldValue { 64 | return 65 | } 66 | updateAndScroll() 67 | } 68 | } 69 | 70 | /** 71 | An optional custom scroll "sequence", defined by an array of `ScrollStep` or `FadeStep` instances. A sequence 72 | defines a single scroll/animation loop, which will continue to be automatically repeated like the default types. 73 | 74 | A `type` value is still required when using a custom sequence. The `type` value defines the `home` and `away` 75 | values used in the `ScrollStep` instances, and the `type` value determines which way the label will scroll. 76 | 77 | When a custom sequence is not supplied, the default sequences are used per the defined `type`. 78 | 79 | `ScrollStep` steps are the primary step types, and define the position of the label at a given time in the sequence. 80 | `FadeStep` steps are secondary steps that define the edge fade state (leading, trailing, or both) around the `ScrollStep` 81 | steps. 82 | 83 | Defaults to nil. 84 | 85 | - Attention: Use of the `scrollSequence` property requires understanding of how MarqueeLabel works for effective 86 | use. As a reference, it is suggested to review the methodology used to build the sequences for the default types. 87 | 88 | - SeeAlso: type 89 | - SeeAlso: ScrollStep 90 | - SeeAlso: FadeStep 91 | */ 92 | open var scrollSequence: [MarqueeStep]? 93 | 94 | /** 95 | Specifies the animation curve used in the scrolling motion of the labels. 96 | Allowable options: 97 | 98 | - `UIViewAnimationOptionCurveEaseInOut` 99 | - `UIViewAnimationOptionCurveEaseIn` 100 | - `UIViewAnimationOptionCurveEaseOut` 101 | - `UIViewAnimationOptionCurveLinear` 102 | 103 | Defaults to `UIViewAnimationOptionCurveEaseInOut`. 104 | */ 105 | open var animationCurve: UIView.AnimationCurve = .linear 106 | 107 | /** 108 | A boolean property that sets whether the `MarqueeLabel` should behave like a normal `UILabel`. 109 | 110 | When set to `true` the `MarqueeLabel` will behave and look like a normal `UILabel`, and will not begin any scrolling animations. 111 | Changes to this property take effect immediately, removing any in-flight animation as well as any edge fade. Note that `MarqueeLabel` 112 | will respect the current values of the `lineBreakMode` and `textAlignment`properties while labelized. 113 | 114 | To simply prevent automatic scrolling, use the `holdScrolling` property. 115 | 116 | Defaults to `false`. 117 | 118 | - SeeAlso: holdScrolling 119 | - SeeAlso: lineBreakMode 120 | - Note: The label will not automatically scroll when this property is set to `true`. 121 | - Warning: The UILabel default setting for the `lineBreakMode` property is `NSLineBreakByTruncatingTail`, which truncates 122 | the text adds an ellipsis glyph (...). Set the `lineBreakMode` property to `NSLineBreakByClipping` in order to avoid the 123 | ellipsis, especially if using an edge transparency fade. 124 | */ 125 | @IBInspectable open var labelize: Bool = false { 126 | didSet { 127 | if labelize != oldValue { 128 | updateAndScroll() 129 | } 130 | } 131 | } 132 | 133 | /** 134 | A boolean property that sets whether the `MarqueeLabel` should hold (prevent) automatic label scrolling. 135 | 136 | When set to `true`, `MarqueeLabel` will not automatically scroll even its text is larger than the specified frame, 137 | although the specified edge fades will remain. 138 | 139 | To set `MarqueeLabel` to act like a normal UILabel, use the `labelize` property. 140 | 141 | Defaults to `false`. 142 | 143 | - Note: The label will not automatically scroll when this property is set to `true`. 144 | - SeeAlso: labelize 145 | */ 146 | @IBInspectable open var holdScrolling: Bool = false { 147 | didSet { 148 | if holdScrolling != oldValue { 149 | if oldValue == true && !(awayFromHome || labelize ) && labelShouldScroll() { 150 | updateAndScroll() 151 | } 152 | } 153 | } 154 | } 155 | 156 | /** 157 | A boolean property that sets whether the `MarqueeLabel` should scroll, even if the specificed test string 158 | can be fully contained within the label frame. 159 | 160 | If this property is set to `true`, the `MarqueeLabel` will automatically scroll regardless of text string 161 | length, although this can still be overridden by the `tapToScroll` and `holdScrolling` properties. 162 | 163 | Defaults to `false`. 164 | 165 | - Warning: Forced scrolling may have unexpected edge cases or have unusual characteristics compared to the 166 | 'normal' scrolling feature. 167 | 168 | - SeeAlso: holdScrolling 169 | - SeeAlso: tapToScroll 170 | */ 171 | @IBInspectable public var forceScrolling: Bool = false { 172 | didSet { 173 | if forceScrolling != oldValue { 174 | if !(awayFromHome || holdScrolling || tapToScroll ) && labelShouldScroll() { 175 | updateAndScroll() 176 | } 177 | } 178 | } 179 | } 180 | 181 | /** 182 | A boolean property that sets whether the `MarqueeLabel` should only begin a scroll when tapped. 183 | 184 | If this property is set to `true`, the `MarqueeLabel` will only begin a scroll animation cycle when tapped. The label will 185 | not automatically being a scroll. This setting overrides the setting of the `holdScrolling` property. 186 | 187 | Defaults to `false`. 188 | 189 | - Note: The label will not automatically scroll when this property is set to `false`. 190 | - SeeAlso: holdScrolling 191 | */ 192 | @IBInspectable open var tapToScroll: Bool = false { 193 | didSet { 194 | if tapToScroll != oldValue { 195 | if tapToScroll { 196 | let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MarqueeLabel.labelWasTapped(_:))) 197 | self.addGestureRecognizer(tapRecognizer) 198 | isUserInteractionEnabled = true 199 | } else { 200 | if let recognizer = self.gestureRecognizers!.first as UIGestureRecognizer? { 201 | self.removeGestureRecognizer(recognizer) 202 | } 203 | isUserInteractionEnabled = false 204 | } 205 | } 206 | } 207 | } 208 | 209 | /** 210 | A read-only boolean property that indicates if the label's scroll animation has been paused. 211 | 212 | - SeeAlso: pauseLabel 213 | - SeeAlso: unpauseLabel 214 | */ 215 | open var isPaused: Bool { 216 | return (sublabel.layer.speed == 0.0) 217 | } 218 | 219 | /** 220 | A boolean property that indicates if the label is currently away from the home location. 221 | 222 | The "home" location is the traditional location of `UILabel` text. This property essentially reflects if a scroll animation is underway. 223 | */ 224 | open var awayFromHome: Bool { 225 | if let presentationLayer = sublabel.layer.presentation() { 226 | return !(presentationLayer.position.x == homeLabelFrame.origin.x) 227 | } 228 | 229 | return false 230 | } 231 | 232 | /** 233 | An optional CGFloat computed value that provides the current scroll animation position, as a value between 234 | 0.0 and 1.0. A value of 0.0 indicates the label is "at home" (`awayFromHome` will be false). A value 235 | of 1.0 indicates the label is at the "away" position (and `awayFromHome` will be true). 236 | 237 | Will return nil when the label presentation layer is nil. 238 | 239 | - Note: For `leftRight` and `rightLeft` type labels this value will increase and reach 1.0 when the label animation reaches the 240 | maximum displacement, as the left or right edge of the label (respectively) is shown. As the scroll reverses, 241 | the value will decrease back to 0.0. 242 | 243 | - Note: For `continuous` and`continuousReverse` type labels, this value will increase from 0.0 and reach 1.0 just as the 244 | label loops around and comes to a stop at the original home position. When that position is reached, the value will 245 | jump from 1.0 directly to 0.0 and begin to increase from 0.0 again. 246 | */ 247 | open var animationPosition: CGFloat? { 248 | guard let presentationLayer = sublabel.layer.presentation() else { 249 | return nil 250 | } 251 | 252 | // No dividing by zero! 253 | if awayOffset == 0.0 { 254 | return 0.0 255 | } 256 | 257 | let progressFraction = abs((presentationLayer.position.x - homeLabelFrame.origin.x) / awayOffset) 258 | return progressFraction 259 | } 260 | 261 | /** 262 | The `MarqueeLabel` scrolling speed may be defined by one of two ways: 263 | - Rate(CGFloat): The speed is defined by a rate of motion, in units of points per second. 264 | - Duration(CGFloat): The speed is defined by the time to complete a scrolling animation cycle, in units of seconds. 265 | 266 | Each case takes an associated `CGFloat` value, which is the rate/duration desired. 267 | */ 268 | public enum SpeedLimit { 269 | case rate(CGFloat) 270 | case duration(CGFloat) 271 | 272 | var value: CGFloat { 273 | switch self { 274 | case .rate(let rate): 275 | return rate 276 | case .duration(let duration): 277 | return duration 278 | } 279 | } 280 | } 281 | 282 | /** 283 | Defines the speed of the `MarqueeLabel` scrolling animation. 284 | 285 | The speed is set by specifying a case of the `SpeedLimit` enum along with an associated value. 286 | 287 | - SeeAlso: SpeedLimit 288 | */ 289 | open var speed: SpeedLimit = .duration(7.0) { 290 | didSet { 291 | switch (speed, oldValue) { 292 | case (.rate(let a), .rate(let b)) where a == b: 293 | return 294 | case (.duration(let a), .duration(let b)) where a == b: 295 | return 296 | default: 297 | updateAndScroll() 298 | } 299 | } 300 | } 301 | 302 | @available(*, deprecated, message: "Use speed property instead") 303 | @IBInspectable open var scrollDuration: CGFloat { 304 | get { 305 | switch speed { 306 | case .duration(let duration): return duration 307 | case .rate(_): return 0.0 308 | } 309 | } 310 | set { 311 | speed = .duration(newValue) 312 | } 313 | } 314 | 315 | @available(*, deprecated, message : "Use speed property instead") 316 | @IBInspectable open var scrollRate: CGFloat { 317 | get { 318 | switch speed { 319 | case .duration(_): return 0.0 320 | case .rate(let rate): return rate 321 | } 322 | } 323 | set { 324 | speed = .rate(newValue) 325 | } 326 | } 327 | 328 | 329 | /** 330 | A buffer (offset) between the leading edge of the label text and the label frame. 331 | 332 | This property adds additional space between the leading edge of the label text and the label frame. The 333 | leading edge is the edge of the label text facing the direction of scroll (i.e. the edge that animates 334 | offscreen first during scrolling). 335 | 336 | Defaults to `0`. 337 | 338 | - Note: The value set to this property affects label positioning at all times (including when `labelize` is set to `true`), 339 | including when the text string length is short enough that the label does not need to scroll. 340 | - Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength` 341 | is used as spacing between the two label instances. Zero is an allowable value for all three properties. 342 | 343 | - SeeAlso: trailingBuffer 344 | */ 345 | @IBInspectable open var leadingBuffer: CGFloat = 0.0 { 346 | didSet { 347 | if leadingBuffer != oldValue { 348 | updateAndScroll() 349 | } 350 | } 351 | } 352 | 353 | /** 354 | A buffer (offset) between the trailing edge of the label text and the label frame. 355 | 356 | This property adds additional space (buffer) between the trailing edge of the label text and the label frame. The 357 | trailing edge is the edge of the label text facing away from the direction of scroll (i.e. the edge that animates 358 | offscreen last during scrolling). 359 | 360 | Defaults to `0`. 361 | 362 | - Note: The value set to this property has no effect when the `labelize` property is set to `true`. 363 | 364 | - Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength` 365 | is used as spacing between the two label instances. Zero is an allowable value for all three properties. 366 | 367 | - SeeAlso: leadingBuffer 368 | */ 369 | @IBInspectable open var trailingBuffer: CGFloat = 0.0 { 370 | didSet { 371 | if trailingBuffer != oldValue { 372 | updateAndScroll() 373 | } 374 | } 375 | } 376 | 377 | /** 378 | The length of transparency fade at the left and right edges of the frame. 379 | 380 | This propery sets the size (in points) of the view edge transparency fades on the left and right edges of a `MarqueeLabel`. The 381 | transparency fades from an alpha of 1.0 (fully visible) to 0.0 (fully transparent) over this distance. Values set to this property 382 | will be sanitized to prevent a fade length greater than 1/2 of the frame width. 383 | 384 | Defaults to `0`. 385 | */ 386 | @IBInspectable open var fadeLength: CGFloat = 0.0 { 387 | didSet { 388 | if fadeLength != oldValue { 389 | applyGradientMask(fadeLength, animated: true) 390 | updateAndScroll() 391 | } 392 | } 393 | } 394 | 395 | 396 | /** 397 | The length of delay in seconds that the label pauses at the completion of a scroll. 398 | */ 399 | @IBInspectable open var animationDelay: CGFloat = 1.0 400 | 401 | 402 | /** The read-only/computed duration of the scroll animation (not including delay). 403 | 404 | The value of this property is calculated from the value set to the `speed` property. If a duration-type speed is 405 | used to set the label animation speed, `animationDuration` will be equivalent to that value. 406 | */ 407 | public var animationDuration: CGFloat { 408 | switch self.speed { 409 | case .rate(let rate): 410 | return CGFloat(abs(self.awayOffset) / rate) 411 | case .duration(let duration): 412 | return duration 413 | } 414 | } 415 | 416 | // 417 | // MARK: - Class Functions and Helpers 418 | // 419 | 420 | /** 421 | Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain. 422 | 423 | - Parameter controller: The view controller for which to restart all `MarqueeLabel` instances. 424 | 425 | - Warning: View controllers that appear with animation (such as from underneath a modal-style controller) can cause some `MarqueeLabel` text 426 | position "jumping" when this method is used in `viewDidAppear` if scroll animations are already underway. Use this method inside `viewWillAppear:` 427 | instead to avoid this problem. 428 | 429 | - Warning: This method may not function properly if passed the parent view controller when using view controller containment. 430 | 431 | - SeeAlso: restartLabel 432 | - SeeAlso: controllerViewDidAppear: 433 | - SeeAlso: controllerViewWillAppear: 434 | */ 435 | open class func restartLabelsOfController(_ controller: UIViewController) { 436 | MarqueeLabel.notifyController(controller, message: .Restart) 437 | } 438 | 439 | /** 440 | Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain. 441 | 442 | Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements. 443 | 444 | - Parameter controller: The view controller that will appear. 445 | - SeeAlso: restartLabel 446 | - SeeAlso: controllerViewDidAppear 447 | */ 448 | open class func controllerViewWillAppear(_ controller: UIViewController) { 449 | MarqueeLabel.restartLabelsOfController(controller) 450 | } 451 | 452 | /** 453 | Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain. 454 | 455 | Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements. 456 | 457 | - Parameter controller: The view controller that did appear. 458 | - SeeAlso: restartLabel 459 | - SeeAlso: controllerViewWillAppear 460 | */ 461 | open class func controllerViewDidAppear(_ controller: UIViewController) { 462 | MarqueeLabel.restartLabelsOfController(controller) 463 | } 464 | 465 | /** 466 | Labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain. 467 | 468 | The `labelize` property of all recognized `MarqueeLabel` instances will be set to `true`. 469 | 470 | - Parameter controller: The view controller for which all `MarqueeLabel` instances should be labelized. 471 | - SeeAlso: labelize 472 | */ 473 | open class func controllerLabelsLabelize(_ controller: UIViewController) { 474 | MarqueeLabel.notifyController(controller, message: .Labelize) 475 | } 476 | 477 | /** 478 | De-labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain. 479 | 480 | The `labelize` property of all recognized `MarqueeLabel` instances will be set to `false`. 481 | 482 | - Parameter controller: The view controller for which all `MarqueeLabel` instances should be de-labelized. 483 | - SeeAlso: labelize 484 | */ 485 | open class func controllerLabelsAnimate(_ controller: UIViewController) { 486 | MarqueeLabel.notifyController(controller, message: .Animate) 487 | } 488 | 489 | 490 | // 491 | // MARK: - Initialization 492 | // 493 | 494 | /** 495 | Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length. 496 | 497 | - Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll. 498 | - Parameter pixelsPerSec: A rate of scroll for the label scroll animation. Must be non-zero. Note that this will be the peak (mid-transition) rate for ease-type animation. 499 | - Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame. 500 | - Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created. 501 | - SeeAlso: fadeLength 502 | */ 503 | public init(frame: CGRect, rate: CGFloat, fadeLength fade: CGFloat) { 504 | speed = .rate(rate) 505 | fadeLength = CGFloat(min(fade, frame.size.width/2.0)) 506 | super.init(frame: frame) 507 | setup() 508 | } 509 | 510 | /** 511 | Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length. 512 | 513 | - Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll. 514 | - Parameter scrollDuration: A scroll duration the label scroll animation. Must be non-zero. This will be the duration that the animation takes for one-half of the scroll cycle in the case of left-right and right-left marquee types, and for one loop of a continuous marquee type. 515 | - Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame. 516 | - Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created. 517 | - SeeAlso: fadeLength 518 | */ 519 | public init(frame: CGRect, duration: CGFloat, fadeLength fade: CGFloat) { 520 | speed = .duration(duration) 521 | fadeLength = CGFloat(min(fade, frame.size.width/2.0)) 522 | super.init(frame: frame) 523 | setup() 524 | } 525 | 526 | required public init?(coder aDecoder: NSCoder) { 527 | super.init(coder: aDecoder) 528 | setup() 529 | } 530 | 531 | /** 532 | Returns a newly initialized `MarqueeLabel` instance. 533 | 534 | The default scroll duration of 7.0 seconds and fade length of 0.0 are used. 535 | 536 | - Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll. 537 | - Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created. 538 | */ 539 | convenience public override init(frame: CGRect) { 540 | self.init(frame: frame, duration:7.0, fadeLength:0.0) 541 | } 542 | 543 | private func setup() { 544 | // Create sublabel 545 | sublabel = UILabel(frame: self.bounds) 546 | sublabel.tag = 700 547 | sublabel.layer.anchorPoint = CGPoint.zero 548 | 549 | // Add sublabel 550 | addSubview(sublabel) 551 | 552 | // Configure self 553 | super.clipsToBounds = true 554 | super.numberOfLines = 1 555 | 556 | // Add notification observers 557 | // Custom class notifications 558 | NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.restartForViewController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Restart.rawValue), object: nil) 559 | NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.labelizeForController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Labelize.rawValue), object: nil) 560 | NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.animateForController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Animate.rawValue), object: nil) 561 | // UIApplication state notifications 562 | NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.restartLabel), name: UIApplication.didBecomeActiveNotification, object: nil) 563 | NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.shutdownLabel), name: UIApplication.didEnterBackgroundNotification, object: nil) 564 | } 565 | 566 | override open func awakeFromNib() { 567 | super.awakeFromNib() 568 | forwardPropertiesToSublabel() 569 | } 570 | 571 | @available(iOS 8.0, *) 572 | override open func prepareForInterfaceBuilder() { 573 | super.prepareForInterfaceBuilder() 574 | forwardPropertiesToSublabel() 575 | } 576 | 577 | private func forwardPropertiesToSublabel() { 578 | /* 579 | Note that this method is currently ONLY called from awakeFromNib, i.e. when 580 | text properties are set via a Storyboard. As the Storyboard/IB doesn't currently 581 | support attributed strings, there's no need to "forward" the super attributedString value. 582 | */ 583 | 584 | // Since we're a UILabel, we actually do implement all of UILabel's properties. 585 | // We don't care about these values, we just want to forward them on to our sublabel. 586 | let properties = ["baselineAdjustment", "enabled", "highlighted", "highlightedTextColor", 587 | "minimumFontSize", "shadowOffset", "textAlignment", 588 | "userInteractionEnabled", "adjustsFontSizeToFitWidth", "minimumScaleFactor", 589 | "lineBreakMode", "numberOfLines", "contentMode"] 590 | 591 | // Iterate through properties 592 | sublabel.text = super.text 593 | sublabel.font = super.font 594 | sublabel.textColor = super.textColor 595 | sublabel.backgroundColor = super.backgroundColor ?? UIColor.clear 596 | sublabel.shadowColor = super.shadowColor 597 | sublabel.shadowOffset = super.shadowOffset 598 | for prop in properties { 599 | let value = super.value(forKey: prop) 600 | sublabel.setValue(value, forKeyPath: prop) 601 | } 602 | } 603 | 604 | // 605 | // MARK: - MarqueeLabel Heavy Lifting 606 | // 607 | 608 | override open func layoutSubviews() { 609 | super.layoutSubviews() 610 | 611 | updateAndScroll() 612 | } 613 | 614 | override open func willMove(toWindow newWindow: UIWindow?) { 615 | if newWindow == nil { 616 | shutdownLabel() 617 | } 618 | } 619 | 620 | override open func didMoveToWindow() { 621 | if self.window == nil { 622 | shutdownLabel() 623 | } else { 624 | updateAndScroll() 625 | } 626 | } 627 | 628 | private func updateAndScroll() { 629 | // Do not automatically begin scroll if tapToScroll is true 630 | updateAndScroll(overrideHold: false) 631 | } 632 | 633 | private func updateAndScroll(overrideHold: Bool) { 634 | // Check if scrolling can occur 635 | if !labelReadyForScroll() { 636 | return 637 | } 638 | 639 | // Calculate expected size 640 | let expectedLabelSize = sublabel.desiredSize() 641 | 642 | // Invalidate intrinsic size 643 | invalidateIntrinsicContentSize() 644 | 645 | // Move label to home 646 | returnLabelToHome() 647 | 648 | // Check if label should scroll 649 | // Note that the holdScrolling propery does not affect this 650 | if !labelShouldScroll() { 651 | // Set text alignment and break mode to act like a normal label 652 | sublabel.textAlignment = super.textAlignment 653 | sublabel.lineBreakMode = super.lineBreakMode 654 | sublabel.adjustsFontSizeToFitWidth = super.adjustsFontSizeToFitWidth 655 | sublabel.minimumScaleFactor = super.minimumScaleFactor 656 | 657 | let labelFrame: CGRect 658 | switch type { 659 | case .continuousReverse, .rightLeft: 660 | labelFrame = bounds.divided(atDistance: leadingBuffer, from: CGRectEdge.maxXEdge).remainder.integral 661 | default: 662 | labelFrame = CGRect(x: leadingBuffer, y: 0.0, width: bounds.size.width - leadingBuffer, height: bounds.size.height).integral 663 | } 664 | 665 | homeLabelFrame = labelFrame 666 | awayOffset = 0.0 667 | 668 | // Remove any additional sublabels (for continuous types) 669 | repliLayer?.instanceCount = 1 670 | 671 | // Set the sublabel frame to calculated labelFrame 672 | sublabel.frame = labelFrame 673 | 674 | // Remove fade, as by definition none is needed in this case 675 | removeGradientMask() 676 | 677 | return 678 | } 679 | 680 | // Label DOES need to scroll 681 | 682 | // Reset font scaling to off for scrolling 683 | sublabel.adjustsFontSizeToFitWidth = false 684 | sublabel.minimumScaleFactor = 0.0 685 | 686 | // Spacing between primary and second sublabel must be at least equal to leadingBuffer, and at least equal to the fadeLength 687 | let minTrailing = minimumTrailingDistance 688 | 689 | // Determine positions and generate scroll steps 690 | let sequence: [MarqueeStep] 691 | 692 | switch type { 693 | case .continuous, .continuousReverse: 694 | if type == .continuous { 695 | homeLabelFrame = CGRect(x: leadingBuffer, y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral 696 | awayOffset = -(homeLabelFrame.size.width + minTrailing) 697 | } else { // .ContinuousReverse 698 | homeLabelFrame = CGRect(x: bounds.size.width - (expectedLabelSize.width + leadingBuffer), y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral 699 | awayOffset = (homeLabelFrame.size.width + minTrailing) 700 | } 701 | 702 | // Find when the lead label will be totally offscreen 703 | let offsetDistance = awayOffset 704 | let offscreenAmount = homeLabelFrame.size.width 705 | let startFadeFraction = abs(offscreenAmount / offsetDistance) 706 | // Find when the animation will hit that point 707 | let startFadeTimeFraction = timingFunctionForAnimationCurve(animationCurve).durationPercentageForPositionPercentage(startFadeFraction, duration: (animationDelay + animationDuration)) 708 | let startFadeTime = startFadeTimeFraction * animationDuration 709 | 710 | sequence = scrollSequence ?? [ 711 | ScrollStep(timeStep: 0.0, position: .home, edgeFades: .trailing), // Starting point, at home, with trailing fade 712 | ScrollStep(timeStep: animationDelay, position: .home, edgeFades: .trailing), // Delay at home, maintaining fade state 713 | FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after scroll start, fade leading edge in as well 714 | FadeStep(timeStep: (startFadeTime - animationDuration), // Maintain fade state until just before reaching end of scroll animation 715 | edgeFades: [.leading, .trailing]), 716 | ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Ending point (back at home), with animationCurve transition, with trailing fade 717 | position: .away, edgeFades: .trailing) 718 | ] 719 | 720 | // Set frame and text 721 | sublabel.frame = homeLabelFrame 722 | 723 | // Configure replication 724 | // Determine replication count required 725 | let fitFactor: CGFloat = bounds.size.width/(expectedLabelSize.width + leadingBuffer) 726 | let repliCount = 1 + Int(ceil(fitFactor)) 727 | repliLayer?.instanceCount = repliCount 728 | repliLayer?.instanceTransform = CATransform3DMakeTranslation(-awayOffset, 0.0, 0.0) 729 | 730 | case .leftRight, .left, .rightLeft, .right: 731 | if type == .leftRight || type == .left { 732 | homeLabelFrame = CGRect(x: leadingBuffer, y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral 733 | awayOffset = bounds.size.width - (expectedLabelSize.width + leadingBuffer + trailingBuffer) 734 | // Enforce text alignment for this type 735 | sublabel.textAlignment = NSTextAlignment.left 736 | } else { 737 | homeLabelFrame = CGRect(x: bounds.size.width - (expectedLabelSize.width + leadingBuffer), y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral 738 | awayOffset = (expectedLabelSize.width + trailingBuffer + leadingBuffer) - bounds.size.width 739 | // Enforce text alignment for this type 740 | sublabel.textAlignment = NSTextAlignment.right 741 | } 742 | // Set frame and text 743 | sublabel.frame = homeLabelFrame 744 | 745 | // Remove any replication 746 | repliLayer?.instanceCount = 1 747 | 748 | if type == .leftRight || type == .rightLeft { 749 | sequence = scrollSequence ?? [ 750 | ScrollStep(timeStep: 0.0, position: .home, edgeFades: .trailing), // Starting point, at home, with trailing fade 751 | ScrollStep(timeStep: animationDelay, position: .home, edgeFades: .trailing), // Delay at home, maintaining fade state 752 | FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after delay ends, fade leading edge in as well 753 | FadeStep(timeStep: -0.2, edgeFades: [.leading, .trailing]), // Maintain fade state until 0.2 sec before reaching away position 754 | ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Away position, using animationCurve transition, with only leading edge faded in 755 | position: .away, edgeFades: .leading), 756 | ScrollStep(timeStep: animationDelay, position: .away, edgeFades: .leading), // Delay at away, maintaining fade state (leading only) 757 | FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after delay ends, fade trailing edge back in as well 758 | FadeStep(timeStep: -0.2, edgeFades: [.leading, .trailing]), // Maintain fade state until 0.2 sec before reaching home position 759 | ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Ending point, back at home, with only trailing fade 760 | position: .home, edgeFades: .trailing) 761 | ] 762 | } else { // .left or .right 763 | sequence = scrollSequence ?? [ 764 | ScrollStep(timeStep: 0.0, position: .home, edgeFades: .trailing), // Starting point, at home, with trailing fade 765 | ScrollStep(timeStep: animationDelay, position: .home, edgeFades: .trailing), // Delay at home, maintaining fade state 766 | FadeStep(timeStep: 0.2, edgeFades: [.leading, .trailing]), // 0.2 sec after delay ends, fade leading edge in as well 767 | FadeStep(timeStep: -0.2, edgeFades: [.leading, .trailing]), // Maintain fade state until 0.2 sec before reaching away position 768 | ScrollStep(timeStep: animationDuration, timingFunction: animationCurve, // Away position, using animationCurve transition, with only leading edge faded in 769 | position: .away, edgeFades: .leading), 770 | ScrollStep(timeStep: animationDelay, position: .away, edgeFades: .leading), // "Delay" at away, maintaining fade state 771 | ] 772 | } 773 | } 774 | 775 | 776 | 777 | // Configure gradient for current condition 778 | applyGradientMask(fadeLength, animated: !self.labelize) 779 | 780 | if overrideHold || (!holdScrolling && !overrideHold) { 781 | beginScroll(sequence) 782 | } 783 | } 784 | 785 | override open func sizeThatFits(_ size: CGSize) -> CGSize { 786 | return sizeThatFits(size, withBuffers: true) 787 | } 788 | 789 | open func sizeThatFits(_ size: CGSize, withBuffers: Bool) -> CGSize { 790 | var fitSize = sublabel.sizeThatFits(size) 791 | if withBuffers { 792 | fitSize.width += leadingBuffer 793 | } 794 | return fitSize 795 | } 796 | 797 | /** 798 | Returns the unconstrained size of the specified label text (for a single line). 799 | */ 800 | open func textLayoutSize() -> CGSize { 801 | return sublabel.desiredSize() 802 | } 803 | 804 | // 805 | // MARK: - Animation Handling 806 | // 807 | 808 | open func labelShouldScroll() -> Bool { 809 | // Check for nil string 810 | guard sublabel.text != nil else { 811 | return false 812 | } 813 | 814 | // Check for empty string 815 | guard !sublabel.text!.isEmpty else { 816 | return false 817 | } 818 | 819 | var labelTooLarge = false 820 | if !super.adjustsFontSizeToFitWidth { 821 | // Usual logic to check if the label string fits 822 | labelTooLarge = (sublabel.desiredSize().width + leadingBuffer) > self.bounds.size.width + CGFloat.ulpOfOne 823 | } else { 824 | // Logic with auto-scale support 825 | // Create mutable attributed string to modify font sizes in-situ 826 | let resizedString = NSMutableAttributedString.init(attributedString: sublabel.attributedText!) 827 | resizedString.beginEditing() 828 | // Enumerate all font attributes of attributed string 829 | resizedString.enumerateAttribute(.font, in: NSRange(0.. 0.0 853 | return (!labelize && (forceScrolling || labelTooLarge) && animationHasDuration) 854 | } 855 | 856 | private func labelReadyForScroll() -> Bool { 857 | // Check if we have a superview 858 | if superview == nil { 859 | return false 860 | } 861 | 862 | // Check if we are attached to a window 863 | if window == nil { 864 | return false 865 | } 866 | 867 | // Check if our view controller is ready 868 | let viewController = firstAvailableViewController() 869 | if viewController != nil { 870 | if !viewController!.isViewLoaded { 871 | return false 872 | } 873 | } 874 | 875 | return true 876 | } 877 | 878 | private func returnLabelToHome() { 879 | // Store if label is away from home at time of call 880 | let away = awayFromHome 881 | 882 | // Remove any gradient animation 883 | maskLayer?.removeAllAnimations() 884 | 885 | // Remove all sublabel position animations 886 | sublabel.layer.removeAllAnimations() 887 | 888 | // Fire completion block if appropriate 889 | if away { 890 | // If label was away when this was called, animation did NOT finish 891 | scrollCompletionBlock?(!away) 892 | } 893 | 894 | // Remove completion block 895 | scrollCompletionBlock = nil 896 | } 897 | 898 | private func beginScroll(_ sequence: [MarqueeStep]) { 899 | let scroller = generateScrollAnimation(sequence) 900 | let fader = generateGradientAnimation(sequence, totalDuration: scroller.duration) 901 | 902 | scroll(scroller, fader: fader) 903 | } 904 | 905 | private func scroll(_ scroller: MLAnimation, fader: MLAnimation?) { 906 | // Check for conditions which would prevent scrolling 907 | if !labelReadyForScroll() { 908 | return 909 | } 910 | // Convert fader to var 911 | var fader = fader 912 | 913 | // Call pre-animation hook 914 | labelWillBeginScroll() 915 | 916 | // Start animation transactions 917 | CATransaction.begin() 918 | CATransaction.setAnimationDuration(TimeInterval(scroller.duration)) 919 | 920 | // Create gradient animation, if needed 921 | let gradientAnimation: CAKeyframeAnimation? 922 | // Check for IBDesignable 923 | #if !TARGET_INTERFACE_BUILDER 924 | if fadeLength > 0.0 { 925 | // Remove any setup animation, but apply final values 926 | if let setupAnim = maskLayer?.animation(forKey: "setupFade") as? CABasicAnimation, let finalColors = setupAnim.toValue as? [CGColor] { 927 | maskLayer?.colors = finalColors 928 | } 929 | maskLayer?.removeAnimation(forKey: "setupFade") 930 | 931 | // Generate animation if needed 932 | if let previousAnimation = fader?.anim { 933 | gradientAnimation = previousAnimation 934 | } else { 935 | gradientAnimation = nil 936 | } 937 | 938 | // Apply fade animation 939 | maskLayer?.add(gradientAnimation!, forKey: "gradient") 940 | } else { 941 | // No animation needed 942 | fader = nil 943 | } 944 | #else 945 | fader = nil 946 | #endif 947 | 948 | scrollCompletionBlock = { [weak self] (finished: Bool) in 949 | guard self != nil else { 950 | return 951 | } 952 | 953 | // Call returned home function 954 | self!.labelReturnedToHome(finished) 955 | 956 | // Check to ensure that: 957 | 958 | // 1) The instance is still attached to a window - this completion block is called for 959 | // many reasons, including if the animation is removed due to the view being removed 960 | // from the UIWindow (typically when the view controller is no longer the "top" view) 961 | guard self!.window != nil else { 962 | return 963 | } 964 | // 2) We don't double fire if an animation already exists 965 | guard self!.sublabel.layer.animation(forKey: "position") == nil else { 966 | return 967 | } 968 | // 3) We don't start automatically if the animation was unexpectedly interrupted 969 | guard finished else { 970 | // Do not continue into the next loop 971 | return 972 | } 973 | // 4) A completion block still exists for the NEXT loop. A notable case here is if 974 | // returnLabelToHome() was called during a subclass's labelReturnToHome() function 975 | guard self!.scrollCompletionBlock != nil else { 976 | return 977 | } 978 | 979 | // Begin again, if conditions met 980 | if self!.labelShouldScroll() && !self!.tapToScroll && !self!.holdScrolling { 981 | // Perform completion callback 982 | self!.scroll(scroller, fader: fader) 983 | } 984 | } 985 | 986 | // Perform scroll animation 987 | scroller.anim.setValue(true, forKey: MarqueeKeys.CompletionClosure.rawValue) 988 | scroller.anim.delegate = self 989 | if type == .left || type == .right { 990 | // Make it stay at away permanently 991 | scroller.anim.isRemovedOnCompletion = false 992 | scroller.anim.fillMode = .forwards 993 | } 994 | sublabel.layer.add(scroller.anim, forKey: "position") 995 | 996 | CATransaction.commit() 997 | } 998 | 999 | private func generateScrollAnimation(_ sequence: [MarqueeStep]) -> MLAnimation { 1000 | // Create scroller, which defines the animation to perform 1001 | let homeOrigin = homeLabelFrame.origin 1002 | let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset) 1003 | 1004 | let scrollSteps = sequence.filter({ $0 is ScrollStep }) as! [ScrollStep] 1005 | let totalDuration = scrollSteps.reduce(0.0) { $0 + $1.timeStep } 1006 | 1007 | // Build scroll data 1008 | var totalTime: CGFloat = 0.0 1009 | var scrollKeyTimes = [NSNumber]() 1010 | var scrollKeyValues = [NSValue]() 1011 | var scrollTimingFunctions = [CAMediaTimingFunction]() 1012 | 1013 | for (offset, step) in scrollSteps.enumerated() { 1014 | // Scroll Times 1015 | totalTime += step.timeStep 1016 | scrollKeyTimes.append(NSNumber(value:Float(totalTime/totalDuration))) 1017 | 1018 | // Scroll Values 1019 | let scrollPosition: CGPoint 1020 | switch step.position { 1021 | case .home: 1022 | scrollPosition = homeOrigin 1023 | case .away: 1024 | scrollPosition = awayOrigin 1025 | case .partial(let frac): 1026 | scrollPosition = offsetCGPoint(homeOrigin, offset: awayOffset*frac) 1027 | } 1028 | scrollKeyValues.append(NSValue(cgPoint:scrollPosition)) 1029 | 1030 | // Scroll Timing Functions 1031 | // Only need n-1 timing functions, so discard the first value as it's unused 1032 | if offset == 0 { continue } 1033 | scrollTimingFunctions.append(timingFunctionForAnimationCurve(step.timingFunction)) 1034 | } 1035 | 1036 | // Create animation 1037 | let animation = CAKeyframeAnimation(keyPath: "position") 1038 | // Set values 1039 | animation.keyTimes = scrollKeyTimes 1040 | animation.values = scrollKeyValues 1041 | animation.timingFunctions = scrollTimingFunctions 1042 | 1043 | return (anim: animation, duration: totalDuration) 1044 | } 1045 | 1046 | private func generateGradientAnimation(_ sequence: [MarqueeStep], totalDuration: CGFloat) -> MLAnimation { 1047 | // Setup 1048 | var totalTime: CGFloat = 0.0 1049 | var stepTime: CGFloat = 0.0 1050 | var fadeKeyValues = [[CGColor]]() 1051 | var fadeKeyTimes = [NSNumber]() 1052 | var fadeTimingFunctions = [CAMediaTimingFunction]() 1053 | let transp = UIColor.clear.cgColor 1054 | let opaque = UIColor.black.cgColor 1055 | 1056 | // Filter to get only scroll steps and valid precedent/subsequent fade steps 1057 | let fadeSteps = sequence.enumerated().filter { (arg: (offset: Int, element: MarqueeStep)) -> Bool in 1058 | let (offset, element) = arg 1059 | 1060 | // Include all Scroll Steps 1061 | if element is ScrollStep { return true } 1062 | 1063 | // Include all Fade Steps that have a directly preceding or subsequent Scroll Step 1064 | // Exception: Fade Step cannot be first step 1065 | if offset == 0 { return false } 1066 | 1067 | // Subsequent step if 1) positive/zero time step and 2) follows a Scroll Step 1068 | let subsequent = element.timeStep >= 0 && (sequence[max(0, offset - 1)] is ScrollStep) 1069 | // Precedent step if 1) negative time step and 2) precedes a Scroll Step 1070 | let precedent = element.timeStep < 0 && (sequence[min(sequence.count - 1, offset + 1)] is ScrollStep) 1071 | 1072 | return (precedent || subsequent) 1073 | } 1074 | 1075 | for (offset, step) in fadeSteps { 1076 | // Fade times 1077 | if step is ScrollStep { 1078 | totalTime += step.timeStep 1079 | stepTime = totalTime 1080 | } else { 1081 | if step.timeStep >= 0 { 1082 | // Is a Subsequent 1083 | stepTime = totalTime + step.timeStep 1084 | } else { 1085 | // Is a Precedent, grab next step 1086 | stepTime = totalTime + fadeSteps[offset + 1].element.timeStep + step.timeStep 1087 | } 1088 | } 1089 | fadeKeyTimes.append(NSNumber(value:Float(stepTime/totalDuration))) 1090 | 1091 | // Fade Values 1092 | let values: [CGColor] 1093 | let leading = step.edgeFades.contains(.leading) ? transp : opaque 1094 | let trailing = step.edgeFades.contains(.trailing) ? transp : opaque 1095 | switch type { 1096 | case .leftRight, .left, .continuous: 1097 | values = [leading, opaque, opaque, trailing] 1098 | case .rightLeft, .right, .continuousReverse: 1099 | values = [trailing, opaque, opaque, leading] 1100 | } 1101 | fadeKeyValues.append(values) 1102 | 1103 | // Fade Timing Function 1104 | // Only need n-1 timing functions, so discard the first value as it's unused 1105 | if offset == 0 { continue } 1106 | fadeTimingFunctions.append(timingFunctionForAnimationCurve(step.timingFunction)) 1107 | } 1108 | 1109 | // Create new animation 1110 | let animation = CAKeyframeAnimation(keyPath: "colors") 1111 | 1112 | animation.values = fadeKeyValues 1113 | animation.keyTimes = fadeKeyTimes 1114 | animation.timingFunctions = fadeTimingFunctions 1115 | 1116 | return (anim: animation, duration: max(totalTime, totalDuration)) 1117 | } 1118 | 1119 | private func applyGradientMask(_ fadeLength: CGFloat, animated: Bool, firstStep: MarqueeStep? = nil) { 1120 | // Remove any in-flight animations 1121 | maskLayer?.removeAllAnimations() 1122 | 1123 | // Check for zero-length fade 1124 | if fadeLength <= 0.0 { 1125 | removeGradientMask() 1126 | return 1127 | } 1128 | 1129 | // Configure gradient mask without implicit animations 1130 | CATransaction.begin() 1131 | CATransaction.setDisableActions(true) 1132 | 1133 | // Determine if gradient mask needs to be created 1134 | let gradientMask: CAGradientLayer 1135 | if let currentMask = self.maskLayer { 1136 | // Mask layer already configured 1137 | gradientMask = currentMask 1138 | } else { 1139 | // No mask exists, create new mask 1140 | gradientMask = CAGradientLayer() 1141 | gradientMask.shouldRasterize = true 1142 | gradientMask.rasterizationScale = UIScreen.main.scale 1143 | gradientMask.startPoint = CGPoint(x:0.0, y:0.5) 1144 | gradientMask.endPoint = CGPoint(x:1.0, y:0.5) 1145 | } 1146 | 1147 | // Check if there is a mask to layer size mismatch 1148 | if gradientMask.bounds != self.layer.bounds { 1149 | // Adjust stops based on fade length 1150 | let leftFadeStop = fadeLength/self.bounds.size.width 1151 | let rightFadeStop = 1.0 - fadeLength/self.bounds.size.width 1152 | gradientMask.locations = [0.0, leftFadeStop, rightFadeStop, 1.0].map { NSNumber(value: Float($0)) } 1153 | } 1154 | 1155 | gradientMask.bounds = self.layer.bounds 1156 | gradientMask.position = CGPoint(x:self.bounds.midX, y:self.bounds.midY) 1157 | 1158 | // Set up colors 1159 | let transparent = UIColor.clear.cgColor 1160 | let opaque = UIColor.black.cgColor 1161 | 1162 | // Set mask 1163 | self.layer.mask = gradientMask 1164 | 1165 | // Determine colors for non-scrolling label (i.e. at home) 1166 | let adjustedColors: [CGColor] 1167 | let trailingFadeNeeded = self.labelShouldScroll() 1168 | 1169 | switch type { 1170 | case .continuousReverse, .rightLeft: 1171 | adjustedColors = [(trailingFadeNeeded ? transparent : opaque), opaque, opaque, opaque] 1172 | 1173 | // .Continuous, .LeftRight 1174 | default: 1175 | adjustedColors = [opaque, opaque, opaque, (trailingFadeNeeded ? transparent : opaque)] 1176 | } 1177 | 1178 | // Check for IBDesignable 1179 | #if TARGET_INTERFACE_BUILDER 1180 | gradientMask.colors = adjustedColors 1181 | CATransaction.commit() 1182 | #else 1183 | if animated { 1184 | // Finish transaction 1185 | CATransaction.commit() 1186 | 1187 | // Create animation for color change 1188 | let colorAnimation = GradientSetupAnimation(keyPath: "colors") 1189 | colorAnimation.fromValue = gradientMask.colors 1190 | colorAnimation.toValue = adjustedColors 1191 | colorAnimation.fillMode = .forwards 1192 | colorAnimation.isRemovedOnCompletion = false 1193 | colorAnimation.delegate = self 1194 | gradientMask.add(colorAnimation, forKey: "setupFade") 1195 | } else { 1196 | gradientMask.colors = adjustedColors 1197 | CATransaction.commit() 1198 | } 1199 | #endif 1200 | } 1201 | 1202 | private func removeGradientMask() { 1203 | self.layer.mask = nil 1204 | } 1205 | 1206 | private func timingFunctionForAnimationCurve(_ curve: UIView.AnimationCurve) -> CAMediaTimingFunction { 1207 | let timingFunction: CAMediaTimingFunctionName? 1208 | 1209 | switch curve { 1210 | case .easeIn: 1211 | timingFunction = .easeIn 1212 | case .easeInOut: 1213 | timingFunction = .easeInEaseOut 1214 | case .easeOut: 1215 | timingFunction = .easeOut 1216 | default: 1217 | timingFunction = .linear 1218 | } 1219 | 1220 | return CAMediaTimingFunction(name: timingFunction!) 1221 | } 1222 | 1223 | private func transactionDurationType(_ labelType: MarqueeType, interval: CGFloat, delay: CGFloat) -> TimeInterval { 1224 | switch labelType { 1225 | case .leftRight, .rightLeft: 1226 | return TimeInterval(2.0 * (delay + interval)) 1227 | default: 1228 | return TimeInterval(delay + interval) 1229 | } 1230 | } 1231 | 1232 | public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { 1233 | if let setupAnim = anim as? GradientSetupAnimation { 1234 | if let finalColors = setupAnim.toValue as? [CGColor] { 1235 | maskLayer?.colors = finalColors 1236 | } 1237 | // Remove regardless, since we set removeOnCompletion = false 1238 | maskLayer?.removeAnimation(forKey: "setupFade") 1239 | } else { 1240 | scrollCompletionBlock?(flag) 1241 | } 1242 | } 1243 | 1244 | 1245 | // 1246 | // MARK: - Private details 1247 | // 1248 | 1249 | private var sublabel = UILabel() 1250 | 1251 | fileprivate var homeLabelFrame = CGRect.zero 1252 | fileprivate var awayOffset: CGFloat = 0.0 1253 | 1254 | override open class var layerClass: AnyClass { 1255 | return CAReplicatorLayer.self 1256 | } 1257 | 1258 | fileprivate weak var repliLayer: CAReplicatorLayer? { 1259 | return self.layer as? CAReplicatorLayer 1260 | } 1261 | 1262 | fileprivate weak var maskLayer: CAGradientLayer? { 1263 | return self.layer.mask as! CAGradientLayer? 1264 | } 1265 | 1266 | fileprivate var scrollCompletionBlock: MLAnimationCompletionBlock? 1267 | 1268 | override open func draw(_ layer: CALayer, in ctx: CGContext) { 1269 | // Do NOT call super, to prevent UILabel superclass from drawing into context 1270 | // Label drawing is handled by sublabel and CAReplicatorLayer layer class 1271 | 1272 | // Draw only background color 1273 | if let bgColor = backgroundColor { 1274 | ctx.setFillColor(bgColor.cgColor) 1275 | ctx.fill(layer.bounds) 1276 | } 1277 | } 1278 | 1279 | private var minimumTrailingDistance: CGFloat { 1280 | // Spacing between primary and second sublabel must be at least equal to leadingBuffer, and at least equal to the fadeLengt 1281 | return max(max(leadingBuffer, trailingBuffer), fadeLength) 1282 | } 1283 | 1284 | fileprivate enum MarqueeKeys: String { 1285 | case Restart = "MLViewControllerRestart" 1286 | case Labelize = "MLShouldLabelize" 1287 | case Animate = "MLShouldAnimate" 1288 | case CompletionClosure = "MLAnimationCompletion" 1289 | } 1290 | 1291 | class fileprivate func notifyController(_ controller: UIViewController, message: MarqueeKeys) { 1292 | NotificationCenter.default.post(name: Notification.Name(rawValue: message.rawValue), object: nil, userInfo: ["controller" : controller]) 1293 | } 1294 | 1295 | @objc public func restartForViewController(_ notification: Notification) { 1296 | if let controller = (notification as NSNotification).userInfo?["controller"] as? UIViewController { 1297 | if controller === self.firstAvailableViewController() { 1298 | self.restartLabel() 1299 | } 1300 | } 1301 | } 1302 | 1303 | @objc public func labelizeForController(_ notification: Notification) { 1304 | if let controller = (notification as NSNotification).userInfo?["controller"] as? UIViewController { 1305 | if controller === self.firstAvailableViewController() { 1306 | self.labelize = true 1307 | } 1308 | } 1309 | } 1310 | 1311 | @objc public func animateForController(_ notification: Notification) { 1312 | if let controller = (notification as NSNotification).userInfo?["controller"] as? UIViewController { 1313 | if controller === self.firstAvailableViewController() { 1314 | self.labelize = false 1315 | } 1316 | } 1317 | } 1318 | 1319 | 1320 | // 1321 | // MARK: - Label Control 1322 | // 1323 | 1324 | /** 1325 | Overrides any non-size condition which is preventing the receiver from automatically scrolling, and begins a scroll animation. 1326 | 1327 | Currently the only non-size conditions which can prevent a label from scrolling are the `tapToScroll` and `holdScrolling` properties. This 1328 | method will not force a label with a string that fits inside the label bounds (i.e. that would not automatically scroll) to begin a scroll 1329 | animation. 1330 | 1331 | Upon the completion of the first forced scroll animation, the receiver will not automatically continue to scroll unless the conditions 1332 | preventing scrolling have been removed. 1333 | 1334 | - Note: This method has no effect if called during an already in-flight scroll animation. 1335 | 1336 | - SeeAlso: restartLabel 1337 | */ 1338 | public func triggerScrollStart() { 1339 | if labelShouldScroll() && !awayFromHome { 1340 | updateAndScroll() 1341 | } 1342 | } 1343 | 1344 | /** 1345 | Immediately resets the label to the home position, cancelling any in-flight scroll animation, and restarts the scroll animation if the appropriate conditions are met. 1346 | 1347 | - SeeAlso: resetLabel 1348 | - SeeAlso: triggerScrollStart 1349 | */ 1350 | @objc public func restartLabel() { 1351 | // Shutdown the label 1352 | shutdownLabel() 1353 | // Restart scrolling if appropriate 1354 | if labelShouldScroll() && !tapToScroll && !holdScrolling { 1355 | updateAndScroll() 1356 | } 1357 | } 1358 | 1359 | /** 1360 | Resets the label text, recalculating the scroll animation. 1361 | 1362 | The text is immediately returned to the home position, and the scroll animation positions are cleared. Scrolling will not resume automatically after 1363 | a call to this method. To re-initiate scrolling, use either a call to `restartLabel` or make a change to a UILabel property such as text, bounds/frame, 1364 | font, font size, etc. 1365 | 1366 | - SeeAlso: restartLabel 1367 | */ 1368 | @available(*, deprecated, message : "Use the shutdownLabel function instead") 1369 | public func resetLabel() { 1370 | returnLabelToHome() 1371 | homeLabelFrame = CGRect.null 1372 | awayOffset = 0.0 1373 | } 1374 | 1375 | /** 1376 | Immediately resets the label to the home position, cancelling any in-flight scroll animation. 1377 | 1378 | The text is immediately returned to the home position. Scrolling will not resume automatically after a call to this method. 1379 | To re-initiate scrolling use a call to `restartLabel` or `triggerScrollStart`, or make a change to a UILabel property such as text, bounds/frame, 1380 | font, font size, etc. 1381 | 1382 | - SeeAlso: restartLabel 1383 | - SeeAlso: triggerScrollStart 1384 | */ 1385 | @objc public func shutdownLabel() { 1386 | // Bring label to home location 1387 | returnLabelToHome() 1388 | // Apply gradient mask for home location 1389 | applyGradientMask(fadeLength, animated: false) 1390 | } 1391 | 1392 | /** 1393 | Pauses the text scrolling animation, at any point during an in-progress animation. 1394 | 1395 | - Note: This method has no effect if a scroll animation is NOT already in progress. To prevent automatic scrolling on a newly-initialized label prior to its presentation onscreen, see the `holdScrolling` property. 1396 | 1397 | - SeeAlso: holdScrolling 1398 | - SeeAlso: unpauseLabel 1399 | */ 1400 | public func pauseLabel() { 1401 | // Prevent pausing label while not in scrolling animation, or when already paused 1402 | guard !isPaused && awayFromHome else { 1403 | return 1404 | } 1405 | 1406 | // Pause sublabel position animations 1407 | let labelPauseTime = sublabel.layer.convertTime(CACurrentMediaTime(), from: nil) 1408 | sublabel.layer.speed = 0.0 1409 | sublabel.layer.timeOffset = labelPauseTime 1410 | 1411 | // Pause gradient fade animation 1412 | let gradientPauseTime = maskLayer?.convertTime(CACurrentMediaTime(), from:nil) 1413 | maskLayer?.speed = 0.0 1414 | maskLayer?.timeOffset = gradientPauseTime! 1415 | } 1416 | 1417 | /** 1418 | Un-pauses a previously paused text scrolling animation. This method has no effect if the label was not previously paused using `pauseLabel`. 1419 | 1420 | - SeeAlso: pauseLabel 1421 | */ 1422 | public func unpauseLabel() { 1423 | // Only unpause if label was previously paused 1424 | guard isPaused else { 1425 | return 1426 | } 1427 | 1428 | // Unpause sublabel position animations 1429 | let labelPausedTime = sublabel.layer.timeOffset 1430 | sublabel.layer.speed = 1.0 1431 | sublabel.layer.timeOffset = 0.0 1432 | sublabel.layer.beginTime = 0.0 1433 | sublabel.layer.beginTime = sublabel.layer.convertTime(CACurrentMediaTime(), from:nil) - labelPausedTime 1434 | 1435 | // Unpause gradient fade animation 1436 | let gradientPauseTime = maskLayer?.timeOffset 1437 | maskLayer?.speed = 1.0 1438 | maskLayer?.timeOffset = 0.0 1439 | maskLayer?.beginTime = 0.0 1440 | maskLayer?.beginTime = maskLayer!.convertTime(CACurrentMediaTime(), from:nil) - gradientPauseTime! 1441 | } 1442 | 1443 | @objc public func labelWasTapped(_ recognizer: UIGestureRecognizer) { 1444 | if labelShouldScroll() && !awayFromHome { 1445 | // Set shouldBeginScroll to true to begin single scroll due to tap 1446 | updateAndScroll(overrideHold: true) 1447 | } 1448 | } 1449 | 1450 | /** 1451 | Function to convert a point from the label view frame coordinates to "text" coordinates, i.e. the equivalent 1452 | position in the (possibly) scrolling label. For example, it can be used to convert the coordinates 1453 | of a tap point on the MarqueeLabel view into that of the scrolling label, in order to determine the 1454 | word or character under the tap point. 1455 | 1456 | If the specified point does not fall inside the bounds of the scrolling label, such as if on a leading 1457 | or trailing buffer area, the function will return nil. 1458 | */ 1459 | open func textCoordinateForFramePoint(_ point:CGPoint) -> CGPoint? { 1460 | // Check for presentation layer, if none return input point 1461 | guard let presentationLayer = sublabel.layer.presentation() else { return point } 1462 | // Convert point from MarqueeLabel main layer to sublabel's presentationLayer 1463 | let presentationPoint = presentationLayer.convert(point, from: self.layer) 1464 | // Check if point overlaps into 2nd instance of a continuous type label 1465 | let textPoint: CGPoint? 1466 | let presentationX = presentationPoint.x 1467 | let labelWidth = sublabel.frame.size.width 1468 | 1469 | var containers: [Range] = [] 1470 | switch type { 1471 | case .continuous: 1472 | // First label frame range 1473 | let firstLabel = 0.0 ..< sublabel.frame.size.width 1474 | // Range from end of first label to the minimum trailining distance (i.e. the separator) 1475 | let minTrailing = firstLabel.rangeForExtension(minimumTrailingDistance) 1476 | // Range of second label instance, from end of separator to length 1477 | let secondLabel = minTrailing.rangeForExtension(labelWidth) 1478 | // Add valid ranges to array to check 1479 | containers += [firstLabel, secondLabel] 1480 | case .continuousReverse: 1481 | // First label frame range 1482 | let firstLabel = 0.0 ..< sublabel.frame.size.width 1483 | // Range of second label instance, from end of separator to length 1484 | let secondLabel = -sublabel.frame.size.width ..< -minimumTrailingDistance 1485 | // Add valid ranges to array to check 1486 | containers += [firstLabel, secondLabel] 1487 | case .left, .leftRight, .right, .rightLeft: 1488 | // Only label frame range 1489 | let firstLabel = 0.0 ..< sublabel.frame.size.width 1490 | containers.append(firstLabel) 1491 | } 1492 | 1493 | // Determine which range contains the point, or return nil if in a buffer/margin area 1494 | guard let container = containers.filter({ (rng) -> Bool in 1495 | return rng.contains(presentationX) 1496 | }).first else { return nil } 1497 | 1498 | textPoint = CGPoint(x: (presentationX - container.lowerBound), y: presentationPoint.y) 1499 | return textPoint 1500 | } 1501 | 1502 | /** 1503 | Called when the label animation is about to begin. 1504 | 1505 | The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions just as 1506 | the label animation begins. This is only called in the event that the conditions for scrolling to begin are met. 1507 | */ 1508 | open func labelWillBeginScroll() { 1509 | // Default implementation does nothing - override to customize 1510 | return 1511 | } 1512 | 1513 | /** 1514 | Called when the label animation has finished, and the label is at the home position. 1515 | 1516 | The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions jas as 1517 | the label animation completes, and before the next animation would begin (assuming the scroll conditions are met). 1518 | 1519 | - Parameter finished: A Boolean that indicates whether or not the scroll animation actually finished before the completion handler was called. 1520 | 1521 | - Warning: This method will be called, and the `finished` parameter will be `NO`, when any property changes are made that would cause the label 1522 | scrolling to be automatically reset. This includes changes to label text and font/font size changes. 1523 | */ 1524 | open func labelReturnedToHome(_ finished: Bool) { 1525 | // Default implementation does nothing - override to customize 1526 | return 1527 | } 1528 | 1529 | // 1530 | // MARK: - Modified UILabel Functions/Getters/Setters 1531 | // 1532 | 1533 | #if os(iOS) 1534 | override open func forBaselineLayout() -> UIView { 1535 | // Use subLabel view for handling baseline layouts 1536 | return sublabel 1537 | } 1538 | 1539 | override open var forLastBaselineLayout: UIView { 1540 | // Use subLabel view for handling baseline layouts 1541 | return sublabel 1542 | } 1543 | #endif 1544 | 1545 | override open var text: String? { 1546 | get { 1547 | return sublabel.text 1548 | } 1549 | 1550 | set { 1551 | if sublabel.text == newValue { 1552 | return 1553 | } 1554 | sublabel.text = newValue 1555 | updateAndScroll() 1556 | super.text = text 1557 | } 1558 | } 1559 | 1560 | override open var attributedText: NSAttributedString? { 1561 | get { 1562 | return sublabel.attributedText 1563 | } 1564 | 1565 | set { 1566 | if sublabel.attributedText == newValue { 1567 | return 1568 | } 1569 | sublabel.attributedText = newValue 1570 | updateAndScroll() 1571 | super.attributedText = attributedText 1572 | } 1573 | } 1574 | 1575 | override open var font: UIFont! { 1576 | get { 1577 | return sublabel.font 1578 | } 1579 | 1580 | set { 1581 | if sublabel.font == newValue { 1582 | return 1583 | } 1584 | sublabel.font = newValue 1585 | super.font = newValue 1586 | 1587 | updateAndScroll() 1588 | } 1589 | } 1590 | 1591 | override open var textColor: UIColor! { 1592 | get { 1593 | return sublabel.textColor 1594 | } 1595 | 1596 | set { 1597 | sublabel.textColor = newValue 1598 | super.textColor = newValue 1599 | } 1600 | } 1601 | 1602 | override open var backgroundColor: UIColor? { 1603 | get { 1604 | return sublabel.backgroundColor 1605 | } 1606 | 1607 | set { 1608 | sublabel.backgroundColor = newValue 1609 | super.backgroundColor = newValue 1610 | } 1611 | } 1612 | 1613 | override open var shadowColor: UIColor? { 1614 | get { 1615 | return sublabel.shadowColor 1616 | } 1617 | 1618 | set { 1619 | sublabel.shadowColor = newValue 1620 | super.shadowColor = newValue 1621 | } 1622 | } 1623 | 1624 | override open var shadowOffset: CGSize { 1625 | get { 1626 | return sublabel.shadowOffset 1627 | } 1628 | 1629 | set { 1630 | sublabel.shadowOffset = newValue 1631 | super.shadowOffset = newValue 1632 | } 1633 | } 1634 | 1635 | override open var highlightedTextColor: UIColor? { 1636 | get { 1637 | return sublabel.highlightedTextColor 1638 | } 1639 | 1640 | set { 1641 | sublabel.highlightedTextColor = newValue 1642 | super.highlightedTextColor = newValue 1643 | } 1644 | } 1645 | 1646 | override open var isHighlighted: Bool { 1647 | get { 1648 | return sublabel.isHighlighted 1649 | } 1650 | 1651 | set { 1652 | sublabel.isHighlighted = newValue 1653 | super.isHighlighted = newValue 1654 | } 1655 | } 1656 | 1657 | override open var isEnabled: Bool { 1658 | get { 1659 | return sublabel.isEnabled 1660 | } 1661 | 1662 | set { 1663 | sublabel.isEnabled = newValue 1664 | super.isEnabled = newValue 1665 | } 1666 | } 1667 | 1668 | override open var numberOfLines: Int { 1669 | get { 1670 | return super.numberOfLines 1671 | } 1672 | 1673 | set { 1674 | // By the nature of MarqueeLabel, this is 1 1675 | super.numberOfLines = 1 1676 | } 1677 | } 1678 | 1679 | override open var baselineAdjustment: UIBaselineAdjustment { 1680 | get { 1681 | return sublabel.baselineAdjustment 1682 | } 1683 | 1684 | set { 1685 | sublabel.baselineAdjustment = newValue 1686 | super.baselineAdjustment = newValue 1687 | } 1688 | } 1689 | 1690 | override open var intrinsicContentSize: CGSize { 1691 | var content = sublabel.intrinsicContentSize 1692 | content.width += leadingBuffer 1693 | return content 1694 | } 1695 | 1696 | override open var tintColor: UIColor! { 1697 | get { 1698 | return sublabel.tintColor 1699 | } 1700 | 1701 | set { 1702 | sublabel.tintColor = newValue 1703 | super.tintColor = newValue 1704 | } 1705 | } 1706 | 1707 | override open func tintColorDidChange() { 1708 | super.tintColorDidChange() 1709 | sublabel.tintColorDidChange() 1710 | } 1711 | 1712 | override open var contentMode: UIView.ContentMode { 1713 | get { 1714 | return sublabel.contentMode 1715 | } 1716 | 1717 | set { 1718 | super.contentMode = contentMode 1719 | sublabel.contentMode = newValue 1720 | } 1721 | } 1722 | 1723 | open override var isAccessibilityElement: Bool { 1724 | didSet { 1725 | sublabel.isAccessibilityElement = self.isAccessibilityElement 1726 | } 1727 | } 1728 | 1729 | // 1730 | // MARK: - Support 1731 | // 1732 | 1733 | fileprivate func offsetCGPoint(_ point: CGPoint, offset: CGFloat) -> CGPoint { 1734 | return CGPoint(x: point.x + offset, y: point.y) 1735 | } 1736 | 1737 | // 1738 | // MARK: - Deinit 1739 | // 1740 | 1741 | deinit { 1742 | NotificationCenter.default.removeObserver(self) 1743 | } 1744 | 1745 | } 1746 | 1747 | 1748 | // 1749 | // MARK: - Support 1750 | // 1751 | public protocol MarqueeStep { 1752 | var timeStep: CGFloat { get } 1753 | var timingFunction: UIView.AnimationCurve { get } 1754 | var edgeFades: EdgeFade { get } 1755 | } 1756 | 1757 | 1758 | /** 1759 | `ScrollStep` types define the label position at a specified time delta since the last `ScrollStep` step, as well as 1760 | the animation curve to that position and edge fade state at the position 1761 | */ 1762 | public struct ScrollStep: MarqueeStep { 1763 | /** 1764 | An enum that provides the possible positions defined by a ScrollStep 1765 | - `home`: The starting, default position of the label 1766 | - `away`: The calculated position that results in the entirety of the label scrolling past. 1767 | - `partial(CGFloat)`: A fractional value, specified by the associated CGFloat value, between the `home` and `away` positions (must be between 0.0 and 1.0). 1768 | 1769 | The `away` position depends on the MarqueeLabel `type` value. 1770 | - For `left`, `leftRight`, `right`, and `rightLeft` types, the `away` position means the trailing edge of the label 1771 | is visible. For `leftRight` and `rightLeft` default types, the scroll animation reverses direction after reaching 1772 | this point and returns to the `home` position. 1773 | - For `continuous` and `continuousReverse` types, the `away` position is the location such that if the scroll is completed 1774 | at this point (i.e. the animation is removed), there will be no visible change in the label appearance. 1775 | */ 1776 | public enum Position { 1777 | case home 1778 | case away 1779 | case partial(CGFloat) 1780 | } 1781 | 1782 | /** 1783 | The desired time between this step and the previous `ScrollStep` in a sequence. 1784 | */ 1785 | public let timeStep: CGFloat 1786 | 1787 | /** 1788 | The animation curve to utilize between the previous `ScrollStep` in a sequence and this step. 1789 | 1790 | - Note: The animation curve value for the first `ScrollStep` in a sequence has no effect. 1791 | */ 1792 | public let timingFunction: UIView.AnimationCurve 1793 | 1794 | /** 1795 | The position of the label for this scroll step. 1796 | - SeeAlso: Position 1797 | */ 1798 | public let position: Position 1799 | 1800 | /** 1801 | The option set defining the edge fade state for this scroll step. 1802 | 1803 | Possible options include `.leading` and `.trailing`, corresponding to the leading edge of the label scrolling (i.e. 1804 | the direction of scroll) and trailing edge of the label. 1805 | */ 1806 | public let edgeFades: EdgeFade 1807 | 1808 | public init(timeStep: CGFloat, timingFunction: UIView.AnimationCurve = .linear, position: Position, edgeFades: EdgeFade) { 1809 | self.timeStep = timeStep 1810 | self.position = position 1811 | self.edgeFades = edgeFades 1812 | self.timingFunction = timingFunction 1813 | } 1814 | } 1815 | 1816 | 1817 | /** 1818 | `FadeStep` types allow additional edge fade state definitions, around the states defined by the `ScrollStep` steps of 1819 | a sequence. `FadeStep` steps are defined by the time delta to the preceding or subsequent `ScrollStep` step and the timing 1820 | function to their edge fade state. 1821 | 1822 | - Note: A `FadeStep` cannot be the first step in a sequence. A `FadeStep` defined as such will be ignored. 1823 | */ 1824 | public struct FadeStep: MarqueeStep { 1825 | /** 1826 | The desired time between this `FadeStep` and the preceding or subsequent `ScrollStep` in a sequence. 1827 | 1828 | `FadeSteps` with a negative `timeStep` value will be associated _only_ with an immediately-subsequent `ScrollStep` step 1829 | in the sequence. 1830 | 1831 | `FadeSteps` with a positive `timeStep` value will be associated _only_ with an immediately-prior `ScrollStep` step in the 1832 | sequence. 1833 | 1834 | - Note: A `FadeStep` with a `timeStep` value of 0.0 will have no effect, and is the same as defining the fade state with 1835 | a `ScrollStep`. 1836 | */ 1837 | public let timeStep: CGFloat 1838 | 1839 | /** 1840 | The animation curve to utilize between the previous fade state in a sequence and this step. 1841 | */ 1842 | public let timingFunction: UIView.AnimationCurve 1843 | 1844 | /** 1845 | The option set defining the edge fade state for this fade step. 1846 | 1847 | Possible options include `.leading` and `.trailing`, corresponding to the leading edge of the label scrolling (i.e. 1848 | the direction of scroll) and trailing edge of the label. 1849 | 1850 | As an Option Set type, both edge fade states may be defined using an array literal: `[.leading, .trailing]`. 1851 | */ 1852 | public let edgeFades: EdgeFade 1853 | 1854 | public init(timeStep: CGFloat, timingFunction: UIView.AnimationCurve = .linear, edgeFades: EdgeFade) { 1855 | self.timeStep = timeStep 1856 | self.timingFunction = timingFunction 1857 | self.edgeFades = edgeFades 1858 | } 1859 | } 1860 | 1861 | public struct EdgeFade: OptionSet { 1862 | public let rawValue: Int 1863 | public static let leading = EdgeFade(rawValue: 1 << 0) 1864 | public static let trailing = EdgeFade(rawValue: 1 << 1) 1865 | 1866 | public init(rawValue: Int) { 1867 | self.rawValue = rawValue 1868 | } 1869 | } 1870 | 1871 | // Define helpful typealiases 1872 | fileprivate typealias MLAnimationCompletionBlock = (_ finished: Bool) -> Void 1873 | fileprivate typealias MLAnimation = (anim: CAKeyframeAnimation, duration: CGFloat) 1874 | 1875 | fileprivate class GradientSetupAnimation: CABasicAnimation { 1876 | } 1877 | 1878 | fileprivate extension UILabel { 1879 | func desiredSize() -> CGSize { 1880 | // Bound the expected size 1881 | let maximumLabelSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) 1882 | // Calculate the expected size 1883 | var expectedLabelSize = self.sizeThatFits(maximumLabelSize) 1884 | 1885 | #if os(tvOS) 1886 | // Sanitize width to 16384.0 (largest width a UILabel will draw on tvOS) 1887 | expectedLabelSize.width = min(expectedLabelSize.width, 16384.0) 1888 | #else 1889 | // Sanitize width to 5461.0 (largest width a UILabel will draw on an iPhone 6S Plus) 1890 | expectedLabelSize.width = min(expectedLabelSize.width, 5461.0) 1891 | #endif 1892 | 1893 | // Adjust to own height (make text baseline match normal label) 1894 | expectedLabelSize.height = bounds.size.height 1895 | return expectedLabelSize 1896 | } 1897 | } 1898 | 1899 | fileprivate extension Range where Bound == CGFloat { 1900 | func rangeForExtension(_ ext: CGFloat) -> Range { 1901 | return self.upperBound..<(self.upperBound + ext) 1902 | } 1903 | } 1904 | 1905 | fileprivate extension UIResponder { 1906 | // Thanks to Phil M 1907 | // http://stackoverflow.com/questions/1340434/get-to-uiviewcontroller-from-uiview-on-iphone 1908 | 1909 | func firstAvailableViewController() -> UIViewController? { 1910 | // convenience function for casting and to "mask" the recursive function 1911 | return self.traverseResponderChainForFirstViewController() 1912 | } 1913 | 1914 | func traverseResponderChainForFirstViewController() -> UIViewController? { 1915 | if let nextResponder = self.next { 1916 | if nextResponder is UIViewController { 1917 | return nextResponder as? UIViewController 1918 | } else if nextResponder is UIView { 1919 | return nextResponder.traverseResponderChainForFirstViewController() 1920 | } else { 1921 | return nil 1922 | } 1923 | } 1924 | return nil 1925 | } 1926 | } 1927 | 1928 | fileprivate extension CAMediaTimingFunction { 1929 | 1930 | func durationPercentageForPositionPercentage(_ positionPercentage: CGFloat, duration: CGFloat) -> CGFloat { 1931 | // Finds the animation duration percentage that corresponds with the given animation "position" percentage. 1932 | // Utilizes Newton's Method to solve for the parametric Bezier curve that is used by CAMediaAnimation. 1933 | 1934 | let controlPoints = self.controlPoints() 1935 | let epsilon: CGFloat = 1.0 / (100.0 * CGFloat(duration)) 1936 | 1937 | // Find the t value that gives the position percentage we want 1938 | let t_found = solveTforY(positionPercentage, epsilon: epsilon, controlPoints: controlPoints) 1939 | 1940 | // With that t, find the corresponding animation percentage 1941 | let durationPercentage = XforCurveAt(t_found, controlPoints: controlPoints) 1942 | 1943 | return durationPercentage 1944 | } 1945 | 1946 | func solveTforY(_ y_0: CGFloat, epsilon: CGFloat, controlPoints: [CGPoint]) -> CGFloat { 1947 | // Use Newton's Method: http://en.wikipedia.org/wiki/Newton's_method 1948 | // For first guess, use t = y (i.e. if curve were linear) 1949 | var t0 = y_0 1950 | var t1 = y_0 1951 | var f0, df0: CGFloat 1952 | 1953 | for _ in 0..<15 { 1954 | // Base this iteration of t1 calculated from last iteration 1955 | t0 = t1 1956 | // Calculate f(t0) 1957 | f0 = YforCurveAt(t0, controlPoints:controlPoints) - y_0 1958 | // Check if this is close (enough) 1959 | if abs(f0) < epsilon { 1960 | // Done! 1961 | return t0 1962 | } 1963 | // Else continue Newton's Method 1964 | df0 = derivativeCurveYValueAt(t0, controlPoints:controlPoints) 1965 | // Check if derivative is small or zero ( http://en.wikipedia.org/wiki/Newton's_method#Failure_analysis ) 1966 | if abs(df0) < 1e-6 { 1967 | break 1968 | } 1969 | // Else recalculate t1 1970 | t1 = t0 - f0/df0 1971 | } 1972 | 1973 | // Give up - shouldn't ever get here...I hope 1974 | print("MarqueeLabel: Failed to find t for Y input!") 1975 | return t0 1976 | } 1977 | 1978 | func YforCurveAt(_ t: CGFloat, controlPoints: [CGPoint]) -> CGFloat { 1979 | let P0 = controlPoints[0] 1980 | let P1 = controlPoints[1] 1981 | let P2 = controlPoints[2] 1982 | let P3 = controlPoints[3] 1983 | 1984 | // Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves 1985 | let y0 = (pow((1.0 - t), 3.0) * P0.y) 1986 | let y1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.y) 1987 | let y2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.y) 1988 | let y3 = (pow(t, 3.0) * P3.y) 1989 | 1990 | return y0 + y1 + y2 + y3 1991 | } 1992 | 1993 | func XforCurveAt(_ t: CGFloat, controlPoints: [CGPoint]) -> CGFloat { 1994 | let P0 = controlPoints[0] 1995 | let P1 = controlPoints[1] 1996 | let P2 = controlPoints[2] 1997 | let P3 = controlPoints[3] 1998 | 1999 | // Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves 2000 | 2001 | let x0 = (pow((1.0 - t), 3.0) * P0.x) 2002 | let x1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.x) 2003 | let x2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.x) 2004 | let x3 = (pow(t, 3.0) * P3.x) 2005 | 2006 | return x0 + x1 + x2 + x3 2007 | } 2008 | 2009 | func derivativeCurveYValueAt(_ t: CGFloat, controlPoints: [CGPoint]) -> CGFloat { 2010 | let P0 = controlPoints[0] 2011 | let P1 = controlPoints[1] 2012 | let P2 = controlPoints[2] 2013 | let P3 = controlPoints[3] 2014 | 2015 | let dy0 = (P0.y + 3.0 * P1.y + 3.0 * P2.y - P3.y) * -3.0 2016 | let dy1 = t * (6.0 * P0.y + 6.0 * P2.y) 2017 | let dy2 = (-3.0 * P0.y + 3.0 * P1.y) 2018 | 2019 | return dy0 * pow(t, 2.0) + dy1 + dy2 2020 | } 2021 | 2022 | func controlPoints() -> [CGPoint] { 2023 | // Create point array to point to 2024 | var point: [Float] = [0.0, 0.0] 2025 | var pointArray = [CGPoint]() 2026 | for i in 0...3 { 2027 | self.getControlPoint(at: i, values: &point) 2028 | pointArray.append(CGPoint(x: CGFloat(point[0]), y: CGFloat(point[1]))) 2029 | } 2030 | 2031 | return pointArray 2032 | } 2033 | } 2034 | 2035 | --------------------------------------------------------------------------------