text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```objective-c // // YYThreadSafeDictionary.h // YYKit <path_to_url // // Created by ibireme on 14/10/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> /** A simple implementation of thread safe mutable dictionary. @discussion Generally, access performance is lower than NSMutableDictionary, but higher than using @synchronized, NSLock, or pthread_mutex_t. @discussion It's also compatible with the custom methods in `NSDictionary(YYAdd)` and `NSMutableDictionary(YYAdd)` @warning Fast enumerate(for...in) and enumerator is not thread safe, use enumerate using block instead. When enumerate or sort with block/callback, do *NOT* send message to the dictionary inside the block/callback. */ @interface YYThreadSafeDictionary : NSMutableDictionary @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYThreadSafeDictionary.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
190
```objective-c // // YYFileHash.h // YYKit <path_to_url // // Created by ibireme on 14/11/2. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /// File hash algorithm type typedef NS_OPTIONS (NSUInteger, YYFileHashType) { YYFileHashTypeMD2 = 1 << 0, ///< MD2 hash YYFileHashTypeMD4 = 1 << 1, ///< MD4 hash YYFileHashTypeMD5 = 1 << 2, ///< MD5 hash YYFileHashTypeSHA1 = 1 << 3, ///< SHA1 hash YYFileHashTypeSHA224 = 1 << 4, ///< SHA224 hash YYFileHashTypeSHA256 = 1 << 5, ///< SHA256 hash YYFileHashTypeSHA384 = 1 << 6, ///< SHA384 hash YYFileHashTypeSHA512 = 1 << 7, ///< SHA512 hash YYFileHashTypeCRC32 = 1 << 8, ///< crc32 checksum YYFileHashTypeAdler32 = 1 << 9, ///< adler32 checksum }; /** Utility for computing hashes of file with high performance and low memory usage. See `YYFileHashType` for all supported hash (checksum) type. Sample Code: YYFileHash *hash = [YYFileHash hashForFile:@"/tmp/Xcode6.dmg" types:YYFileHashTypeMD5 | YYFileHashTypeSHA1]; NSLog(@"md5:%@ sha1:%@", hash.md5String, hash.sha1String); */ @interface YYFileHash : NSObject /** Start calculate file hash and return the result. @discussion The calling thread is blocked until the asynchronous hash progress finished. @param filePath The path to the file to access. @param types File hash algorithm types. @return File hash result, or nil when an error occurs. */ + (nullable YYFileHash *)hashForFile:(NSString *)filePath types:(YYFileHashType)types; /** Start calculate file hash and return the result. @discussion The calling thread is blocked until the asynchronous hash progress finished or cancelled. @param filePath The path to the file to access. @param types File hash algorithm types. @param block A block which is called in progress. The block takes 3 arguments: `totalSize` is the total file size in bytes; `processedSize` is the processed file size in bytes; `stop` is a reference to a Boolean value, which can be set to YES to stop further processing. If the block stop the processing, it just returns nil. @return File hash result, or nil when an error occurs. */ + (nullable YYFileHash *)hashForFile:(NSString *)filePath types:(YYFileHashType)types usingBlock:(nullable void (^)(UInt64 totalSize, UInt64 processedSize, BOOL *stop))block; @property (nonatomic, readonly) YYFileHashType types; ///< hash type @property (nullable, nonatomic, strong, readonly) NSString *md2String; ///< md2 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *md4String; ///< md4 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *md5String; ///< md5 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *sha1String; ///< sha1 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *sha224String; ///< sha224 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *sha256String; ///< sha256 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *sha384String; ///< sha384 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *sha512String; ///< sha512 hash string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *crc32String; ///< crc32 checksum string in lowercase @property (nullable, nonatomic, strong, readonly) NSString *adler32String; ///< adler32 checksum string in lowercase @property (nullable, nonatomic, strong, readonly) NSData *md2Data; ///< md2 hash @property (nullable, nonatomic, strong, readonly) NSData *md4Data; ///< md4 hash @property (nullable, nonatomic, strong, readonly) NSData *md5Data; ///< md5 hash @property (nullable, nonatomic, strong, readonly) NSData *sha1Data; ///< sha1 hash @property (nullable, nonatomic, strong, readonly) NSData *sha224Data; ///< sha224 hash @property (nullable, nonatomic, strong, readonly) NSData *sha256Data; ///< sha256 hash @property (nullable, nonatomic, strong, readonly) NSData *sha384Data; ///< sha384 hash @property (nullable, nonatomic, strong, readonly) NSData *sha512Data; ///< sha512 hash @property (nonatomic, readonly) uint32_t crc32; ///< crc32 checksum @property (nonatomic, readonly) uint32_t adler32; ///< adler32 checksum @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYFileHash.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,152
```objective-c // // NSObject+YYAdd.m // YYKit <path_to_url // // Created by ibireme on 14/10/8. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "NSObject+YYAdd.h" #import "YYKitMacro.h" #import <objc/objc.h> #import <objc/runtime.h> YYSYNTH_DUMMY_CLASS(NSObject_YYAdd) @implementation NSObject (YYAdd) /* NSInvocation is much slower than objc_msgSend()... Do not use it if you have performance issues. */ #define INIT_INV(_last_arg_, _return_) \ NSMethodSignature * sig = [self methodSignatureForSelector:sel]; \ if (!sig) { [self doesNotRecognizeSelector:sel]; return _return_; } \ NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig]; \ if (!inv) { [self doesNotRecognizeSelector:sel]; return _return_; } \ [inv setTarget:self]; \ [inv setSelector:sel]; \ va_list args; \ va_start(args, _last_arg_); \ [NSObject setInv:inv withSig:sig andArgs:args]; \ va_end(args); - (id)performSelectorWithArgs:(SEL)sel, ...{ INIT_INV(sel, nil); [inv invoke]; return [NSObject getReturnFromInv:inv withSig:sig]; } - (void)performSelectorWithArgs:(SEL)sel afterDelay:(NSTimeInterval)delay, ...{ INIT_INV(delay, ); [inv retainArguments]; [inv performSelector:@selector(invoke) withObject:nil afterDelay:delay]; } - (id)performSelectorWithArgsOnMainThread:(SEL)sel waitUntilDone:(BOOL)wait, ...{ INIT_INV(wait, nil); if (!wait) [inv retainArguments]; [inv performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:wait]; return wait ? [NSObject getReturnFromInv:inv withSig:sig] : nil; } - (id)performSelectorWithArgs:(SEL)sel onThread:(NSThread *)thr waitUntilDone:(BOOL)wait, ...{ INIT_INV(wait, nil); if (!wait) [inv retainArguments]; [inv performSelector:@selector(invoke) onThread:thr withObject:nil waitUntilDone:wait]; return wait ? [NSObject getReturnFromInv:inv withSig:sig] : nil; } - (void)performSelectorWithArgsInBackground:(SEL)sel, ...{ INIT_INV(sel, ); [inv retainArguments]; [inv performSelectorInBackground:@selector(invoke) withObject:nil]; } #undef INIT_INV + (id)getReturnFromInv:(NSInvocation *)inv withSig:(NSMethodSignature *)sig { NSUInteger length = [sig methodReturnLength]; if (length == 0) return nil; char *type = (char *)[sig methodReturnType]; while (*type == 'r' || // const *type == 'n' || // in *type == 'N' || // inout *type == 'o' || // out *type == 'O' || // bycopy *type == 'R' || // byref *type == 'V') { // oneway type++; // cutoff useless prefix } #define return_with_number(_type_) \ do { \ _type_ ret; \ [inv getReturnValue:&ret]; \ return @(ret); \ } while (0) switch (*type) { case 'v': return nil; // void case 'B': return_with_number(bool); case 'c': return_with_number(char); case 'C': return_with_number(unsigned char); case 's': return_with_number(short); case 'S': return_with_number(unsigned short); case 'i': return_with_number(int); case 'I': return_with_number(unsigned int); case 'l': return_with_number(int); case 'L': return_with_number(unsigned int); case 'q': return_with_number(long long); case 'Q': return_with_number(unsigned long long); case 'f': return_with_number(float); case 'd': return_with_number(double); case 'D': { // long double long double ret; [inv getReturnValue:&ret]; return [NSNumber numberWithDouble:ret]; }; case '@': { // id id ret = nil; [inv getReturnValue:&ret]; return ret; }; case '#': { // Class Class ret = nil; [inv getReturnValue:&ret]; return ret; }; default: { // struct / union / SEL / void* / unknown const char *objCType = [sig methodReturnType]; char *buf = calloc(1, length); if (!buf) return nil; [inv getReturnValue:buf]; NSValue *value = [NSValue valueWithBytes:buf objCType:objCType]; free(buf); return value; }; } #undef return_with_number } + (void)setInv:(NSInvocation *)inv withSig:(NSMethodSignature *)sig andArgs:(va_list)args { NSUInteger count = [sig numberOfArguments]; for (int index = 2; index < count; index++) { char *type = (char *)[sig getArgumentTypeAtIndex:index]; while (*type == 'r' || // const *type == 'n' || // in *type == 'N' || // inout *type == 'o' || // out *type == 'O' || // bycopy *type == 'R' || // byref *type == 'V') { // oneway type++; // cutoff useless prefix } BOOL unsupportedType = NO; switch (*type) { case 'v': // 1: void case 'B': // 1: bool case 'c': // 1: char / BOOL case 'C': // 1: unsigned char case 's': // 2: short case 'S': // 2: unsigned short case 'i': // 4: int / NSInteger(32bit) case 'I': // 4: unsigned int / NSUInteger(32bit) case 'l': // 4: long(32bit) case 'L': // 4: unsigned long(32bit) { // 'char' and 'short' will be promoted to 'int'. int arg = va_arg(args, int); [inv setArgument:&arg atIndex:index]; } break; case 'q': // 8: long long / long(64bit) / NSInteger(64bit) case 'Q': // 8: unsigned long long / unsigned long(64bit) / NSUInteger(64bit) { long long arg = va_arg(args, long long); [inv setArgument:&arg atIndex:index]; } break; case 'f': // 4: float / CGFloat(32bit) { // 'float' will be promoted to 'double'. double arg = va_arg(args, double); float argf = arg; [inv setArgument:&argf atIndex:index]; } break; case 'd': // 8: double / CGFloat(64bit) { double arg = va_arg(args, double); [inv setArgument:&arg atIndex:index]; } break; case 'D': // 16: long double { long double arg = va_arg(args, long double); [inv setArgument:&arg atIndex:index]; } break; case '*': // char * case '^': // pointer { void *arg = va_arg(args, void *); [inv setArgument:&arg atIndex:index]; } break; case ':': // SEL { SEL arg = va_arg(args, SEL); [inv setArgument:&arg atIndex:index]; } break; case '#': // Class { Class arg = va_arg(args, Class); [inv setArgument:&arg atIndex:index]; } break; case '@': // id { id arg = va_arg(args, id); [inv setArgument:&arg atIndex:index]; } break; case '{': // struct { if (strcmp(type, @encode(CGPoint)) == 0) { CGPoint arg = va_arg(args, CGPoint); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(CGSize)) == 0) { CGSize arg = va_arg(args, CGSize); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(CGRect)) == 0) { CGRect arg = va_arg(args, CGRect); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(CGVector)) == 0) { CGVector arg = va_arg(args, CGVector); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(CGAffineTransform)) == 0) { CGAffineTransform arg = va_arg(args, CGAffineTransform); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(CATransform3D)) == 0) { CATransform3D arg = va_arg(args, CATransform3D); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(NSRange)) == 0) { NSRange arg = va_arg(args, NSRange); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(UIOffset)) == 0) { UIOffset arg = va_arg(args, UIOffset); [inv setArgument:&arg atIndex:index]; } else if (strcmp(type, @encode(UIEdgeInsets)) == 0) { UIEdgeInsets arg = va_arg(args, UIEdgeInsets); [inv setArgument:&arg atIndex:index]; } else { unsupportedType = YES; } } break; case '(': // union { unsupportedType = YES; } break; case '[': // array { unsupportedType = YES; } break; default: // what?! { unsupportedType = YES; } break; } if (unsupportedType) { // Try with some dummy type... NSUInteger size = 0; NSGetSizeAndAlignment(type, &size, NULL); #define case_size(_size_) \ else if (size <= 4 * _size_ ) { \ struct dummy { char tmp[4 * _size_]; }; \ struct dummy arg = va_arg(args, struct dummy); \ [inv setArgument:&arg atIndex:index]; \ } if (size == 0) { } case_size( 1) case_size( 2) case_size( 3) case_size( 4) case_size( 5) case_size( 6) case_size( 7) case_size( 8) case_size( 9) case_size(10) case_size(11) case_size(12) case_size(13) case_size(14) case_size(15) case_size(16) case_size(17) case_size(18) case_size(19) case_size(20) case_size(21) case_size(22) case_size(23) case_size(24) case_size(25) case_size(26) case_size(27) case_size(28) case_size(29) case_size(30) case_size(31) case_size(32) case_size(33) case_size(34) case_size(35) case_size(36) case_size(37) case_size(38) case_size(39) case_size(40) case_size(41) case_size(42) case_size(43) case_size(44) case_size(45) case_size(46) case_size(47) case_size(48) case_size(49) case_size(50) case_size(51) case_size(52) case_size(53) case_size(54) case_size(55) case_size(56) case_size(57) case_size(58) case_size(59) case_size(60) case_size(61) case_size(62) case_size(63) case_size(64) else { /* Larger than 256 byte?! I don't want to deal with this stuff up... Ignore this argument. */ struct dummy {char tmp;}; for (int i = 0; i < size; i++) va_arg(args, struct dummy); NSLog(@"YYKit performSelectorWithArgs unsupported type:%s (%lu bytes)", [sig getArgumentTypeAtIndex:index],(unsigned long)size); } #undef case_size } } } - (void)performSelector:(SEL)sel afterDelay:(NSTimeInterval)delay { [self performSelector:sel withObject:nil afterDelay:delay]; } + (BOOL)swizzleInstanceMethod:(SEL)originalSel with:(SEL)newSel { Method originalMethod = class_getInstanceMethod(self, originalSel); Method newMethod = class_getInstanceMethod(self, newSel); if (!originalMethod || !newMethod) return NO; class_addMethod(self, originalSel, class_getMethodImplementation(self, originalSel), method_getTypeEncoding(originalMethod)); class_addMethod(self, newSel, class_getMethodImplementation(self, newSel), method_getTypeEncoding(newMethod)); method_exchangeImplementations(class_getInstanceMethod(self, originalSel), class_getInstanceMethod(self, newSel)); return YES; } + (BOOL)swizzleClassMethod:(SEL)originalSel with:(SEL)newSel { Class class = object_getClass(self); Method originalMethod = class_getInstanceMethod(class, originalSel); Method newMethod = class_getInstanceMethod(class, newSel); if (!originalMethod || !newMethod) return NO; method_exchangeImplementations(originalMethod, newMethod); return YES; } - (void)setAssociateValue:(id)value withKey:(void *)key { objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)setAssociateWeakValue:(id)value withKey:(void *)key { objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_ASSIGN); } - (void)removeAssociatedValues { objc_removeAssociatedObjects(self); } - (id)getAssociatedValueForKey:(void *)key { return objc_getAssociatedObject(self, key); } + (NSString *)className { return NSStringFromClass(self); } - (NSString *)className { return [NSString stringWithUTF8String:class_getName([self class])]; } - (id)deepCopy { id obj = nil; @try { obj = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self]]; } @catch (NSException *exception) { NSLog(@"%@", exception); } return obj; } - (id)deepCopyWithArchiver:(Class)archiver unarchiver:(Class)unarchiver { id obj = nil; @try { obj = [unarchiver unarchiveObjectWithData:[archiver archivedDataWithRootObject:self]]; } @catch (NSException *exception) { NSLog(@"%@", exception); } return obj; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSObject+YYAdd.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
3,383
```objective-c // // YYGestureRecognizer.h // YYKit <path_to_url // // Created by ibireme on 14/10/26. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /// State of the gesture typedef NS_ENUM(NSUInteger, YYGestureRecognizerState) { YYGestureRecognizerStateBegan, ///< gesture start YYGestureRecognizerStateMoved, ///< gesture moved YYGestureRecognizerStateEnded, ///< gesture end YYGestureRecognizerStateCancelled, ///< gesture cancel }; /** A simple UIGestureRecognizer subclass for receive touch events. */ @interface YYGestureRecognizer : UIGestureRecognizer @property (nonatomic, readonly) CGPoint startPoint; ///< start point @property (nonatomic, readonly) CGPoint lastPoint; ///< last move point. @property (nonatomic, readonly) CGPoint currentPoint; ///< current move point. /// The action block invoked by every gesture event. @property (nullable, nonatomic, copy) void (^action)(YYGestureRecognizer *gesture, YYGestureRecognizerState state); /// Cancel the gesture for current touch. - (void)cancel; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYGestureRecognizer.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
248
```objective-c // // YYTimer.h // YYKit <path_to_url // // Created by ibireme on 15/2/7. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** YYTimer is a thread-safe timer based on GCD. It has similar API with `NSTimer`. YYTimer object differ from NSTimer in a few ways: * It use GCD to produce timer tick, and won't be affected by runLoop. * It make a weak reference to the target, so it can avoid retain cycles. * It always fire on main thread. */ @interface YYTimer : NSObject + (YYTimer *)timerWithTimeInterval:(NSTimeInterval)interval target:(id)target selector:(SEL)selector repeats:(BOOL)repeats; - (instancetype)initWithFireTime:(NSTimeInterval)start interval:(NSTimeInterval)interval target:(id)target selector:(SEL)selector repeats:(BOOL)repeats NS_DESIGNATED_INITIALIZER; @property (readonly) BOOL repeats; @property (readonly) NSTimeInterval timeInterval; @property (readonly, getter=isValid) BOOL valid; - (void)invalidate; - (void)fire; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYTimer.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
291
```objective-c // // YYSentinel.h // YYKit <path_to_url // // Created by ibireme on 15/4/13. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** YYSentinel is a thread safe incrementing counter. It may be used in some multi-threaded situation. */ @interface YYSentinel : NSObject /// Returns the current value of the counter. @property (readonly) int32_t value; /// Increase the value atomically. /// @return The new value. - (int32_t)increase; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYSentinel.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
155
```objective-c // // YYAsyncLayer.m // YYKit <path_to_url // // Created by ibireme on 15/4/11. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYAsyncLayer.h" #import "YYSentinel.h" #if __has_include("YYDispatchQueuePool.h") #import "YYDispatchQueuePool.h" #else #import <libkern/OSAtomic.h> #endif /// Global display queue, used for content rendering. static dispatch_queue_t YYAsyncLayerGetDisplayQueue() { #ifdef YYDispatchQueuePool_h return YYDispatchQueueGetForQOS(NSQualityOfServiceUserInitiated); #else #define MAX_QUEUE_COUNT 16 static int queueCount; static dispatch_queue_t queues[MAX_QUEUE_COUNT]; static dispatch_once_t onceToken; static int32_t counter = 0; dispatch_once(&onceToken, ^{ queueCount = (int)[NSProcessInfo processInfo].activeProcessorCount; queueCount = queueCount < 1 ? 1 : queueCount > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : queueCount; if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) { for (NSUInteger i = 0; i < queueCount; i++) { dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0); queues[i] = dispatch_queue_create("com.ibireme.yykit.render", attr); } } else { for (NSUInteger i = 0; i < queueCount; i++) { queues[i] = dispatch_queue_create("com.ibireme.yykit.render", DISPATCH_QUEUE_SERIAL); dispatch_set_target_queue(queues[i], dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); } } }); int32_t cur = OSAtomicIncrement32(&counter); if (cur < 0) cur = -cur; return queues[(cur) % queueCount]; #undef MAX_QUEUE_COUNT #endif } static dispatch_queue_t YYAsyncLayerGetReleaseQueue() { #ifdef YYDispatchQueuePool_h return YYDispatchQueueGetForQOS(NSQualityOfServiceDefault); #else return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0); #endif } @implementation YYAsyncLayerDisplayTask @end @implementation YYAsyncLayer { YYSentinel *_sentinel; } #pragma mark - Override + (id)defaultValueForKey:(NSString *)key { if ([key isEqualToString:@"displaysAsynchronously"]) { return @(YES); } else { return [super defaultValueForKey:key]; } } - (instancetype)init { self = [super init]; static CGFloat scale; //global static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ scale = [UIScreen mainScreen].scale; }); self.contentsScale = scale; _sentinel = [YYSentinel new]; _displaysAsynchronously = YES; return self; } - (void)dealloc { [_sentinel increase]; } - (void)setNeedsDisplay { [self _cancelAsyncDisplay]; [super setNeedsDisplay]; } - (void)display { super.contents = super.contents; [self _displayAsync:_displaysAsynchronously]; } #pragma mark - Private - (void)_displayAsync:(BOOL)async { __strong id<YYAsyncLayerDelegate> delegate = (id)self.delegate; YYAsyncLayerDisplayTask *task = [delegate newAsyncDisplayTask]; if (!task.display) { if (task.willDisplay) task.willDisplay(self); self.contents = nil; if (task.didDisplay) task.didDisplay(self, YES); return; } if (async) { if (task.willDisplay) task.willDisplay(self); YYSentinel *sentinel = _sentinel; int32_t value = sentinel.value; BOOL (^isCancelled)() = ^BOOL() { return value != sentinel.value; }; CGSize size = self.bounds.size; BOOL opaque = self.opaque; CGFloat scale = self.contentsScale; CGColorRef backgroundColor = (opaque && self.backgroundColor) ? CGColorRetain(self.backgroundColor) : NULL; if (size.width < 1 || size.height < 1) { CGImageRef image = (__bridge_retained CGImageRef)(self.contents); self.contents = nil; if (image) { dispatch_async(YYAsyncLayerGetReleaseQueue(), ^{ CFRelease(image); }); } if (task.didDisplay) task.didDisplay(self, YES); CGColorRelease(backgroundColor); return; } dispatch_async(YYAsyncLayerGetDisplayQueue(), ^{ if (isCancelled()) { CGColorRelease(backgroundColor); return; } UIGraphicsBeginImageContextWithOptions(size, opaque, scale); CGContextRef context = UIGraphicsGetCurrentContext(); if (opaque) { CGContextSaveGState(context); { if (!backgroundColor || CGColorGetAlpha(backgroundColor) < 1) { CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor); CGContextAddRect(context, CGRectMake(0, 0, size.width * scale, size.height * scale)); CGContextFillPath(context); } if (backgroundColor) { CGContextSetFillColorWithColor(context, backgroundColor); CGContextAddRect(context, CGRectMake(0, 0, size.width * scale, size.height * scale)); CGContextFillPath(context); } } CGContextRestoreGState(context); CGColorRelease(backgroundColor); } task.display(context, size, isCancelled); if (isCancelled()) { UIGraphicsEndImageContext(); dispatch_async(dispatch_get_main_queue(), ^{ if (task.didDisplay) task.didDisplay(self, NO); }); return; } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if (isCancelled()) { dispatch_async(dispatch_get_main_queue(), ^{ if (task.didDisplay) task.didDisplay(self, NO); }); return; } dispatch_async(dispatch_get_main_queue(), ^{ if (isCancelled()) { if (task.didDisplay) task.didDisplay(self, NO); } else { self.contents = (__bridge id)(image.CGImage); if (task.didDisplay) task.didDisplay(self, YES); } }); }); } else { [_sentinel increase]; if (task.willDisplay) task.willDisplay(self); UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, self.contentsScale); CGContextRef context = UIGraphicsGetCurrentContext(); if (self.opaque) { CGSize size = self.bounds.size; size.width *= self.contentsScale; size.height *= self.contentsScale; CGContextSaveGState(context); { if (!self.backgroundColor || CGColorGetAlpha(self.backgroundColor) < 1) { CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor); CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height)); CGContextFillPath(context); } if (self.backgroundColor) { CGContextSetFillColorWithColor(context, self.backgroundColor); CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height)); CGContextFillPath(context); } } CGContextRestoreGState(context); } task.display(context, self.bounds.size, ^{return NO;}); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.contents = (__bridge id)(image.CGImage); if (task.didDisplay) task.didDisplay(self, YES); } } - (void)_cancelAsyncDisplay { [_sentinel increase]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYAsyncLayer.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,664
```objective-c // // YYWeakProxy.h // YYKit <path_to_url // // Created by ibireme on 14/10/18. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** A proxy used to hold a weak object. It can be used to avoid retain cycles, such as the target in NSTimer or CADisplayLink. sample code: @implementation MyView { NSTimer *_timer; } - (void)initTimer { YYWeakProxy *proxy = [YYWeakProxy proxyWithTarget:self]; _timer = [NSTimer timerWithTimeInterval:0.1 target:proxy selector:@selector(tick:) userInfo:nil repeats:YES]; } - (void)tick:(NSTimer *)timer {...} @end */ @interface YYWeakProxy : NSProxy /** The proxy target. */ @property (nullable, nonatomic, weak, readonly) id target; /** Creates a new weak proxy for target. @param target Target object. @return A new proxy object. */ - (instancetype)initWithTarget:(id)target; /** Creates a new weak proxy for target. @param target Target object. @return A new proxy object. */ + (instancetype)proxyWithTarget:(id)target; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYWeakProxy.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
305
```objective-c // // YYReachability.h // YYKit <path_to_url // // Created by ibireme on 15/2/6. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> #import <SystemConfiguration/SystemConfiguration.h> #import <netinet/in.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSUInteger, YYReachabilityStatus) { YYReachabilityStatusNone = 0, ///< Not Reachable YYReachabilityStatusWWAN = 1, ///< Reachable via WWAN (2G/3G/4G) YYReachabilityStatusWiFi = 2, ///< Reachable via WiFi }; typedef NS_ENUM(NSUInteger, YYReachabilityWWANStatus) { YYReachabilityWWANStatusNone = 0, ///< Not Reachable vis WWAN YYReachabilityWWANStatus2G = 2, ///< Reachable via 2G (GPRS/EDGE) 10~100Kbps YYReachabilityWWANStatus3G = 3, ///< Reachable via 3G (WCDMA/HSDPA/...) 1~10Mbps YYReachabilityWWANStatus4G = 4, ///< Reachable via 4G (eHRPD/LTE) 100Mbps }; /** `YYReachability` can used to monitor the network status of an iOS device. */ @interface YYReachability : NSObject @property (nonatomic, readonly) SCNetworkReachabilityFlags flags; ///< Current flags. @property (nonatomic, readonly) YYReachabilityStatus status; ///< Current status. @property (nonatomic, readonly) YYReachabilityWWANStatus wwanStatus NS_AVAILABLE_IOS(7_0); ///< Current WWAN status. @property (nonatomic, readonly, getter=isReachable) BOOL reachable; ///< Current reachable status. /// Notify block which will be called on main thread when network changed. @property (nullable, nonatomic, copy) void (^notifyBlock)(YYReachability *reachability); /// Create an object to check the reachability of the default route. + (instancetype)reachability; /// Create an object to check the reachability of the local WI-FI. + (instancetype)reachabilityForLocalWifi DEPRECATED_MSG_ATTRIBUTE("unnecessary and potentially harmful"); /// Create an object to check the reachability of a given host name. + (nullable instancetype)reachabilityWithHostname:(NSString *)hostname; /// Create an object to check the reachability of a given IP address /// @param hostAddress You may pass `struct sockaddr_in` for IPv4 address or `struct sockaddr_in6` for IPv6 address. + (nullable instancetype)reachabilityWithAddress:(const struct sockaddr *)hostAddress; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYReachability.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
604
```objective-c // // YYSentinel.m // YYKit <path_to_url // // Created by ibireme on 15/4/13. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYSentinel.h" #import <libkern/OSAtomic.h> @implementation YYSentinel { int32_t _value; } - (int32_t)value { return _value; } - (int32_t)increase { return OSAtomicIncrement32(&_value); } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYSentinel.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
129
```objective-c // // YYThreadSafeArray.m // YYKit <path_to_url // // Created by ibireme on 14/10/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYThreadSafeArray.h" #import "NSArray+YYAdd.h" #define INIT(...) self = super.init; \ if (!self) return nil; \ __VA_ARGS__; \ if (!_arr) return nil; \ _lock = dispatch_semaphore_create(1); \ return self; #define LOCK(...) dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \ __VA_ARGS__; \ dispatch_semaphore_signal(_lock); @implementation YYThreadSafeArray { NSMutableArray *_arr; //Subclass a class cluster... dispatch_semaphore_t _lock; } #pragma mark - init - (instancetype)init { INIT(_arr = [[NSMutableArray alloc] init]); } - (instancetype)initWithCapacity:(NSUInteger)numItems { INIT(_arr = [[NSMutableArray alloc] initWithCapacity:numItems]); } - (instancetype)initWithArray:(NSArray *)array { INIT(_arr = [[NSMutableArray alloc] initWithArray:array]); } - (instancetype)initWithObjects:(const id[])objects count:(NSUInteger)cnt { INIT(_arr = [[NSMutableArray alloc] initWithObjects:objects count:cnt]); } - (instancetype)initWithContentsOfFile:(NSString *)path { INIT(_arr = [[NSMutableArray alloc] initWithContentsOfFile:path]); } - (instancetype)initWithContentsOfURL:(NSURL *)url { INIT(_arr = [[NSMutableArray alloc] initWithContentsOfURL:url]); } #pragma mark - method - (NSUInteger)count { LOCK(NSUInteger count = _arr.count); return count; } - (id)objectAtIndex:(NSUInteger)index { LOCK(id obj = [_arr objectAtIndex:index]); return obj; } - (NSArray *)arrayByAddingObject:(id)anObject { LOCK(NSArray * arr = [_arr arrayByAddingObject:anObject]); return arr; } - (NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray { LOCK(NSArray * arr = [_arr arrayByAddingObjectsFromArray:otherArray]); return arr; } - (NSString *)componentsJoinedByString:(NSString *)separator { LOCK(NSString * str = [_arr componentsJoinedByString:separator]); return str; } - (BOOL)containsObject:(id)anObject { LOCK(BOOL c = [_arr containsObject:anObject]); return c; } - (NSString *)description { LOCK(NSString * d = _arr.description); return d; } - (NSString *)descriptionWithLocale:(id)locale { LOCK(NSString * d = [_arr descriptionWithLocale:locale]); return d; } - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level { LOCK(NSString * d = [_arr descriptionWithLocale:locale indent:level]); return d; } - (id)firstObjectCommonWithArray:(NSArray *)otherArray { LOCK(id o = [_arr firstObjectCommonWithArray:otherArray]); return o; } - (void)getObjects:(id __unsafe_unretained[])objects range:(NSRange)range { LOCK([_arr getObjects:objects range:range]); } - (NSUInteger)indexOfObject:(id)anObject { LOCK(NSUInteger i = [_arr indexOfObject:anObject]); return i; } - (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range { LOCK(NSUInteger i = [_arr indexOfObject:anObject inRange:range]); return i; } - (NSUInteger)indexOfObjectIdenticalTo:(id)anObject { LOCK(NSUInteger i = [_arr indexOfObjectIdenticalTo:anObject]); return i; } - (NSUInteger)indexOfObjectIdenticalTo:(id)anObject inRange:(NSRange)range { LOCK(NSUInteger i = [_arr indexOfObjectIdenticalTo:anObject inRange:range]); return i; } - (id)firstObject { LOCK(id o = _arr.firstObject); return o; } - (id)lastObject { LOCK(id o = _arr.lastObject); return o; } - (NSEnumerator *)objectEnumerator { LOCK(NSEnumerator * e = [_arr objectEnumerator]); return e; } - (NSEnumerator *)reverseObjectEnumerator { LOCK(NSEnumerator * e = [_arr reverseObjectEnumerator]); return e; } - (NSData *)sortedArrayHint { LOCK(NSData * d = [_arr sortedArrayHint]); return d; } - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context { LOCK(NSArray * arr = [_arr sortedArrayUsingFunction:comparator context:context]) return arr; } - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context hint:(NSData *)hint { LOCK(NSArray * arr = [_arr sortedArrayUsingFunction:comparator context:context hint:hint]); return arr; } - (NSArray *)sortedArrayUsingSelector:(SEL)comparator { LOCK(NSArray * arr = [_arr sortedArrayUsingSelector:comparator]); return arr; } - (NSArray *)subarrayWithRange:(NSRange)range { LOCK(NSArray * arr = [_arr subarrayWithRange:range]) return arr; } - (void)makeObjectsPerformSelector:(SEL)aSelector { LOCK([_arr makeObjectsPerformSelector:aSelector]); } - (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument { LOCK([_arr makeObjectsPerformSelector:aSelector withObject:argument]); } - (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes { LOCK(NSArray * arr = [_arr objectsAtIndexes:indexes]); return arr; } - (id)objectAtIndexedSubscript:(NSUInteger)idx { LOCK(id o = [_arr objectAtIndexedSubscript:idx]); return o; } - (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block { LOCK([_arr enumerateObjectsUsingBlock:block]); } - (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block { LOCK([_arr enumerateObjectsWithOptions:opts usingBlock:block]); } - (void)enumerateObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block { LOCK([_arr enumerateObjectsAtIndexes:s options:opts usingBlock:block]); } - (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate { LOCK(NSUInteger i = [_arr indexOfObjectPassingTest:predicate]); return i; } - (NSUInteger)indexOfObjectWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate { LOCK(NSUInteger i = [_arr indexOfObjectWithOptions:opts passingTest:predicate]); return i; } - (NSUInteger)indexOfObjectAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate { LOCK(NSUInteger i = [_arr indexOfObjectAtIndexes:s options:opts passingTest:predicate]); return i; } - (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate { LOCK(NSIndexSet * i = [_arr indexesOfObjectsPassingTest:predicate]); return i; } - (NSIndexSet *)indexesOfObjectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate { LOCK(NSIndexSet * i = [_arr indexesOfObjectsWithOptions:opts passingTest:predicate]); return i; } - (NSIndexSet *)indexesOfObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate { LOCK(NSIndexSet * i = [_arr indexesOfObjectsAtIndexes:s options:opts passingTest:predicate]); return i; } - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr { LOCK(NSArray * a = [_arr sortedArrayUsingComparator:cmptr]); return a; } - (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr { LOCK(NSArray * a = [_arr sortedArrayWithOptions:opts usingComparator:cmptr]); return a; } - (NSUInteger)indexOfObject:(id)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp { LOCK(NSUInteger i = [_arr indexOfObject:obj inSortedRange:r options:opts usingComparator:cmp]); return i; } #pragma mark - mutable - (void)addObject:(id)anObject { LOCK([_arr addObject:anObject]); } - (void)insertObject:(id)anObject atIndex:(NSUInteger)index { LOCK([_arr insertObject:anObject atIndex:index]); } - (void)removeLastObject { LOCK([_arr removeLastObject]); } - (void)removeObjectAtIndex:(NSUInteger)index { LOCK([_arr removeObjectAtIndex:index]); } - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject { LOCK([_arr replaceObjectAtIndex:index withObject:anObject]); } - (void)addObjectsFromArray:(NSArray *)otherArray { LOCK([_arr addObjectsFromArray:otherArray]); } - (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2 { LOCK([_arr exchangeObjectAtIndex:idx1 withObjectAtIndex:idx2]); } - (void)removeAllObjects { LOCK([_arr removeAllObjects]); } - (void)removeObject:(id)anObject inRange:(NSRange)range { LOCK([_arr removeObject:anObject inRange:range]); } - (void)removeObject:(id)anObject { LOCK([_arr removeObject:anObject]); } - (void)removeObjectIdenticalTo:(id)anObject inRange:(NSRange)range { LOCK([_arr removeObjectIdenticalTo:anObject inRange:range]); } - (void)removeObjectIdenticalTo:(id)anObject { LOCK([_arr removeObjectIdenticalTo:anObject]); } - (void)removeObjectsInArray:(NSArray *)otherArray { LOCK([_arr removeObjectsInArray:otherArray]); } - (void)removeObjectsInRange:(NSRange)range { LOCK([_arr removeObjectsInRange:range]); } - (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray *)otherArray range:(NSRange)otherRange { LOCK([_arr replaceObjectsInRange:range withObjectsFromArray:otherArray range:otherRange]); } - (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray *)otherArray { LOCK([_arr replaceObjectsInRange:range withObjectsFromArray:otherArray]); } - (void)setArray:(NSArray *)otherArray { LOCK([_arr setArray:otherArray]); } - (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context { LOCK([_arr sortUsingFunction:compare context:context]); } - (void)sortUsingSelector:(SEL)comparator { LOCK([_arr sortUsingSelector:comparator]); } - (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes { LOCK([_arr insertObjects:objects atIndexes:indexes]); } - (void)removeObjectsAtIndexes:(NSIndexSet *)indexes { LOCK([_arr removeObjectsAtIndexes:indexes]); } - (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray *)objects { LOCK([_arr replaceObjectsAtIndexes:indexes withObjects:objects]); } - (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx { LOCK([_arr setObject:obj atIndexedSubscript:idx]); } - (void)sortUsingComparator:(NSComparator)cmptr { LOCK([_arr sortUsingComparator:cmptr]); } - (void)sortWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr { LOCK([_arr sortWithOptions:opts usingComparator:cmptr]); } - (BOOL)isEqualToArray:(NSArray *)otherArray { if (otherArray == self) return YES; if ([otherArray isKindOfClass:YYThreadSafeArray.class]) { YYThreadSafeArray *other = (id)otherArray; BOOL isEqual; dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); dispatch_semaphore_wait(other->_lock, DISPATCH_TIME_FOREVER); isEqual = [_arr isEqualToArray:other->_arr]; dispatch_semaphore_signal(other->_lock); dispatch_semaphore_signal(_lock); return isEqual; } return NO; } #pragma mark - protocol - (id)copyWithZone:(NSZone *)zone { return [self mutableCopyWithZone:zone]; } - (id)mutableCopyWithZone:(NSZone *)zone { LOCK(id copiedDictionary = [[self.class allocWithZone:zone] initWithArray:_arr]); return copiedDictionary; } - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained[])stackbuf count:(NSUInteger)len { LOCK(NSUInteger count = [_arr countByEnumeratingWithState:state objects:stackbuf count:len]); return count; } - (BOOL)isEqual:(id)object { if (object == self) return YES; if ([object isKindOfClass:YYThreadSafeArray.class]) { YYThreadSafeArray *other = object; BOOL isEqual; dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); dispatch_semaphore_wait(other->_lock, DISPATCH_TIME_FOREVER); isEqual = [_arr isEqual:other->_arr]; dispatch_semaphore_signal(other->_lock); dispatch_semaphore_signal(_lock); return isEqual; } return NO; } - (NSUInteger)hash { LOCK(NSUInteger hash = [_arr hash]); return hash; } #pragma mark - custom methods for NSArray(YYAdd) - (id)randomObject { LOCK(id o = [_arr randomObject]) return o; } - (id)objectOrNilAtIndex:(NSUInteger)index { LOCK(id o = [_arr objectOrNilAtIndex:index]) return o; } - (void)removeFirstObject { LOCK([_arr removeFirstObject]); } - (id)popFirstObject { LOCK(id o = [_arr popFirstObject]) return o; } - (id)popLastObject { LOCK(id o = [_arr popLastObject]) return o; } - (void)appendObjects:(NSArray *)objects { LOCK([_arr appendObjects:objects]); } - (void)prependObjects:(NSArray *)objects { LOCK([_arr prependObjects:objects]); } - (void)insertObjects:(NSArray *)objects atIndex:(NSUInteger)index { LOCK([_arr insertObjects:objects atIndex:index]); } - (void)reverse { LOCK([_arr reverse]); } - (void)shuffle { LOCK([_arr shuffle]); } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYThreadSafeArray.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
3,248
```objective-c // // YYTransaction.h // YYKit <path_to_url // // Created by ibireme on 15/4/18. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** YYTransaction let you perform a selector once before current runloop sleep. */ @interface YYTransaction : NSObject /** Creates and returns a transaction with a specified target and selector. @param target A specified target, the target is retained until runloop end. @param selector A selector for target. @return A new transaction, or nil if an error occurs. */ + (YYTransaction *)transactionWithTarget:(id)target selector:(SEL)selector; /** Commit the trancaction to main runloop. @discussion It will perform the selector on the target once before main runloop's current loop sleep. If the same transaction (same target and same selector) has already commit to runloop in this loop, this method do nothing. */ - (void)commit; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYTransaction.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
244
```objective-c // // YYReachability.m // YYKit <path_to_url // // Created by ibireme on 15/2/6. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYReachability.h" #import <objc/message.h> #import <CoreTelephony/CTTelephonyNetworkInfo.h> static YYReachabilityStatus YYReachabilityStatusFromFlags(SCNetworkReachabilityFlags flags, BOOL allowWWAN) { if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { return YYReachabilityStatusNone; } if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) && (flags & kSCNetworkReachabilityFlagsTransientConnection)) { return YYReachabilityStatusNone; } if ((flags & kSCNetworkReachabilityFlagsIsWWAN) && allowWWAN) { return YYReachabilityStatusWWAN; } return YYReachabilityStatusWiFi; } static void YYReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) { YYReachability *self = ((__bridge YYReachability *)info); if (self.notifyBlock) { dispatch_async(dispatch_get_main_queue(), ^{ self.notifyBlock(self); }); } } @interface YYReachability () @property (nonatomic, assign) SCNetworkReachabilityRef ref; @property (nonatomic, assign) BOOL scheduled; @property (nonatomic, assign) BOOL allowWWAN; @property (nonatomic, strong) CTTelephonyNetworkInfo *networkInfo; @end @implementation YYReachability + (dispatch_queue_t)sharedQueue { static dispatch_queue_t queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ queue = dispatch_queue_create("com.ibireme.yykit.reachability", DISPATCH_QUEUE_SERIAL); }); return queue; } - (instancetype)init { /* See Apple's Reachability implementation and readme: The address 0.0.0.0, which reachability treats as a special token that causes it to actually monitor the general routing status of the device, both IPv4 and IPv6. path_to_url#//apple_ref/doc/uid/DTS40007324-ReadMe_md-DontLinkElementID_11 */ struct sockaddr_in zero_addr; bzero(&zero_addr, sizeof(zero_addr)); zero_addr.sin_len = sizeof(zero_addr); zero_addr.sin_family = AF_INET; SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)&zero_addr); return [self initWithRef:ref]; } - (instancetype)initWithRef:(SCNetworkReachabilityRef)ref { if (!ref) return nil; self = super.init; if (!self) return nil; _ref = ref; _allowWWAN = YES; if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_7_0) { _networkInfo = [CTTelephonyNetworkInfo new]; } return self; } - (void)dealloc { self.notifyBlock = nil; self.scheduled = NO; CFRelease(self.ref); } - (void)setScheduled:(BOOL)scheduled { if (_scheduled == scheduled) return; _scheduled = scheduled; if (scheduled) { SCNetworkReachabilityContext context = { 0, (__bridge void *)self, NULL, NULL, NULL }; SCNetworkReachabilitySetCallback(self.ref, YYReachabilityCallback, &context); SCNetworkReachabilitySetDispatchQueue(self.ref, [self.class sharedQueue]); } else { SCNetworkReachabilitySetDispatchQueue(self.ref, NULL); } } - (SCNetworkReachabilityFlags)flags { SCNetworkReachabilityFlags flags = 0; SCNetworkReachabilityGetFlags(self.ref, &flags); return flags; } - (YYReachabilityStatus)status { return YYReachabilityStatusFromFlags(self.flags, self.allowWWAN); } - (YYReachabilityWWANStatus)wwanStatus { if (!self.networkInfo) return YYReachabilityWWANStatusNone; NSString *status = self.networkInfo.currentRadioAccessTechnology; if (!status) return YYReachabilityWWANStatusNone; static NSDictionary *dic; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ dic = @{CTRadioAccessTechnologyGPRS : @(YYReachabilityWWANStatus2G), // 2.5G 171Kbps CTRadioAccessTechnologyEdge : @(YYReachabilityWWANStatus2G), // 2.75G 384Kbps CTRadioAccessTechnologyWCDMA : @(YYReachabilityWWANStatus3G), // 3G 3.6Mbps/384Kbps CTRadioAccessTechnologyHSDPA : @(YYReachabilityWWANStatus3G), // 3.5G 14.4Mbps/384Kbps CTRadioAccessTechnologyHSUPA : @(YYReachabilityWWANStatus3G), // 3.75G 14.4Mbps/5.76Mbps CTRadioAccessTechnologyCDMA1x : @(YYReachabilityWWANStatus3G), // 2.5G CTRadioAccessTechnologyCDMAEVDORev0 : @(YYReachabilityWWANStatus3G), CTRadioAccessTechnologyCDMAEVDORevA : @(YYReachabilityWWANStatus3G), CTRadioAccessTechnologyCDMAEVDORevB : @(YYReachabilityWWANStatus3G), CTRadioAccessTechnologyeHRPD : @(YYReachabilityWWANStatus3G), CTRadioAccessTechnologyLTE : @(YYReachabilityWWANStatus4G)}; // LTE:3.9G 150M/75M LTE-Advanced:4G 300M/150M }); NSNumber *num = dic[status]; if (num) return num.unsignedIntegerValue; else return YYReachabilityWWANStatusNone; } - (BOOL)isReachable { return self.status != YYReachabilityStatusNone; } + (instancetype)reachability { return self.new; } + (instancetype)reachabilityForLocalWifi { struct sockaddr_in localWifiAddress; bzero(&localWifiAddress, sizeof(localWifiAddress)); localWifiAddress.sin_len = sizeof(localWifiAddress); localWifiAddress.sin_family = AF_INET; localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); YYReachability *one = [self reachabilityWithAddress:(const struct sockaddr *)&localWifiAddress]; one.allowWWAN = NO; return one; } + (instancetype)reachabilityWithHostname:(NSString *)hostname { SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(NULL, [hostname UTF8String]); return [[self alloc] initWithRef:ref]; } + (instancetype)reachabilityWithAddress:(const struct sockaddr *)hostAddress { SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)hostAddress); return [[self alloc] initWithRef:ref]; } - (void)setNotifyBlock:(void (^)(YYReachability *reachability))notifyBlock { _notifyBlock = [notifyBlock copy]; self.scheduled = (self.notifyBlock != nil); } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYReachability.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,610
```objective-c // // YYTransaction.m // YYKit <path_to_url // // Created by ibireme on 15/4/18. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTransaction.h" @interface YYTransaction() @property (nonatomic, strong) id target; @property (nonatomic, assign) SEL selector; @end static NSMutableSet *transactionSet = nil; static void YYRunLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) { if (transactionSet.count == 0) return; NSSet *currentSet = transactionSet; transactionSet = [NSMutableSet new]; [currentSet enumerateObjectsUsingBlock:^(YYTransaction *transaction, BOOL *stop) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [transaction.target performSelector:transaction.selector]; #pragma clang diagnostic pop }]; } static void YYTransactionSetup() { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ transactionSet = [NSMutableSet new]; CFRunLoopRef runloop = CFRunLoopGetMain(); CFRunLoopObserverRef observer; observer = CFRunLoopObserverCreate(CFAllocatorGetDefault(), kCFRunLoopBeforeWaiting | kCFRunLoopExit, true, // repeat 0xFFFFFF, // after CATransaction(2000000) YYRunLoopObserverCallBack, NULL); CFRunLoopAddObserver(runloop, observer, kCFRunLoopCommonModes); CFRelease(observer); }); } @implementation YYTransaction + (YYTransaction *)transactionWithTarget:(id)target selector:(SEL)selector{ if (!target || !selector) return nil; YYTransaction *t = [YYTransaction new]; t.target = target; t.selector = selector; return t; } - (void)commit { if (!_target || !_selector) return; YYTransactionSetup(); [transactionSet addObject:self]; } - (NSUInteger)hash { long v1 = (long)((void *)_selector); long v2 = (long)_target; return v1 ^ v2; } - (BOOL)isEqual:(id)object { if (self == object) return YES; if (![object isMemberOfClass:self.class]) return NO; YYTransaction *other = object; return other.selector == _selector && other.target == _target; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYTransaction.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
529
```objective-c // // YYThreadSafeDictionary.m // YYKit <path_to_url // // Created by ibireme on 14/10/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYThreadSafeDictionary.h" #import "NSDictionary+YYAdd.h" #define INIT(...) self = super.init; \ if (!self) return nil; \ __VA_ARGS__; \ if (!_dic) return nil; \ _lock = dispatch_semaphore_create(1); \ return self; #define LOCK(...) dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \ __VA_ARGS__; \ dispatch_semaphore_signal(_lock); @implementation YYThreadSafeDictionary { NSMutableDictionary *_dic; //Subclass a class cluster... dispatch_semaphore_t _lock; } #pragma mark - init - (instancetype)init { INIT(_dic = [[NSMutableDictionary alloc] init]); } - (instancetype)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys { INIT(_dic = [[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys]); } - (instancetype)initWithCapacity:(NSUInteger)capacity { INIT(_dic = [[NSMutableDictionary alloc] initWithCapacity:capacity]); } - (instancetype)initWithObjects:(const id[])objects forKeys:(const id <NSCopying>[])keys count:(NSUInteger)cnt { INIT(_dic = [[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys count:cnt]); } - (instancetype)initWithDictionary:(NSDictionary *)otherDictionary { INIT(_dic = [[NSMutableDictionary alloc] initWithDictionary:otherDictionary]); } - (instancetype)initWithDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL)flag { INIT(_dic = [[NSMutableDictionary alloc] initWithDictionary:otherDictionary copyItems:flag]); } #pragma mark - method - (NSUInteger)count { LOCK(NSUInteger c = _dic.count); return c; } - (id)objectForKey:(id)aKey { LOCK(id o = [_dic objectForKey:aKey]); return o; } - (NSEnumerator *)keyEnumerator { LOCK(NSEnumerator * e = [_dic keyEnumerator]); return e; } - (NSArray *)allKeys { LOCK(NSArray * a = [_dic allKeys]); return a; } - (NSArray *)allKeysForObject:(id)anObject { LOCK(NSArray * a = [_dic allKeysForObject:anObject]); return a; } - (NSArray *)allValues { LOCK(NSArray * a = [_dic allValues]); return a; } - (NSString *)description { LOCK(NSString * d = [_dic description]); return d; } - (NSString *)descriptionInStringsFileFormat { LOCK(NSString * d = [_dic descriptionInStringsFileFormat]); return d; } - (NSString *)descriptionWithLocale:(id)locale { LOCK(NSString * d = [_dic descriptionWithLocale:locale]); return d; } - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level { LOCK(NSString * d = [_dic descriptionWithLocale:locale indent:level]); return d; } - (BOOL)isEqualToDictionary:(NSDictionary *)otherDictionary { if (otherDictionary == self) return YES; if ([otherDictionary isKindOfClass:YYThreadSafeDictionary.class]) { YYThreadSafeDictionary *other = (id)otherDictionary; BOOL isEqual; dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); dispatch_semaphore_wait(other->_lock, DISPATCH_TIME_FOREVER); isEqual = [_dic isEqual:other->_dic]; dispatch_semaphore_signal(other->_lock); dispatch_semaphore_signal(_lock); return isEqual; } return NO; } - (NSEnumerator *)objectEnumerator { LOCK(NSEnumerator * e = [_dic objectEnumerator]); return e; } - (NSArray *)objectsForKeys:(NSArray *)keys notFoundMarker:(id)marker { LOCK(NSArray * a = [_dic objectsForKeys:keys notFoundMarker:marker]); return a; } - (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator { LOCK(NSArray * a = [_dic keysSortedByValueUsingSelector:comparator]); return a; } - (void)getObjects:(id __unsafe_unretained[])objects andKeys:(id __unsafe_unretained[])keys { LOCK([_dic getObjects:objects andKeys:keys]); } - (id)objectForKeyedSubscript:(id)key { LOCK(id o = [_dic objectForKeyedSubscript:key]); return o; } - (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block { LOCK([_dic enumerateKeysAndObjectsUsingBlock:block]); } - (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id key, id obj, BOOL *stop))block { LOCK([_dic enumerateKeysAndObjectsWithOptions:opts usingBlock:block]); } - (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr { LOCK(NSArray * a = [_dic keysSortedByValueUsingComparator:cmptr]); return a; } - (NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr { LOCK(NSArray * a = [_dic keysSortedByValueWithOptions:opts usingComparator:cmptr]); return a; } - (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate { LOCK(NSSet * a = [_dic keysOfEntriesPassingTest:predicate]); return a; } - (NSSet *)keysOfEntriesWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate { LOCK(NSSet * a = [_dic keysOfEntriesWithOptions:opts passingTest:predicate]); return a; } #pragma mark - mutable - (void)removeObjectForKey:(id)aKey { LOCK([_dic removeObjectForKey:aKey]); } - (void)setObject:(id)anObject forKey:(id <NSCopying> )aKey { LOCK([_dic setObject:anObject forKey:aKey]); } - (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary { LOCK([_dic addEntriesFromDictionary:otherDictionary]); } - (void)removeAllObjects { LOCK([_dic removeAllObjects]); } - (void)removeObjectsForKeys:(NSArray *)keyArray { LOCK([_dic removeObjectsForKeys:keyArray]); } - (void)setDictionary:(NSDictionary *)otherDictionary { LOCK([_dic setDictionary:otherDictionary]); } - (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying> )key { LOCK([_dic setObject:obj forKeyedSubscript:key]); } #pragma mark - protocol - (id)copyWithZone:(NSZone *)zone { return [self mutableCopyWithZone:zone]; } - (id)mutableCopyWithZone:(NSZone *)zone { LOCK(id copiedDictionary = [[self.class allocWithZone:zone] initWithDictionary:_dic]); return copiedDictionary; } - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained[])stackbuf count:(NSUInteger)len { LOCK(NSUInteger count = [_dic countByEnumeratingWithState:state objects:stackbuf count:len]); return count; } - (BOOL)isEqual:(id)object { if (object == self) return YES; if ([object isKindOfClass:YYThreadSafeDictionary.class]) { YYThreadSafeDictionary *other = object; BOOL isEqual; dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); dispatch_semaphore_wait(other->_lock, DISPATCH_TIME_FOREVER); isEqual = [_dic isEqual:other->_dic]; dispatch_semaphore_signal(other->_lock); dispatch_semaphore_signal(_lock); return isEqual; } return NO; } - (NSUInteger)hash { LOCK(NSUInteger hash = [_dic hash]); return hash; } #pragma mark - custom methods for NSDictionary(YYAdd) - (NSDictionary *)entriesForKeys:(NSArray *)keys { LOCK(NSDictionary * dic = [_dic entriesForKeys:keys]) return dic; } - (NSString *)jsonStringEncoded { LOCK(NSString * s = [_dic jsonStringEncoded]) return s; } - (NSString *)jsonPrettyStringEncoded { LOCK(NSString * s = [_dic jsonPrettyStringEncoded]) return s; } - (id)popObjectForKey:(id)aKey { LOCK(id o = [_dic popObjectForKey:aKey]) return o; } - (NSDictionary *)popEntriesForKeys:(NSArray *)keys { LOCK(NSDictionary * d = [_dic popEntriesForKeys:keys]) return d; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYThreadSafeDictionary.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,848
```objective-c // // YYKeychain.h // YYKit <path_to_url // // Created by ibireme on 14/10/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> @class YYKeychainItem; NS_ASSUME_NONNULL_BEGIN /** A wrapper for system keychain API. Inspired by [SSKeychain](path_to_url */ @interface YYKeychain : NSObject #pragma mark - Convenience method for keychain ///============================================================================= /// @name Convenience method for keychain ///============================================================================= /** Returns the password for a given account and service, or `nil` if not found or an error occurs. @param serviceName The service for which to return the corresponding password. This value must not be nil. @param account The account for which to return the corresponding password. This value must not be nil. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return Password string, or nil when not found or error occurs. */ + (nullable NSString *)getPasswordForService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error; + (nullable NSString *)getPasswordForService:(NSString *)serviceName account:(NSString *)account; /** Deletes a password from the Keychain. @param serviceName The service for which to return the corresponding password. This value must not be nil. @param account The account for which to return the corresponding password. This value must not be nil. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return Whether succeed. */ + (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error; + (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account; /** Insert or update the password for a given account and service. @param password The new password. @param serviceName The service for which to return the corresponding password. This value must not be nil. @param account The account for which to return the corresponding password. This value must not be nil. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return Whether succeed. */ + (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error; + (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account; #pragma mark - Full query for keychain (SQL-like) ///============================================================================= /// @name Full query for keychain (SQL-like) ///============================================================================= /** Insert an item into keychain. @discussion The service,account,password is required. If there's item exist already, an error occurs and insert fail. @param item The item to insert. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return Whether succeed. */ + (BOOL)insertItem:(YYKeychainItem *)item error:(NSError **)error; + (BOOL)insertItem:(YYKeychainItem *)item; /** Update item in keychain. @discussion The service,account,password is required. If there's no item exist already, an error occurs and insert fail. @param item The item to insert. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return Whether succeed. */ + (BOOL)updateItem:(YYKeychainItem *)item error:(NSError **)error; + (BOOL)updateItem:(YYKeychainItem *)item; /** Delete items from keychain. @discussion The service,account,password is required. If there's item exist already, an error occurs and insert fail. @param item The item to update. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return Whether succeed. */ + (BOOL)deleteItem:(YYKeychainItem *)item error:(NSError **)error; + (BOOL)deleteItem:(YYKeychainItem *)item; /** Find an item from keychain. @discussion The service,account is optinal. It returns only one item if there exist multi. @param item The item for query. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return An item or nil. */ + (nullable YYKeychainItem *)selectOneItem:(YYKeychainItem *)item error:(NSError **)error; + (nullable YYKeychainItem *)selectOneItem:(YYKeychainItem *)item; /** Find all items matches the query. @discussion The service,account is optinal. It returns all item matches by the query. @param item The item for query. @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. See `YYKeychainErrorCode`. @return An array of YYKeychainItem. */ + (nullable NSArray<YYKeychainItem *> *)selectItems:(YYKeychainItem *)item error:(NSError **)error; + (nullable NSArray<YYKeychainItem *> *)selectItems:(YYKeychainItem *)item; @end #pragma mark - Const /** Error code in YYKeychain API. */ typedef NS_ENUM (NSUInteger, YYKeychainErrorCode) { YYKeychainErrorUnimplemented = 1, ///< Function or operation not implemented. YYKeychainErrorIO, ///< I/O error (bummers) YYKeychainErrorOpWr, ///< File already open with with write permission. YYKeychainErrorParam, ///< One or more parameters passed to a function where not valid. YYKeychainErrorAllocate, ///< Failed to allocate memory. YYKeychainErrorUserCancelled, ///< User cancelled the operation. YYKeychainErrorBadReq, ///< Bad parameter or invalid state for operation. YYKeychainErrorInternalComponent, ///< Internal... YYKeychainErrorNotAvailable, ///< No keychain is available. You may need to restart your computer. YYKeychainErrorDuplicateItem, ///< The specified item already exists in the keychain. YYKeychainErrorItemNotFound, ///< The specified item could not be found in the keychain. YYKeychainErrorInteractionNotAllowed, ///< User interaction is not allowed. YYKeychainErrorDecode, ///< Unable to decode the provided data. YYKeychainErrorAuthFailed, ///< The user name or passphrase you entered is not. }; /** When query to return the item's data, the error errSecInteractionNotAllowed will be returned if the item's data is not available until a device unlock occurs. */ typedef NS_ENUM (NSUInteger, YYKeychainAccessible) { YYKeychainAccessibleNone = 0, ///< no value /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will migrate to a new device when using encrypted backups. */ YYKeychainAccessibleWhenUnlocked, /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accesible by background applications. Items with this attribute will migrate to a new device when using encrypted backups.*/ YYKeychainAccessibleAfterFirstUnlock, /** Item data can always be accessed regardless of the lock state of the device. This is not recommended for anything except system use. Items with this attribute will migrate to a new device when using encrypted backups.*/ YYKeychainAccessibleAlways, /** Item data can only be accessed while the device is unlocked. This class is only available if a passcode is set on the device. This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode will cause all items in this class to be deleted.*/ YYKeychainAccessibleWhenPasscodeSetThisDeviceOnly, /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. */ YYKeychainAccessibleWhenUnlockedThisDeviceOnly, /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accessible by background applications. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device these items will be missing.*/ YYKeychainAccessibleAfterFirstUnlockThisDeviceOnly, /** Item data can always be accessed regardless of the lock state of the device. This option is not recommended for anything except system use. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing.*/ YYKeychainAccessibleAlwaysThisDeviceOnly, }; /** Whether the item in question can be synchronized. */ typedef NS_ENUM (NSUInteger, YYKeychainQuerySynchronizationMode) { /** Default, Don't care for synchronization */ YYKeychainQuerySynchronizationModeAny = 0, /** Is not synchronized */ YYKeychainQuerySynchronizationModeNo, /** To add a new item which can be synced to other devices, or to obtain synchronized results from a query*/ YYKeychainQuerySynchronizationModeYes, } NS_AVAILABLE_IOS (7_0); #pragma mark - Item /** Wrapper for keychain item/query. */ @interface YYKeychainItem : NSObject <NSCopying> @property (nullable, nonatomic, copy) NSString *service; ///< kSecAttrService @property (nullable, nonatomic, copy) NSString *account; ///< kSecAttrAccount @property (nullable, nonatomic, copy) NSData *passwordData; ///< kSecValueData @property (nullable, nonatomic, copy) NSString *password; ///< shortcut for `passwordData` @property (nullable, nonatomic, copy) id <NSCoding> passwordObject; ///< shortcut for `passwordData` @property (nullable, nonatomic, copy) NSString *label; ///< kSecAttrLabel @property (nullable, nonatomic, copy) NSNumber *type; ///< kSecAttrType (FourCC) @property (nullable, nonatomic, copy) NSNumber *creater; ///< kSecAttrCreator (FourCC) @property (nullable, nonatomic, copy) NSString *comment; ///< kSecAttrComment @property (nullable, nonatomic, copy) NSString *descr; ///< kSecAttrDescription @property (nullable, nonatomic, readonly, strong) NSDate *modificationDate; ///< kSecAttrModificationDate @property (nullable, nonatomic, readonly, strong) NSDate *creationDate; ///< kSecAttrCreationDate @property (nullable, nonatomic, copy) NSString *accessGroup; ///< kSecAttrAccessGroup @property (nonatomic) YYKeychainAccessible accessible; ///< kSecAttrAccessible @property (nonatomic) YYKeychainQuerySynchronizationMode synchronizable NS_AVAILABLE_IOS(7_0); ///< kSecAttrSynchronizable @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYKeychain.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,769
```objective-c // // YYTimer.m // YYKit <path_to_url // // Created by ibireme on 15/2/7. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTimer.h" #import <pthread.h> #define LOCK(...) dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \ __VA_ARGS__; \ dispatch_semaphore_signal(_lock); @implementation YYTimer { BOOL _valid; NSTimeInterval _timeInterval; BOOL _repeats; __weak id _target; SEL _selector; dispatch_source_t _source; dispatch_semaphore_t _lock; } + (YYTimer *)timerWithTimeInterval:(NSTimeInterval)interval target:(id)target selector:(SEL)selector repeats:(BOOL)repeats { return [[self alloc] initWithFireTime:interval interval:interval target:target selector:selector repeats:repeats]; } - (instancetype)init { @throw [NSException exceptionWithName:@"YYTimer init error" reason:@"Use the designated initializer to init." userInfo:nil]; return [self initWithFireTime:0 interval:0 target:self selector:@selector(invalidate) repeats:NO]; } - (instancetype)initWithFireTime:(NSTimeInterval)start interval:(NSTimeInterval)interval target:(id)target selector:(SEL)selector repeats:(BOOL)repeats { self = [super init]; _repeats = repeats; _timeInterval = interval; _valid = YES; _target = target; _selector = selector; __weak typeof(self) _self = self; _lock = dispatch_semaphore_create(1); _source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); dispatch_source_set_timer(_source, dispatch_time(DISPATCH_TIME_NOW, (start * NSEC_PER_SEC)), (interval * NSEC_PER_SEC), 0); dispatch_source_set_event_handler(_source, ^{[_self fire];}); dispatch_resume(_source); return self; } - (void)invalidate { dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); if (_valid) { dispatch_source_cancel(_source); _source = NULL; _target = nil; _valid = NO; } dispatch_semaphore_signal(_lock); } - (void)fire { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); id target = _target; if (!_repeats || !target) { dispatch_semaphore_signal(_lock); [self invalidate]; } else { dispatch_semaphore_signal(_lock); [target performSelector:_selector withObject:self]; } #pragma clang diagnostic pop } - (BOOL)repeats { LOCK(BOOL repeat = _repeats); return repeat; } - (NSTimeInterval)timeInterval { LOCK(NSTimeInterval t = _timeInterval) return t; } - (BOOL)isValid { LOCK(BOOL valid = _valid) return valid; } - (void)dealloc { [self invalidate]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYTimer.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
683
```objective-c // // YYGestureRecognizer.m // YYKit <path_to_url // // Created by ibireme on 14/10/26. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYGestureRecognizer.h" #import <UIKit/UIGestureRecognizerSubclass.h> @implementation YYGestureRecognizer - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { self.state = UIGestureRecognizerStateBegan; _startPoint = [(UITouch *)[touches anyObject] locationInView:self.view]; _lastPoint = _currentPoint; _currentPoint = _startPoint; if (_action) _action(self, YYGestureRecognizerStateBegan); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = (UITouch *)[touches anyObject]; CGPoint currentPoint = [touch locationInView:self.view]; self.state = UIGestureRecognizerStateChanged; _currentPoint = currentPoint; if (_action) _action(self, YYGestureRecognizerStateMoved); _lastPoint = _currentPoint; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { self.state = UIGestureRecognizerStateEnded; if (_action) _action(self, YYGestureRecognizerStateEnded); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { self.state = UIGestureRecognizerStateCancelled; if (_action) _action(self, YYGestureRecognizerStateCancelled); } - (void)reset { self.state = UIGestureRecognizerStatePossible; } - (void)cancel { if (self.state == UIGestureRecognizerStateBegan || self.state == UIGestureRecognizerStateChanged) { self.state = UIGestureRecognizerStateCancelled; if (_action) _action(self, YYGestureRecognizerStateCancelled); } } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYGestureRecognizer.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
399
```objective-c // // YYKeychain.m // YYKit <path_to_url // // Created by ibireme on 14/10/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYKeychain.h" #import "UIDevice+YYAdd.h" #import "YYKitMacro.h" #import <Security/Security.h> static YYKeychainErrorCode YYKeychainErrorCodeFromOSStatus(OSStatus status) { switch (status) { case errSecUnimplemented: return YYKeychainErrorUnimplemented; case errSecIO: return YYKeychainErrorIO; case errSecOpWr: return YYKeychainErrorOpWr; case errSecParam: return YYKeychainErrorParam; case errSecAllocate: return YYKeychainErrorAllocate; case errSecUserCanceled: return YYKeychainErrorUserCancelled; case errSecBadReq: return YYKeychainErrorBadReq; case errSecInternalComponent: return YYKeychainErrorInternalComponent; case errSecNotAvailable: return YYKeychainErrorNotAvailable; case errSecDuplicateItem: return YYKeychainErrorDuplicateItem; case errSecItemNotFound: return YYKeychainErrorItemNotFound; case errSecInteractionNotAllowed: return YYKeychainErrorInteractionNotAllowed; case errSecDecode: return YYKeychainErrorDecode; case errSecAuthFailed: return YYKeychainErrorAuthFailed; default: return 0; } } static NSString *YYKeychainErrorDesc(YYKeychainErrorCode code) { switch (code) { case YYKeychainErrorUnimplemented: return @"Function or operation not implemented."; case YYKeychainErrorIO: return @"I/O error (bummers)"; case YYKeychainErrorOpWr: return @"ile already open with with write permission."; case YYKeychainErrorParam: return @"One or more parameters passed to a function where not valid."; case YYKeychainErrorAllocate: return @"Failed to allocate memory."; case YYKeychainErrorUserCancelled: return @"User canceled the operation."; case YYKeychainErrorBadReq: return @"Bad parameter or invalid state for operation."; case YYKeychainErrorInternalComponent: return @"Inrernal Component"; case YYKeychainErrorNotAvailable: return @"No keychain is available. You may need to restart your computer."; case YYKeychainErrorDuplicateItem: return @"The specified item already exists in the keychain."; case YYKeychainErrorItemNotFound: return @"The specified item could not be found in the keychain."; case YYKeychainErrorInteractionNotAllowed: return @"User interaction is not allowed."; case YYKeychainErrorDecode: return @"Unable to decode the provided data."; case YYKeychainErrorAuthFailed: return @"The user name or passphrase you entered is not"; default: break; } return nil; } static NSString *YYKeychainAccessibleStr(YYKeychainAccessible e) { switch (e) { case YYKeychainAccessibleWhenUnlocked: return (__bridge NSString *)(kSecAttrAccessibleWhenUnlocked); case YYKeychainAccessibleAfterFirstUnlock: return (__bridge NSString *)(kSecAttrAccessibleAfterFirstUnlock); case YYKeychainAccessibleAlways: return (__bridge NSString *)(kSecAttrAccessibleAlways); case YYKeychainAccessibleWhenPasscodeSetThisDeviceOnly: return (__bridge NSString *)(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly); case YYKeychainAccessibleWhenUnlockedThisDeviceOnly: return (__bridge NSString *)(kSecAttrAccessibleWhenUnlockedThisDeviceOnly); case YYKeychainAccessibleAfterFirstUnlockThisDeviceOnly: return (__bridge NSString *)(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly); case YYKeychainAccessibleAlwaysThisDeviceOnly: return (__bridge NSString *)(kSecAttrAccessibleAlwaysThisDeviceOnly); default: return nil; } } static YYKeychainAccessible YYKeychainAccessibleEnum(NSString *s) { if ([s isEqualToString:(__bridge NSString *)kSecAttrAccessibleWhenUnlocked]) return YYKeychainAccessibleWhenUnlocked; if ([s isEqualToString:(__bridge NSString *)kSecAttrAccessibleAfterFirstUnlock]) return YYKeychainAccessibleAfterFirstUnlock; if ([s isEqualToString:(__bridge NSString *)kSecAttrAccessibleAlways]) return YYKeychainAccessibleAlways; if ([s isEqualToString:(__bridge NSString *)kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly]) return YYKeychainAccessibleWhenPasscodeSetThisDeviceOnly; if ([s isEqualToString:(__bridge NSString *)kSecAttrAccessibleWhenUnlockedThisDeviceOnly]) return YYKeychainAccessibleWhenUnlockedThisDeviceOnly; if ([s isEqualToString:(__bridge NSString *)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]) return YYKeychainAccessibleAfterFirstUnlockThisDeviceOnly; if ([s isEqualToString:(__bridge NSString *)kSecAttrAccessibleAlwaysThisDeviceOnly]) return YYKeychainAccessibleAlwaysThisDeviceOnly; return YYKeychainAccessibleNone; } static id YYKeychainQuerySynchonizationID(YYKeychainQuerySynchronizationMode mode) { switch (mode) { case YYKeychainQuerySynchronizationModeAny: return (__bridge id)(kSecAttrSynchronizableAny); case YYKeychainQuerySynchronizationModeNo: return (__bridge id)kCFBooleanFalse; case YYKeychainQuerySynchronizationModeYes: return (__bridge id)kCFBooleanTrue; default: return (__bridge id)(kSecAttrSynchronizableAny); } } static YYKeychainQuerySynchronizationMode YYKeychainQuerySynchonizationEnum(NSNumber *num) { if ([num isEqualToNumber:@NO]) return YYKeychainQuerySynchronizationModeNo; if ([num isEqualToNumber:@YES]) return YYKeychainQuerySynchronizationModeYes; return YYKeychainQuerySynchronizationModeAny; } @interface YYKeychainItem () @property (nonatomic, readwrite, strong) NSDate *modificationDate; @property (nonatomic, readwrite, strong) NSDate *creationDate; @end @implementation YYKeychainItem - (void)setPasswordObject:(id <NSCoding> )object { self.passwordData = [NSKeyedArchiver archivedDataWithRootObject:object]; } - (id <NSCoding> )passwordObject { if ([self.passwordData length]) { return [NSKeyedUnarchiver unarchiveObjectWithData:self.passwordData]; } return nil; } - (void)setPassword:(NSString *)password { self.passwordData = [password dataUsingEncoding:NSUTF8StringEncoding]; } - (NSString *)password { if ([self.passwordData length]) { return [[NSString alloc] initWithData:self.passwordData encoding:NSUTF8StringEncoding]; } return nil; } - (NSMutableDictionary *)queryDic { NSMutableDictionary *dic = [NSMutableDictionary new]; dic[(__bridge id)kSecClass] = (__bridge id)kSecClassGenericPassword; if (self.account) dic[(__bridge id)kSecAttrAccount] = self.account; if (self.service) dic[(__bridge id)kSecAttrService] = self.service; if (![UIDevice currentDevice].isSimulator) { // Remove the access group if running on the iPhone simulator. // // Apps that are built for the simulator aren't signed, so there's no keychain access group // for the simulator to check. This means that all apps can see all keychain items when run // on the simulator. // // If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the // simulator will return -25243 (errSecNoAccessForItem). // // The access group attribute will be included in items returned by SecItemCopyMatching, // which is why we need to remove it before updating the item. if (self.accessGroup) dic[(__bridge id)kSecAttrAccessGroup] = self.accessGroup; } if (kiOS7Later) { dic[(__bridge id)kSecAttrSynchronizable] = YYKeychainQuerySynchonizationID(self.synchronizable); } return dic; } - (NSMutableDictionary *)dic { NSMutableDictionary *dic = [NSMutableDictionary new]; dic[(__bridge id)kSecClass] = (__bridge id)kSecClassGenericPassword; if (self.account) dic[(__bridge id)kSecAttrAccount] = self.account; if (self.service) dic[(__bridge id)kSecAttrService] = self.service; if (self.label) dic[(__bridge id)kSecAttrLabel] = self.label; if (![UIDevice currentDevice].isSimulator) { // Remove the access group if running on the iPhone simulator. // // Apps that are built for the simulator aren't signed, so there's no keychain access group // for the simulator to check. This means that all apps can see all keychain items when run // on the simulator. // // If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the // simulator will return -25243 (errSecNoAccessForItem). // // The access group attribute will be included in items returned by SecItemCopyMatching, // which is why we need to remove it before updating the item. if (self.accessGroup) dic[(__bridge id)kSecAttrAccessGroup] = self.accessGroup; } if (kiOS7Later) { dic[(__bridge id)kSecAttrSynchronizable] = YYKeychainQuerySynchonizationID(self.synchronizable); } if (self.accessible) dic[(__bridge id)kSecAttrAccessible] = YYKeychainAccessibleStr(self.accessible); if (self.passwordData) dic[(__bridge id)kSecValueData] = self.passwordData; if (self.type) dic[(__bridge id)kSecAttrType] = self.type; if (self.creater) dic[(__bridge id)kSecAttrCreator] = self.creater; if (self.comment) dic[(__bridge id)kSecAttrComment] = self.comment; if (self.descr) dic[(__bridge id)kSecAttrDescription] = self.descr; return dic; } - (instancetype)initWithDic:(NSDictionary *)dic { if (dic.count == 0) return nil; self = self.init; self.service = dic[(__bridge id)kSecAttrService]; self.account = dic[(__bridge id)kSecAttrAccount]; self.passwordData = dic[(__bridge id)kSecValueData]; self.label = dic[(__bridge id)kSecAttrLabel]; self.type = dic[(__bridge id)kSecAttrType]; self.creater = dic[(__bridge id)kSecAttrCreator]; self.comment = dic[(__bridge id)kSecAttrComment]; self.descr = dic[(__bridge id)kSecAttrDescription]; self.modificationDate = dic[(__bridge id)kSecAttrModificationDate]; self.creationDate = dic[(__bridge id)kSecAttrCreationDate]; self.accessGroup = dic[(__bridge id)kSecAttrAccessGroup]; self.accessible = YYKeychainAccessibleEnum(dic[(__bridge id)kSecAttrAccessible]); self.synchronizable = YYKeychainQuerySynchonizationEnum(dic[(__bridge id)kSecAttrSynchronizable]); return self; } - (id)copyWithZone:(NSZone *)zone { YYKeychainItem *item = [YYKeychainItem new]; item.service = self.service; item.account = self.account; item.passwordData = self.passwordData; item.label = self.label; item.type = self.type; item.creater = self.creater; item.comment = self.comment; item.descr = self.descr; item.modificationDate = self.modificationDate; item.creationDate = self.creationDate; item.accessGroup = self.accessGroup; item.accessible = self.accessible; item.synchronizable = self.synchronizable; return item; } - (NSString *)description { NSMutableString *str = @"".mutableCopy; [str appendString:@"YYKeychainItem:{\n"]; if (self.service) [str appendFormat:@" service:%@,\n", self.service]; if (self.account) [str appendFormat:@" service:%@,\n", self.account]; if (self.password) [str appendFormat:@" service:%@,\n", self.password]; if (self.label) [str appendFormat:@" service:%@,\n", self.label]; if (self.type) [str appendFormat:@" service:%@,\n", self.type]; if (self.creater) [str appendFormat:@" service:%@,\n", self.creater]; if (self.comment) [str appendFormat:@" service:%@,\n", self.comment]; if (self.descr) [str appendFormat:@" service:%@,\n", self.descr]; if (self.modificationDate) [str appendFormat:@" service:%@,\n", self.modificationDate]; if (self.creationDate) [str appendFormat:@" service:%@,\n", self.creationDate]; if (self.accessGroup) [str appendFormat:@" service:%@,\n", self.accessGroup]; [str appendString:@"}"]; return str; } @end @implementation YYKeychain + (NSString *)getPasswordForService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error { if (!serviceName || !account) { if (error) *error = [YYKeychain errorWithCode:errSecParam]; return nil; } YYKeychainItem *item = [YYKeychainItem new]; item.service = serviceName; item.account = account; YYKeychainItem *result = [self selectOneItem:item error:error]; return result.password; } + (nullable NSString *)getPasswordForService:(NSString *)serviceName account:(NSString *)account { return [self getPasswordForService:serviceName account:account error:NULL]; } + (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error { if (!serviceName || !account) { if (error) *error = [YYKeychain errorWithCode:errSecParam]; return NO; } YYKeychainItem *item = [YYKeychainItem new]; item.service = serviceName; item.account = account; return [self deleteItem:item error:error]; } + (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account { return [self deletePasswordForService:serviceName account:account error:NULL]; } + (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error { if (!password || !serviceName || !account) { if (error) *error = [YYKeychain errorWithCode:errSecParam]; return NO; } YYKeychainItem *item = [YYKeychainItem new]; item.service = serviceName; item.account = account; YYKeychainItem *result = [self selectOneItem:item error:NULL]; if (result) { result.password = password; return [self updateItem:result error:error]; } else { item.password = password; return [self insertItem:item error:error]; } } + (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account { return [self setPassword:password forService:serviceName account:account error:NULL]; } + (BOOL)insertItem:(YYKeychainItem *)item error:(NSError **)error { if (!item.service || !item.account || !item.passwordData) { if (error) *error = [YYKeychain errorWithCode:errSecParam]; return NO; } NSMutableDictionary *query = [item dic]; OSStatus status = status = SecItemAdd((__bridge CFDictionaryRef)query, NULL); if (status != errSecSuccess) { if (error) *error = [YYKeychain errorWithCode:status]; return NO; } return YES; } + (BOOL)insertItem:(YYKeychainItem *)item { return [self insertItem:item error:NULL]; } + (BOOL)updateItem:(YYKeychainItem *)item error:(NSError **)error { if (!item.service || !item.account || !item.passwordData) { if (error) *error = [YYKeychain errorWithCode:errSecParam]; return NO; } NSMutableDictionary *query = [item queryDic]; NSMutableDictionary *update = [item dic]; [update removeObjectForKey:(__bridge id)kSecClass]; if (!query || !update) return NO; OSStatus status = status = SecItemUpdate((__bridge CFDictionaryRef)query, (__bridge CFDictionaryRef)update); if (status != errSecSuccess) { if (error) *error = [YYKeychain errorWithCode:status]; return NO; } return YES; } + (BOOL)updateItem:(YYKeychainItem *)item { return [self updateItem:item error:NULL]; } + (BOOL)deleteItem:(YYKeychainItem *)item error:(NSError **)error { if (!item.service || !item.account) { if (error) *error = [YYKeychain errorWithCode:errSecParam]; return NO; } NSMutableDictionary *query = [item dic]; OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query); if (status != errSecSuccess) { if (error) *error = [YYKeychain errorWithCode:status]; return NO; } return YES; } + (BOOL)deleteItem:(YYKeychainItem *)item { return [self deleteItem:item error:NULL]; } + (YYKeychainItem *)selectOneItem:(YYKeychainItem *)item error:(NSError **)error { if (!item.service || !item.account) { if (error) *error = [YYKeychain errorWithCode:errSecParam]; return nil; } NSMutableDictionary *query = [item dic]; query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne; query[(__bridge id)kSecReturnAttributes] = @YES; query[(__bridge id)kSecReturnData] = @YES; OSStatus status; CFTypeRef result = NULL; status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); if (status != errSecSuccess) { if (error) *error = [[self class] errorWithCode:status]; return nil; } if (!result) return nil; NSDictionary *dic = nil; if (CFGetTypeID(result) == CFDictionaryGetTypeID()) { dic = (__bridge NSDictionary *)(result); } else if (CFGetTypeID(result) == CFArrayGetTypeID()){ dic = [(__bridge NSArray *)(result) firstObject]; if (![dic isKindOfClass:[NSDictionary class]]) dic = nil; } if (!dic.count) return nil; return [[YYKeychainItem alloc] initWithDic:dic]; } + (YYKeychainItem *)selectOneItem:(YYKeychainItem *)item { return [self selectOneItem:item error:NULL]; } + (NSArray *)selectItems:(YYKeychainItem *)item error:(NSError **)error { NSMutableDictionary *query = [item dic]; query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitAll; query[(__bridge id)kSecReturnAttributes] = @YES; query[(__bridge id)kSecReturnData] = @YES; OSStatus status; CFTypeRef result = NULL; status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); if (status != errSecSuccess && error != NULL) { *error = [[self class] errorWithCode:status]; return nil; } NSMutableArray *res = [NSMutableArray new]; NSDictionary *dic = nil; if (CFGetTypeID(result) == CFDictionaryGetTypeID()) { dic = (__bridge NSDictionary *)(result); YYKeychainItem *item = [[YYKeychainItem alloc] initWithDic:dic]; if (item) [res addObject:item]; } else if (CFGetTypeID(result) == CFArrayGetTypeID()){ for (NSDictionary *dic in (__bridge NSArray *)(result)) { YYKeychainItem *item = [[YYKeychainItem alloc] initWithDic:dic]; if (item) [res addObject:item]; } } return res; } + (NSArray *)selectItems:(YYKeychainItem *)item { return [self selectItems:item error:NULL]; } + (NSError *)errorWithCode:(OSStatus)osCode { YYKeychainErrorCode code = YYKeychainErrorCodeFromOSStatus(osCode); NSString *desc = YYKeychainErrorDesc(code); NSDictionary *userInfo = desc ? @{ NSLocalizedDescriptionKey : desc } : nil; return [NSError errorWithDomain:@"com.ibireme.yykit.keychain" code:code userInfo:userInfo]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYKeychain.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
4,678
```objective-c // // YYAsyncLayer.h // YYKit <path_to_url // // Created by ibireme on 15/4/11. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> @class YYAsyncLayerDisplayTask; NS_ASSUME_NONNULL_BEGIN /** The YYAsyncLayer class is a subclass of CALayer used for render contents asynchronously. @discussion When the layer need update it's contents, it will ask the delegate for a async display task to render the contents in a background queue. */ @interface YYAsyncLayer : CALayer /// Whether the render code is executed in background. Default is YES. @property BOOL displaysAsynchronously; @end /** The YYAsyncLayer's delegate protocol. The delegate of the YYAsyncLayer (typically a UIView) must implements the method in this protocol. */ @protocol YYAsyncLayerDelegate <NSObject> @required /// This method is called to return a new display task when the layer's contents need update. - (YYAsyncLayerDisplayTask *)newAsyncDisplayTask; @end /** A display task used by YYAsyncLayer to render the contents in background queue. */ @interface YYAsyncLayerDisplayTask : NSObject /** This block will be called before the asynchronous drawing begins. It will be called on the main thread. @param layer The layer. */ @property (nullable, nonatomic, copy) void (^willDisplay)(CALayer *layer); /** This block is called to draw the layer's contents. @discussion This block may be called on main thread or background thread, so is should be thread-safe. @param context A new bitmap content created by layer. @param size The content size (typically same as layer's bound size). @param isCancelled If this block returns `YES`, the method should cancel the drawing process and return as quickly as possible. */ @property (nullable, nonatomic, copy) void (^display)(CGContextRef context, CGSize size, BOOL(^isCancelled)(void)); /** This block will be called after the asynchronous drawing finished. It will be called on the main thread. @param layer The layer. @param finished If the draw process is cancelled, it's `NO`, otherwise it's `YES`; */ @property (nullable, nonatomic, copy) void (^didDisplay)(CALayer *layer, BOOL finished); @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYAsyncLayer.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
523
```objective-c // // YYDispatchQueueManager.h // YYKit <path_to_url // // Created by ibireme on 15/7/18. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> #ifndef YYDispatchQueuePool_h #define YYDispatchQueuePool_h NS_ASSUME_NONNULL_BEGIN /** A dispatch queue pool holds multiple serial queues. Use this class to control queue's thread count (instead of concurrent queue). */ @interface YYDispatchQueuePool : NSObject - (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)new UNAVAILABLE_ATTRIBUTE; /** Creates and returns a dispatch queue pool. @param name The name of the pool. @param queueCount Maxmium queue count, should in range (1, 32). @param qos Queue quality of service (QOS). @return A new pool, or nil if an error occurs. */ - (instancetype)initWithName:(nullable NSString *)name queueCount:(NSUInteger)queueCount qos:(NSQualityOfService)qos; /// Pool's name. @property (nullable, nonatomic, readonly) NSString *name; /// Get a serial queue from pool. - (dispatch_queue_t)queue; + (instancetype)defaultPoolForQOS:(NSQualityOfService)qos; @end /// Get a serial queue from global queue pool with a specified qos. extern dispatch_queue_t YYDispatchQueueGetForQOS(NSQualityOfService qos); NS_ASSUME_NONNULL_END #endif ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYDispatchQueuePool.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
321
```objective-c // // YYThreadSafeArray.h // YYKit <path_to_url // // Created by ibireme on 14/10/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> /** A simple implementation of thread safe mutable array. @discussion Generally, access performance is lower than NSMutableArray, but higher than using @synchronized, NSLock, or pthread_mutex_t. @discussion It's also compatible with the custom methods in `NSArray(YYAdd)` and `NSMutableArray(YYAdd)` @warning Fast enumerate(for..in) and enumerator is not thread safe, use enumerate using block instead. When enumerate or sort with block/callback, do *NOT* send message to the array inside the block/callback. */ @interface YYThreadSafeArray : NSMutableArray @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYThreadSafeArray.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
191
```objective-c // // YYWeakProxy.m // YYKit <path_to_url // // Created by ibireme on 14/10/18. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYWeakProxy.h" @implementation YYWeakProxy - (instancetype)initWithTarget:(id)target { _target = target; return self; } + (instancetype)proxyWithTarget:(id)target { return [[YYWeakProxy alloc] initWithTarget:target]; } - (id)forwardingTargetForSelector:(SEL)selector { return _target; } - (void)forwardInvocation:(NSInvocation *)invocation { void *null = NULL; [invocation setReturnValue:&null]; } - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { return [NSObject instanceMethodSignatureForSelector:@selector(init)]; } - (BOOL)respondsToSelector:(SEL)aSelector { return [_target respondsToSelector:aSelector]; } - (BOOL)isEqual:(id)object { return [_target isEqual:object]; } - (NSUInteger)hash { return [_target hash]; } - (Class)superclass { return [_target superclass]; } - (Class)class { return [_target class]; } - (BOOL)isKindOfClass:(Class)aClass { return [_target isKindOfClass:aClass]; } - (BOOL)isMemberOfClass:(Class)aClass { return [_target isMemberOfClass:aClass]; } - (BOOL)conformsToProtocol:(Protocol *)aProtocol { return [_target conformsToProtocol:aProtocol]; } - (BOOL)isProxy { return YES; } - (NSString *)description { return [_target description]; } - (NSString *)debugDescription { return [_target debugDescription]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYWeakProxy.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
392
```objective-c // // YYDispatchQueueManager.m // YYKit <path_to_url // // Created by ibireme on 15/7/18. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYDispatchQueuePool.h" #import <UIKit/UIKit.h> #import <libkern/OSAtomic.h> #define MAX_QUEUE_COUNT 32 static inline dispatch_queue_priority_t NSQualityOfServiceToDispatchPriority(NSQualityOfService qos) { switch (qos) { case NSQualityOfServiceUserInteractive: return DISPATCH_QUEUE_PRIORITY_HIGH; case NSQualityOfServiceUserInitiated: return DISPATCH_QUEUE_PRIORITY_HIGH; case NSQualityOfServiceUtility: return DISPATCH_QUEUE_PRIORITY_LOW; case NSQualityOfServiceBackground: return DISPATCH_QUEUE_PRIORITY_BACKGROUND; case NSQualityOfServiceDefault: return DISPATCH_QUEUE_PRIORITY_DEFAULT; default: return DISPATCH_QUEUE_PRIORITY_DEFAULT; } } static inline qos_class_t NSQualityOfServiceToQOSClass(NSQualityOfService qos) { switch (qos) { case NSQualityOfServiceUserInteractive: return QOS_CLASS_USER_INTERACTIVE; case NSQualityOfServiceUserInitiated: return QOS_CLASS_USER_INITIATED; case NSQualityOfServiceUtility: return QOS_CLASS_UTILITY; case NSQualityOfServiceBackground: return QOS_CLASS_BACKGROUND; case NSQualityOfServiceDefault: return QOS_CLASS_DEFAULT; default: return QOS_CLASS_UNSPECIFIED; } } typedef struct { const char *name; void **queues; uint32_t queueCount; int32_t counter; } YYDispatchContext; static YYDispatchContext *YYDispatchContextCreate(const char *name, uint32_t queueCount, NSQualityOfService qos) { YYDispatchContext *context = calloc(1, sizeof(YYDispatchContext)); if (!context) return NULL; context->queues = calloc(queueCount, sizeof(void *)); if (!context->queues) { free(context); return NULL; } if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) { dispatch_qos_class_t qosClass = NSQualityOfServiceToQOSClass(qos); for (NSUInteger i = 0; i < queueCount; i++) { dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qosClass, 0); dispatch_queue_t queue = dispatch_queue_create(name, attr); context->queues[i] = (__bridge_retained void *)(queue); } } else { long identifier = NSQualityOfServiceToDispatchPriority(qos); for (NSUInteger i = 0; i < queueCount; i++) { dispatch_queue_t queue = dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL); dispatch_set_target_queue(queue, dispatch_get_global_queue(identifier, 0)); context->queues[i] = (__bridge_retained void *)(queue); } } context->queueCount = queueCount; if (name) { context->name = strdup(name); } return context; } static void YYDispatchContextRelease(YYDispatchContext *context) { if (!context) return; if (context->queues) { for (NSUInteger i = 0; i < context->queueCount; i++) { void *queuePointer = context->queues[i]; dispatch_queue_t queue = (__bridge_transfer dispatch_queue_t)(queuePointer); const char *name = dispatch_queue_get_label(queue); if (name) strlen(name); // avoid compiler warning queue = nil; } free(context->queues); context->queues = NULL; } if (context->name) free((void *)context->name); } static dispatch_queue_t YYDispatchContextGetQueue(YYDispatchContext *context) { uint32_t counter = (uint32_t)OSAtomicIncrement32(&context->counter); void *queue = context->queues[counter % context->queueCount]; return (__bridge dispatch_queue_t)(queue); } static YYDispatchContext *YYDispatchContextGetForQOS(NSQualityOfService qos) { static YYDispatchContext *context[5] = {0}; switch (qos) { case NSQualityOfServiceUserInteractive: { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ int count = (int)[NSProcessInfo processInfo].activeProcessorCount; count = count < 1 ? 1 : count > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : count; context[0] = YYDispatchContextCreate("com.ibireme.yykit.user-interactive", count, qos); }); return context[0]; } break; case NSQualityOfServiceUserInitiated: { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ int count = (int)[NSProcessInfo processInfo].activeProcessorCount; count = count < 1 ? 1 : count > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : count; context[1] = YYDispatchContextCreate("com.ibireme.yykit.user-initiated", count, qos); }); return context[1]; } break; case NSQualityOfServiceUtility: { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ int count = (int)[NSProcessInfo processInfo].activeProcessorCount; count = count < 1 ? 1 : count > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : count; context[2] = YYDispatchContextCreate("com.ibireme.yykit.utility", count, qos); }); return context[2]; } break; case NSQualityOfServiceBackground: { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ int count = (int)[NSProcessInfo processInfo].activeProcessorCount; count = count < 1 ? 1 : count > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : count; context[3] = YYDispatchContextCreate("com.ibireme.yykit.background", count, qos); }); return context[3]; } break; case NSQualityOfServiceDefault: default: { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ int count = (int)[NSProcessInfo processInfo].activeProcessorCount; count = count < 1 ? 1 : count > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : count; context[4] = YYDispatchContextCreate("com.ibireme.yykit.default", count, qos); }); return context[4]; } break; } } @implementation YYDispatchQueuePool { @public YYDispatchContext *_context; } - (void)dealloc { if (_context) { YYDispatchContextRelease(_context); _context = NULL; } } - (instancetype)initWithContext:(YYDispatchContext *)context { self = [super init]; if (!context) return nil; self->_context = context; _name = context->name ? [NSString stringWithUTF8String:context->name] : nil; return self; } - (instancetype)initWithName:(NSString *)name queueCount:(NSUInteger)queueCount qos:(NSQualityOfService)qos { if (queueCount == 0 || queueCount > MAX_QUEUE_COUNT) return nil; self = [super init]; _context = YYDispatchContextCreate(name.UTF8String, (uint32_t)queueCount, qos); if (!_context) return nil; _name = name; return self; } - (dispatch_queue_t)queue { return YYDispatchContextGetQueue(_context); } + (instancetype)defaultPoolForQOS:(NSQualityOfService)qos { switch (qos) { case NSQualityOfServiceUserInteractive: { static YYDispatchQueuePool *pool; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ pool = [[YYDispatchQueuePool alloc] initWithContext:YYDispatchContextGetForQOS(qos)]; }); return pool; } break; case NSQualityOfServiceUserInitiated: { static YYDispatchQueuePool *pool; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ pool = [[YYDispatchQueuePool alloc] initWithContext:YYDispatchContextGetForQOS(qos)]; }); return pool; } break; case NSQualityOfServiceUtility: { static YYDispatchQueuePool *pool; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ pool = [[YYDispatchQueuePool alloc] initWithContext:YYDispatchContextGetForQOS(qos)]; }); return pool; } break; case NSQualityOfServiceBackground: { static YYDispatchQueuePool *pool; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ pool = [[YYDispatchQueuePool alloc] initWithContext:YYDispatchContextGetForQOS(qos)]; }); return pool; } break; case NSQualityOfServiceDefault: default: { static YYDispatchQueuePool *pool; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ pool = [[YYDispatchQueuePool alloc] initWithContext:YYDispatchContextGetForQOS(NSQualityOfServiceDefault)]; }); return pool; } break; } } @end dispatch_queue_t YYDispatchQueueGetForQOS(NSQualityOfService qos) { return YYDispatchContextGetQueue(YYDispatchContextGetForQOS(qos)); } ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYDispatchQueuePool.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,055
```objective-c // // YYFileHash.m // YYKit <path_to_url // // Created by ibireme on 14/11/2. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYFileHash.h" #include <CommonCrypto/CommonCrypto.h> #include <zlib.h> #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR #define BUF_SIZE (1024 * 512) //512 KB per read #define BLOCK_LOOP_FACTOR 16 // 8MB (0.5MB*16) per block callback #define BUF_SIZE_NO_PROGRESS (1024 * 1024) // 1MB #else #define BUF_SIZE (1024 * 1024 * 16) //16MB per read #define BLOCK_LOOP_FACTOR 16 // 64MB (16MB*16) per block callback #define BUF_SIZE_NO_PROGRESS (1024 * 1024 * 16) // 16MB #endif @implementation YYFileHash + (YYFileHash *)hashForFile:(NSString *)filePath types:(YYFileHashType)types { return [self hashForFile:filePath types:types usingBlock:nil]; } + (YYFileHash *)hashForFile:(NSString *)filePath types:(YYFileHashType)types usingBlock:(void(^)(UInt64 totalSize, UInt64 processedSize, BOOL *stop))block { YYFileHash *hash = nil; BOOL stop = NO, done = NO; int64_t file_size = 0, readed = 0, loop = 0; const char *path = 0; FILE *fd = 0; char *buf = NULL; int hash_type_total = 10; void *ctx[hash_type_total]; int(*ctx_init[hash_type_total])(void *); int(*ctx_update[hash_type_total])(void *, const void *, CC_LONG); int(*ctx_final[hash_type_total])(unsigned char *, void *); long digist_length[hash_type_total]; unsigned char *digest[hash_type_total]; for (int i = 0; i < hash_type_total; i++) { ctx[i] = NULL; ctx_init[i] = NULL; ctx_update[i] = NULL; ctx_final[i] = NULL; digist_length[i] = 0; digest[i] = 0; } #define init_hash(Type,Init,Update,Final,Length) \ ctx[ctx_index] = malloc(sizeof(Type)); \ ctx_init[ctx_index] = (int (*)(void *))Init; \ ctx_update[ctx_index] = (int (*)(void *, const void *, CC_LONG))Update; \ ctx_final[ctx_index] = (int (*)(unsigned char *, void *))Final; \ digist_length[ctx_index] = Length; int ctx_index = 0; if (types & YYFileHashTypeMD2) { init_hash(CC_MD2_CTX, CC_MD2_Init, CC_MD2_Update, CC_MD2_Final, CC_MD2_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeMD4) { init_hash(CC_MD4_CTX, CC_MD4_Init, CC_MD4_Update, CC_MD4_Final, CC_MD4_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeMD5) { init_hash(CC_MD5_CTX, CC_MD5_Init, CC_MD5_Update, CC_MD5_Final, CC_MD5_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeSHA1) { init_hash(CC_SHA1_CTX, CC_SHA1_Init, CC_SHA1_Update, CC_SHA1_Final, CC_SHA1_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeSHA224) { init_hash(CC_SHA256_CTX, CC_SHA224_Init, CC_SHA224_Update, CC_SHA224_Final, CC_SHA224_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeSHA256) { init_hash(CC_SHA256_CTX, CC_SHA256_Init, CC_SHA256_Update, CC_SHA256_Final, CC_SHA256_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeSHA384) { init_hash(CC_SHA512_CTX, CC_SHA384_Init, CC_SHA384_Update, CC_SHA384_Final, CC_SHA384_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeSHA512) { init_hash(CC_SHA512_CTX, CC_SHA512_Init, CC_SHA512_Update, CC_SHA512_Final, CC_SHA512_DIGEST_LENGTH); } ctx_index++; if (types & YYFileHashTypeCRC32) { init_hash(uLong, crc32_init, crc32_update, crc32_final, sizeof(uint32_t)); } ctx_index++; if (types & YYFileHashTypeAdler32) { init_hash(uLong, adler32_init, adler32_update, adler32_final, sizeof(uint32_t)); } #undef init_hash int hash_type_this = 0; for (int i = 0; i < hash_type_total; i++) { if (digist_length[i]) { hash_type_this++; digest[i] = malloc(digist_length[i]); if (digest[i] == NULL || ctx[i] == NULL) goto cleanup; } } if (hash_type_this == 0) goto cleanup; buf = malloc(block ? BUF_SIZE : BUF_SIZE_NO_PROGRESS); if (!buf) goto cleanup; if (filePath.length == 0) goto cleanup; path = [filePath cStringUsingEncoding:NSUTF8StringEncoding]; fd = fopen(path, "rb"); if (!fd) goto cleanup; if (fseeko(fd, 0, SEEK_END) != 0) goto cleanup; file_size = ftell(fd); if (fseeko(fd, 0, SEEK_SET) != 0) goto cleanup; if (file_size < 0) goto cleanup; // init hash context for (int i = 0; i < hash_type_total; i++) { if (ctx[i]) ctx_init[i](ctx[i]); } // read stream and calculate checksum in a single loop // 'dispatch_io' has better performance, I will rewrite it later... if (block) { while (!done && !stop) { size_t size = fread(buf, 1, BUF_SIZE, fd); if (size < BUF_SIZE) { if (feof(fd)) done = YES; // finish else { stop = YES; break; } // error } for (int i = 0; i < hash_type_total; i++) { if (ctx[i]) ctx_update[i](ctx[i], buf, (CC_LONG)size); } readed += size; if (!done) { loop++; if ((loop % BLOCK_LOOP_FACTOR) == 0) { block(file_size, readed, &stop); } } } } else { while (!done && !stop) { size_t size = fread(buf, 1, BUF_SIZE_NO_PROGRESS, fd); if (size < BUF_SIZE_NO_PROGRESS) { if (feof(fd)) done = YES; // finish else { stop = YES; break; } // error } for (int i = 0; i < hash_type_total; i++) { if (ctx[i]) ctx_update[i](ctx[i], buf, (CC_LONG)size); } readed += size; } } // collect result if (done && !stop) { hash = [YYFileHash new]; hash->_types = types; for (int i = 0; i < hash_type_total; i++) { if (ctx[i]) { ctx_final[i](digest[i], ctx[i]); NSUInteger type = 1 << i; NSData *data = [NSData dataWithBytes:digest[i] length:digist_length[i]]; NSMutableString *str = [NSMutableString string]; unsigned char *bytes = (unsigned char *)data.bytes; for (NSUInteger d = 0; d < data.length; d++) { [str appendFormat:@"%02x", bytes[d]]; } switch (type) { case YYFileHashTypeMD2: { hash->_md2Data = data; hash->_md2String = str; } break; case YYFileHashTypeMD4: { hash->_md4Data = data; hash->_md4String = str; } break; case YYFileHashTypeMD5: { hash->_md5Data = data; hash->_md5String = str; } break; case YYFileHashTypeSHA1: { hash->_sha1Data = data; hash->_sha1String = str; } break; case YYFileHashTypeSHA224: { hash->_sha224Data = data; hash->_sha224String = str; } break; case YYFileHashTypeSHA256: { hash->_sha256Data = data; hash->_sha256String = str; } break; case YYFileHashTypeSHA384: { hash->_sha384Data = data; hash->_sha384String = str; } break; case YYFileHashTypeSHA512: { hash->_sha512Data = data; hash->_sha512String = str; } break; case YYFileHashTypeCRC32: { uint32_t hash32 = *((uint32_t *)bytes); hash->_crc32 = hash32; hash->_crc32String = [NSString stringWithFormat:@"%08x", hash32]; } break; case YYFileHashTypeAdler32: { uint32_t hash32 = *((uint32_t *)bytes); hash->_adler32 = hash32; hash->_adler32String = [NSString stringWithFormat:@"%08x", hash32]; } break; default: break; } } } } cleanup: // do cleanup when canceled of finished if (buf) free(buf); if (fd) fclose(fd); for (int i = 0; i < hash_type_total; i++) { if (ctx[i]) free(ctx[i]); if (digest[i]) free(digest[i]); } return hash; } #pragma mark - crc32 callback static int crc32_init(uLong *c) { *c = crc32(0L, Z_NULL, 0); return 0; } static int crc32_update(uLong *c, const void *data, CC_LONG len) { *c = crc32(*c, data, len); return 0; } static int crc32_final(unsigned char *buf, uLong *c) { *((uint32_t *)buf) = (uint32_t)*c; return 0; } #pragma mark - adler32 callback static int adler32_init(uLong *c) { *c = adler32(0L, Z_NULL, 0); return 0; } static int adler32_update(uLong *c, const void *data, CC_LONG len) { *c = adler32(*c, data, len); return 0; } static int adler32_final(unsigned char *buf, uLong *c) { *((uint32_t *)buf) = (uint32_t)*c; return 0; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Utility/YYFileHash.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,508
```objective-c // // YYImage.m // YYKit <path_to_url // // Created by ibireme on 14/10/20. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYImage.h" #import "NSString+YYAdd.h" #import "NSBundle+YYAdd.h" @implementation YYImage { YYImageDecoder *_decoder; NSArray *_preloadedFrames; dispatch_semaphore_t _preloadedLock; NSUInteger _bytesPerFrame; } + (YYImage *)imageNamed:(NSString *)name { if (name.length == 0) return nil; if ([name hasSuffix:@"/"]) return nil; NSString *res = name.stringByDeletingPathExtension; NSString *ext = name.pathExtension; NSString *path = nil; CGFloat scale = 1; // If no extension, guess by system supported (same as UIImage). NSArray *exts = ext.length > 0 ? @[ext] : @[@"", @"png", @"jpeg", @"jpg", @"gif", @"webp", @"apng"]; NSArray *scales = [NSBundle preferredScales]; for (int s = 0; s < scales.count; s++) { scale = ((NSNumber *)scales[s]).floatValue; NSString *scaledName = [res stringByAppendingNameScale:scale]; for (NSString *e in exts) { path = [[NSBundle mainBundle] pathForResource:scaledName ofType:e]; if (path) break; } if (path) break; } if (path.length == 0) return nil; NSData *data = [NSData dataWithContentsOfFile:path]; if (data.length == 0) return nil; return [[self alloc] initWithData:data scale:scale]; } + (YYImage *)imageWithContentsOfFile:(NSString *)path { return [[self alloc] initWithContentsOfFile:path]; } + (YYImage *)imageWithData:(NSData *)data { return [[self alloc] initWithData:data]; } + (YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale { return [[self alloc] initWithData:data scale:scale]; } - (instancetype)initWithContentsOfFile:(NSString *)path { NSData *data = [NSData dataWithContentsOfFile:path]; return [self initWithData:data scale:path.pathScale]; } - (instancetype)initWithData:(NSData *)data { return [self initWithData:data scale:1]; } - (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale { if (data.length == 0) return nil; if (scale <= 0) scale = [UIScreen mainScreen].scale; _preloadedLock = dispatch_semaphore_create(1); @autoreleasepool { YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:scale]; YYImageFrame *frame = [decoder frameAtIndex:0 decodeForDisplay:YES]; UIImage *image = frame.image; if (!image) return nil; self = [self initWithCGImage:image.CGImage scale:decoder.scale orientation:image.imageOrientation]; if (!self) return nil; _animatedImageType = decoder.type; if (decoder.frameCount > 1) { _decoder = decoder; _bytesPerFrame = CGImageGetBytesPerRow(image.CGImage) * CGImageGetHeight(image.CGImage); _animatedImageMemorySize = _bytesPerFrame * decoder.frameCount; } self.isDecodedForDisplay = YES; } return self; } - (NSData *)animatedImageData { return _decoder.data; } - (void)setPreloadAllAnimatedImageFrames:(BOOL)preloadAllAnimatedImageFrames { if (_preloadAllAnimatedImageFrames != preloadAllAnimatedImageFrames) { if (preloadAllAnimatedImageFrames && _decoder.frameCount > 0) { NSMutableArray *frames = [NSMutableArray new]; for (NSUInteger i = 0, max = _decoder.frameCount; i < max; i++) { UIImage *img = [self animatedImageFrameAtIndex:i]; if (img) { [frames addObject:img]; } else { [frames addObject:[NSNull null]]; } } dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER); _preloadedFrames = frames; dispatch_semaphore_signal(_preloadedLock); } else { dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER); _preloadedFrames = nil; dispatch_semaphore_signal(_preloadedLock); } } } #pragma mark - protocol NSCoding - (instancetype)initWithCoder:(NSCoder *)aDecoder { NSNumber *scale = [aDecoder decodeObjectForKey:@"YYImageScale"]; NSData *data = [aDecoder decodeObjectForKey:@"YYImageData"]; if (data.length) { self = [self initWithData:data scale:scale.doubleValue]; } else { self = [super initWithCoder:aDecoder]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { if (_decoder.data.length) { [aCoder encodeObject:@(self.scale) forKey:@"YYImageScale"]; [aCoder encodeObject:_decoder.data forKey:@"YYImageData"]; } else { [super encodeWithCoder:aCoder]; // Apple use UIImagePNGRepresentation() to encode UIImage. } } #pragma mark - protocol YYAnimatedImage - (NSUInteger)animatedImageFrameCount { return _decoder.frameCount; } - (NSUInteger)animatedImageLoopCount { return _decoder.loopCount; } - (NSUInteger)animatedImageBytesPerFrame { return _bytesPerFrame; } - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { if (index >= _decoder.frameCount) return nil; dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER); UIImage *image = _preloadedFrames[index]; dispatch_semaphore_signal(_preloadedLock); if (image) return image == (id)[NSNull null] ? nil : image; return [_decoder frameAtIndex:index decodeForDisplay:YES].image; } - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { NSTimeInterval duration = [_decoder frameDurationAtIndex:index]; /* path_to_url Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See <rdar://problem/7689300> and <path_to_url for more information. See also: path_to_url */ if (duration < 0.011f) return 0.100f; return duration; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYImage.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,441
```objective-c // // YYSpriteImage.m // YYKit <path_to_url // // Created by ibireme on 15/4/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYSpriteSheetImage.h" @implementation YYSpriteSheetImage - (instancetype)initWithSpriteSheetImage:(UIImage *)image contentRects:(NSArray *)contentRects frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount { if (!image.CGImage) return nil; if (contentRects.count < 1 || frameDurations.count < 1) return nil; if (contentRects.count != frameDurations.count) return nil; self = [super initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation]; if (!self) return nil; _contentRects = contentRects.copy; _frameDurations = frameDurations.copy; _loopCount = loopCount; return self; } - (CGRect)contentsRectForCALayerAtIndex:(NSUInteger)index { CGRect layerRect = CGRectMake(0, 0, 1, 1); if (index >= _contentRects.count) return layerRect; CGSize imageSize = self.size; CGRect rect = [self animatedImageContentsRectAtIndex:index]; if (imageSize.width > 0.01 && imageSize.height > 0.01) { layerRect.origin.x = rect.origin.x / imageSize.width; layerRect.origin.y = rect.origin.y / imageSize.height; layerRect.size.width = rect.size.width / imageSize.width; layerRect.size.height = rect.size.height / imageSize.height; layerRect = CGRectIntersection(layerRect, CGRectMake(0, 0, 1, 1)); if (CGRectIsNull(layerRect) || CGRectIsEmpty(layerRect)) { layerRect = CGRectMake(0, 0, 1, 1); } } return layerRect; } #pragma mark @protocol YYAnimatedImage - (NSUInteger)animatedImageFrameCount { return _contentRects.count; } - (NSUInteger)animatedImageLoopCount { return _loopCount; } - (NSUInteger)animatedImageBytesPerFrame { return 0; } - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { return self; } - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { if (index >= _frameDurations.count) return 0; return ((NSNumber *)_frameDurations[index]).doubleValue; } - (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index { if (index >= _contentRects.count) return CGRectZero; return ((NSValue *)_contentRects[index]).CGRectValue; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYSpriteSheetImage.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
598
```objective-c // // YYFrameImage.h // YYKit <path_to_url // // Created by ibireme on 14/12/9. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYAnimatedImageView.h> #else #import "YYAnimatedImageView.h" #endif NS_ASSUME_NONNULL_BEGIN /** An image to display frame-based animation. @discussion It is a fully compatible `UIImage` subclass. It only support system image format such as png and jpeg. The animation can be played by YYAnimatedImageView. Sample Code: NSArray *paths = @[@"/ani/frame1.png", @"/ani/frame2.png", @"/ani/frame3.png"]; NSArray *times = @[@0.1, @0.2, @0.1]; YYFrameImage *image = [YYFrameImage alloc] initWithImagePaths:paths frameDurations:times repeats:YES]; YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image]; [view addSubView:imageView]; */ @interface YYFrameImage : UIImage <YYAnimatedImage> /** Create a frame animated image from files. @param paths An array of NSString objects, contains the full or partial path to each image file. e.g. @[@"/ani/1.png",@"/ani/2.png",@"/ani/3.png"] @param oneFrameDuration The duration (in seconds) per frame. @param loopCount The animation loop count, 0 means infinite. @return An initialized YYFrameImage object, or nil when an error occurs. */ - (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount; /** Create a frame animated image from files. @param paths An array of NSString objects, contains the full or partial path to each image file. e.g. @[@"/ani/frame1.png",@"/ani/frame2.png",@"/ani/frame3.png"] @param frameDurations An array of NSNumber objects, contains the duration (in seconds) per frame. e.g. @[@0.1, @0.2, @0.3]; @param loopCount The animation loop count, 0 means infinite. @return An initialized YYFrameImage object, or nil when an error occurs. */ - (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths frameDurations:(NSArray<NSNumber *> *)frameDurations loopCount:(NSUInteger)loopCount; /** Create a frame animated image from an array of data. @param dataArray An array of NSData objects. @param oneFrameDuration The duration (in seconds) per frame. @param loopCount The animation loop count, 0 means infinite. @return An initialized YYFrameImage object, or nil when an error occurs. */ - (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount; /** Create a frame animated image from an array of data. @param dataArray An array of NSData objects. @param frameDurations An array of NSNumber objects, contains the duration (in seconds) per frame. e.g. @[@0.1, @0.2, @0.3]; @param loopCount The animation loop count, 0 means infinite. @return An initialized YYFrameImage object, or nil when an error occurs. */ - (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYFrameImage.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
844
```objective-c // // YYWebImageManager.h // YYKit <path_to_url // // Created by ibireme on 15/2/19. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYImageCache.h> #else #import "YYImageCache.h" #endif @class YYWebImageOperation; NS_ASSUME_NONNULL_BEGIN /// The options to control image operation. typedef NS_OPTIONS(NSUInteger, YYWebImageOptions) { /// Show network activity on status bar when download image. YYWebImageOptionShowNetworkActivity = 1 << 0, /// Display progressive/interlaced/baseline image during download (same as web browser). YYWebImageOptionProgressive = 1 << 1, /// Display blurred progressive JPEG or interlaced PNG image during download. /// This will ignore baseline image for better user experience. YYWebImageOptionProgressiveBlur = 1 << 2, /// Use NSURLCache instead of YYImageCache. YYWebImageOptionUseNSURLCache = 1 << 3, /// Allows untrusted SSL ceriticates. YYWebImageOptionAllowInvalidSSLCertificates = 1 << 4, /// Allows background task to download image when app is in background. YYWebImageOptionAllowBackgroundTask = 1 << 5, /// Handles cookies stored in NSHTTPCookieStore. YYWebImageOptionHandleCookies = 1 << 6, /// Load the image from remote and refresh the image cache. YYWebImageOptionRefreshImageCache = 1 << 7, /// Do not load image from/to disk cache. YYWebImageOptionIgnoreDiskCache = 1 << 8, /// Do not change the view's image before set a new URL to it. YYWebImageOptionIgnorePlaceHolder = 1 << 9, /// Ignore image decoding. /// This may used for image downloading without display. YYWebImageOptionIgnoreImageDecoding = 1 << 10, /// Ignore multi-frame image decoding. /// This will handle the GIF/APNG/WebP/ICO image as single frame image. YYWebImageOptionIgnoreAnimatedImage = 1 << 11, /// Set the image to view with a fade animation. /// This will add a "fade" animation on image view's layer for better user experience. YYWebImageOptionSetImageWithFadeAnimation = 1 << 12, /// Do not set the image to the view when image fetch complete. /// You may set the image manually. YYWebImageOptionAvoidSetImage = 1 << 13, /// This flag will add the URL to a blacklist (in memory) when the URL fail to be downloaded, /// so the library won't keep trying. YYWebImageOptionIgnoreFailedURL = 1 << 14, }; /// Indicated where the image came from. typedef NS_ENUM(NSUInteger, YYWebImageFromType) { /// No value. YYWebImageFromNone = 0, /// Fetched from memory cache immediately. /// If you called "setImageWithURL:..." and the image is already in memory, /// then you will get this value at the same call. YYWebImageFromMemoryCacheFast, /// Fetched from memory cache. YYWebImageFromMemoryCache, /// Fetched from disk cache. YYWebImageFromDiskCache, /// Fetched from remote (web or file path). YYWebImageFromRemote, }; /// Indicated image fetch complete stage. typedef NS_ENUM(NSInteger, YYWebImageStage) { /// Incomplete, progressive image. YYWebImageStageProgress = -1, /// Cancelled. YYWebImageStageCancelled = 0, /// Finished (succeed or failed). YYWebImageStageFinished = 1, }; /** The block invoked in remote image fetch progress. @param receivedSize Current received size in bytes. @param expectedSize Expected total size in bytes (-1 means unknown). */ typedef void(^YYWebImageProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); /** The block invoked before remote image fetch finished to do additional image process. @discussion This block will be invoked before `YYWebImageCompletionBlock` to give you a chance to do additional image process (such as resize or crop). If there's no need to transform the image, just return the `image` parameter. @example You can clip the image, blur it and add rounded corners with these code: ^(UIImage *image, NSURL *url) { // Maybe you need to create an @autoreleasepool to limit memory cost. image = [image imageByResizeToSize:CGSizeMake(100, 100) contentMode:UIViewContentModeScaleAspectFill]; image = [image imageByBlurRadius:20 tintColor:nil tintMode:kCGBlendModeNormal saturation:1.2 maskImage:nil]; image = [image imageByRoundCornerRadius:5]; return image; } @param image The image fetched from url. @param url The image url (remote or local file path). @return The transformed image. */ typedef UIImage * _Nullable (^YYWebImageTransformBlock)(UIImage *image, NSURL *url); /** The block invoked when image fetch finished or cancelled. @param image The image. @param url The image url (remote or local file path). @param from Where the image came from. @param error Error during image fetching. @param finished If the operation is cancelled, this value is NO, otherwise YES. */ typedef void (^YYWebImageCompletionBlock)(UIImage * _Nullable image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error); /** A manager to create and manage web image operation. */ @interface YYWebImageManager : NSObject /** Returns global YYWebImageManager instance. @return YYWebImageManager shared instance. */ + (instancetype)sharedManager; /** Creates a manager with an image cache and operation queue. @param cache Image cache used by manager (pass nil to avoid image cache). @param queue The operation queue on which image operations are scheduled and run (pass nil to make the new operation start immediately without queue). @return A new manager. */ - (instancetype)initWithCache:(nullable YYImageCache *)cache queue:(nullable NSOperationQueue *)queue NS_DESIGNATED_INITIALIZER; - (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)new UNAVAILABLE_ATTRIBUTE; /** Creates and returns a new image operation, the operation will start immediately. @param url The image url (remote or local file path). @param options The options to control image operation. @param progress Progress block which will be invoked on background thread (pass nil to avoid). @param transform Transform block which will be invoked on background thread (pass nil to avoid). @param completion Completion block which will be invoked on background thread (pass nil to avoid). @return A new image operation. */ - (nullable YYWebImageOperation *)requestImageWithURL:(NSURL *)url options:(YYWebImageOptions)options progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** The image cache used by image operation. You can set it to nil to avoid image cache. */ @property (nullable, nonatomic, strong) YYImageCache *cache; /** The operation queue on which image operations are scheduled and run. You can set it to nil to make the new operation start immediately without queue. You can use this queue to control maximum number of concurrent operations, to obtain the status of the current operations, or to cancel all operations in this manager. */ @property (nullable, nonatomic, strong) NSOperationQueue *queue; /** The shared transform block to process image. Default is nil. When called `requestImageWithURL:options:progress:transform:completion` and the `transform` is nil, this block will be used. */ @property (nullable, nonatomic, copy) YYWebImageTransformBlock sharedTransformBlock; /** The image request timeout interval in seconds. Default is 15. */ @property (nonatomic) NSTimeInterval timeout; /** The username used by NSURLCredential, default is nil. */ @property (nullable, nonatomic, copy) NSString *username; /** The password used by NSURLCredential, default is nil. */ @property (nullable, nonatomic, copy) NSString *password; /** The image HTTP request header. Default is "Accept:image/webp,image/\*;q=0.8". */ @property (nullable, nonatomic, copy) NSDictionary<NSString *, NSString *> *headers; /** A block which will be invoked for each image HTTP request to do additional HTTP header process. Default is nil. Use this block to add or remove HTTP header field for a specified URL. */ @property (nullable, nonatomic, copy) NSDictionary<NSString *, NSString *> *(^headersFilter)(NSURL *url, NSDictionary<NSString *, NSString *> * _Nullable header); /** A block which will be invoked for each image operation. Default is nil. Use this block to provide a custom image cache key for a specified URL. */ @property (nullable, nonatomic, copy) NSString *(^cacheKeyFilter)(NSURL *url); /** Returns the HTTP headers for a specified URL. @param url A specified URL. @return HTTP headers. */ - (nullable NSDictionary<NSString *, NSString *> *)headersForURL:(NSURL *)url; /** Returns the cache key for a specified URL. @param url A specified URL @return Cache key used in YYImageCache. */ - (NSString *)cacheKeyForURL:(NSURL *)url; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYWebImageManager.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,123
```objective-c // // YYAnimatedImageView.h // YYKit <path_to_url // // Created by ibireme on 14/10/19. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** An image view for displaying animated image. @discussion It is a fully compatible `UIImageView` subclass. If the `image` or `highlightedImage` property adopt to the `YYAnimatedImage` protocol, then it can be used to play the multi-frame animation. The animation can also be controlled with the UIImageView methods `-startAnimating`, `-stopAnimating` and `-isAnimating`. This view request the frame data just in time. When the device has enough free memory, this view may cache some or all future frames in an inner buffer for lower CPU cost. Buffer size is dynamically adjusted based on the current state of the device memory. Sample Code: // ani@3x.gif YYImage *image = [YYImage imageNamed:@"ani"]; YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image]; [view addSubView:imageView]; */ @interface YYAnimatedImageView : UIImageView /** If the image has more than one frame, set this value to `YES` will automatically play/stop the animation when the view become visible/invisible. The default value is `YES`. */ @property (nonatomic) BOOL autoPlayAnimatedImage; /** Index of the currently displayed frame (index from 0). Set a new value to this property will cause to display the new frame immediately. If the new value is invalid, this method has no effect. You can add an observer to this property to observe the playing status. */ @property (nonatomic) NSUInteger currentAnimatedImageIndex; /** Whether the image view is playing animation currently. You can add an observer to this property to observe the playing status. */ @property (nonatomic, readonly) BOOL currentIsPlayingAnimation; /** The animation timer's runloop mode, default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. */ @property (nonatomic, copy) NSString *runloopMode; /** The max size (in bytes) for inner frame buffer size, default is 0 (dynamically). When the device has enough free memory, this view will request and decode some or all future frame image into an inner buffer. If this property's value is 0, then the max buffer size will be dynamically adjusted based on the current state of the device free memory. Otherwise, the buffer size will be limited by this value. When receive memory warning or app enter background, the buffer will be released immediately, and may grow back at the right time. */ @property (nonatomic) NSUInteger maxBufferSize; @end /** The YYAnimatedImage protocol declares the required methods for animated image display with YYAnimatedImageView. Subclass a UIImage and implement this protocol, so that instances of that class can be set to YYAnimatedImageView.image or YYAnimatedImageView.highlightedImage to display animation. See `YYImage` and `YYFrameImage` for example. */ @protocol YYAnimatedImage <NSObject> @required /// Total animated frame count. /// If the frame count is less than 1, then the methods below will be ignored. - (NSUInteger)animatedImageFrameCount; /// Animation loop count, 0 means infinite looping. - (NSUInteger)animatedImageLoopCount; /// Bytes per frame (in memory). It may used to optimize memory buffer size. - (NSUInteger)animatedImageBytesPerFrame; /// Returns the frame image from a specified index. /// This method may be called on background thread. /// @param index Frame index (zero based). - (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index; /// Returns the frames's duration from a specified index. /// @param index Frame index (zero based). - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index; @optional /// A rectangle in image coordinates defining the subrectangle of the image that /// will be displayed. The rectangle should not outside the image's bounds. /// It may used to display sprite animation with a single image (sprite sheet). - (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYAnimatedImageView.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
915
```objective-c // // YYWebImageOperation.h // YYKit <path_to_url // // Created by ibireme on 15/2/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYImageCache.h> #import <YYKit/YYWebImageManager.h> #else #import "YYImageCache.h" #import "YYWebImageManager.h" #endif NS_ASSUME_NONNULL_BEGIN /** The YYWebImageOperation class is an NSOperation subclass used to fetch image from URL request. @discussion It's an asynchronous operation. You typically execute it by adding it to an operation queue, or calls 'start' to execute it manually. When the operation is started, it will: 1. Get the image from the cache, if exist, return it with `completion` block. 2. Start an URL connection to fetch image from the request, invoke the `progress` to notify request progress (and invoke `completion` block to return the progressive image if enabled by progressive option). 3. Process the image by invoke the `transform` block. 4. Put the image to cache and return it with `completion` block. */ @interface YYWebImageOperation : NSOperation @property (nonatomic, strong, readonly) NSURLRequest *request; ///< The image URL request. @property (nullable, nonatomic, strong, readonly) NSURLResponse *response; ///< The response for request. @property (nullable, nonatomic, strong, readonly) YYImageCache *cache; ///< The image cache. @property (nonatomic, strong, readonly) NSString *cacheKey; ///< The image cache key. @property (nonatomic, readonly) YYWebImageOptions options; ///< The operation's option. /** Whether the URL connection should consult the credential storage for authenticating the connection. Default is YES. @discussion This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. */ @property (nonatomic) BOOL shouldUseCredentialStorage; /** The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. @discussion This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. */ @property (nullable, nonatomic, strong) NSURLCredential *credential; /** Creates and returns a new operation. You should call `start` to execute this operation, or you can add the operation to an operation queue. @param request The Image request. This value should not be nil. @param options A mask to specify options to use for this operation. @param cache An image cache. Pass nil to avoid image cache. @param cacheKey An image cache key. Pass nil to avoid image cache. @param progress A block invoked in image fetch progress. The block will be invoked in background thread. Pass nil to avoid it. @param transform A block invoked before image fetch finished to do additional image process. The block will be invoked in background thread. Pass nil to avoid it. @param completion A block invoked when image fetch finished or cancelled. The block will be invoked in background thread. Pass nil to avoid it. @return The image request opeartion, or nil if an error occurs. */ - (instancetype)initWithRequest:(NSURLRequest *)request options:(YYWebImageOptions)options cache:(nullable YYImageCache *)cache cacheKey:(nullable NSString *)cacheKey progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion NS_DESIGNATED_INITIALIZER; - (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)new UNAVAILABLE_ATTRIBUTE; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYWebImageOperation.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
838
```objective-c // // YYAnimatedImageView.m // YYKit <path_to_url // // Created by ibireme on 14/10/19. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYAnimatedImageView.h" #import "YYWeakProxy.h" #import "UIDevice+YYAdd.h" #import "YYImageCoder.h" #import "YYKitMacro.h" #define BUFFER_SIZE (10 * 1024 * 1024) // 10MB (minimum memory buffer size) #define LOCK(...) dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER); \ __VA_ARGS__; \ dispatch_semaphore_signal(self->_lock); #define LOCK_VIEW(...) dispatch_semaphore_wait(view->_lock, DISPATCH_TIME_FOREVER); \ __VA_ARGS__; \ dispatch_semaphore_signal(view->_lock); typedef NS_ENUM(NSUInteger, YYAnimatedImageType) { YYAnimatedImageTypeNone = 0, YYAnimatedImageTypeImage, YYAnimatedImageTypeHighlightedImage, YYAnimatedImageTypeImages, YYAnimatedImageTypeHighlightedImages, }; @interface YYAnimatedImageView() { @package UIImage <YYAnimatedImage> *_curAnimatedImage; dispatch_once_t _onceToken; dispatch_semaphore_t _lock; ///< lock for _buffer NSOperationQueue *_requestQueue; ///< image request queue, serial CADisplayLink *_link; ///< ticker for change frame NSTimeInterval _time; ///< time after last frame UIImage *_curFrame; ///< current frame to display NSUInteger _curIndex; ///< current frame index (from 0) NSUInteger _totalFrameCount; ///< total frame count BOOL _loopEnd; ///< whether the loop is end. NSUInteger _curLoop; ///< current loop count (from 0) NSUInteger _totalLoop; ///< total loop count, 0 means infinity NSMutableDictionary *_buffer; ///< frame buffer BOOL _bufferMiss; ///< whether miss frame on last opportunity NSUInteger _maxBufferCount; ///< maximum buffer count NSInteger _incrBufferCount; ///< current allowed buffer count (will increase by step) CGRect _curContentsRect; BOOL _curImageHasContentsRect; ///< image has implementated "animatedImageContentsRectAtIndex:" } @property (nonatomic, readwrite) BOOL currentIsPlayingAnimation; - (void)calcMaxBufferCount; @end /// An operation for image fetch @interface _YYAnimatedImageViewFetchOperation : NSOperation @property (nonatomic, weak) YYAnimatedImageView *view; @property (nonatomic, assign) NSUInteger nextIndex; @property (nonatomic, strong) UIImage <YYAnimatedImage> *curImage; @end @implementation _YYAnimatedImageViewFetchOperation - (void)main { __strong YYAnimatedImageView *view = _view; if (!view) return; if ([self isCancelled]) return; view->_incrBufferCount++; if (view->_incrBufferCount == 0) [view calcMaxBufferCount]; if (view->_incrBufferCount > (NSInteger)view->_maxBufferCount) { view->_incrBufferCount = view->_maxBufferCount; } NSUInteger idx = _nextIndex; NSUInteger max = view->_incrBufferCount < 1 ? 1 : view->_incrBufferCount; NSUInteger total = view->_totalFrameCount; view = nil; for (int i = 0; i < max; i++, idx++) { @autoreleasepool { if (idx >= total) idx = 0; if ([self isCancelled]) break; __strong YYAnimatedImageView *view = _view; if (!view) break; LOCK_VIEW(BOOL miss = (view->_buffer[@(idx)] == nil)); if (miss) { UIImage *img = [_curImage animatedImageFrameAtIndex:idx]; img = img.imageByDecoded; if ([self isCancelled]) break; LOCK_VIEW(view->_buffer[@(idx)] = img ? img : [NSNull null]); view = nil; } } } } @end @implementation YYAnimatedImageView - (instancetype)init { self = [super init]; _runloopMode = NSRunLoopCommonModes; _autoPlayAnimatedImage = YES; return self; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; _runloopMode = NSRunLoopCommonModes; _autoPlayAnimatedImage = YES; return self; } - (instancetype)initWithImage:(UIImage *)image { self = [super init]; _runloopMode = NSRunLoopCommonModes; _autoPlayAnimatedImage = YES; self.frame = (CGRect) {CGPointZero, image.size }; self.image = image; return self; } - (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage { self = [super init]; _runloopMode = NSRunLoopCommonModes; _autoPlayAnimatedImage = YES; CGSize size = image ? image.size : highlightedImage.size; self.frame = (CGRect) {CGPointZero, size }; self.image = image; self.highlightedImage = highlightedImage; return self; } // init the animated params. - (void)resetAnimated { dispatch_once(&_onceToken, ^{ _lock = dispatch_semaphore_create(1); _buffer = [NSMutableDictionary new]; _requestQueue = [[NSOperationQueue alloc] init]; _requestQueue.maxConcurrentOperationCount = 1; _link = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(step:)]; if (_runloopMode) { [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:_runloopMode]; } _link.paused = YES; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; }); [_requestQueue cancelAllOperations]; LOCK( if (_buffer.count) { NSMutableDictionary *holder = _buffer; _buffer = [NSMutableDictionary new]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ // Capture the dictionary to global queue, // release these images in background to avoid blocking UI thread. [holder class]; }); } ); _link.paused = YES; _time = 0; if (_curIndex != 0) { [self willChangeValueForKey:@"currentAnimatedImageIndex"]; _curIndex = 0; [self didChangeValueForKey:@"currentAnimatedImageIndex"]; } _curAnimatedImage = nil; _curFrame = nil; _curLoop = 0; _totalLoop = 0; _totalFrameCount = 1; _loopEnd = NO; _bufferMiss = NO; _incrBufferCount = 0; } - (void)setImage:(UIImage *)image { if (self.image == image) return; [self setImage:image withType:YYAnimatedImageTypeImage]; } - (void)setHighlightedImage:(UIImage *)highlightedImage { if (self.highlightedImage == highlightedImage) return; [self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage]; } - (void)setAnimationImages:(NSArray *)animationImages { if (self.animationImages == animationImages) return; [self setImage:animationImages withType:YYAnimatedImageTypeImages]; } - (void)setHighlightedAnimationImages:(NSArray *)highlightedAnimationImages { if (self.highlightedAnimationImages == highlightedAnimationImages) return; [self setImage:highlightedAnimationImages withType:YYAnimatedImageTypeHighlightedImages]; } - (void)setHighlighted:(BOOL)highlighted { [super setHighlighted:highlighted]; if (_link) [self resetAnimated]; [self imageChanged]; } - (id)imageForType:(YYAnimatedImageType)type { switch (type) { case YYAnimatedImageTypeNone: return nil; case YYAnimatedImageTypeImage: return self.image; case YYAnimatedImageTypeHighlightedImage: return self.highlightedImage; case YYAnimatedImageTypeImages: return self.animationImages; case YYAnimatedImageTypeHighlightedImages: return self.highlightedAnimationImages; } return nil; } - (YYAnimatedImageType)currentImageType { YYAnimatedImageType curType = YYAnimatedImageTypeNone; if (self.highlighted) { if (self.highlightedAnimationImages.count) curType = YYAnimatedImageTypeHighlightedImages; else if (self.highlightedImage) curType = YYAnimatedImageTypeHighlightedImage; } if (curType == YYAnimatedImageTypeNone) { if (self.animationImages.count) curType = YYAnimatedImageTypeImages; else if (self.image) curType = YYAnimatedImageTypeImage; } return curType; } - (void)setImage:(id)image withType:(YYAnimatedImageType)type { [self stopAnimating]; if (_link) [self resetAnimated]; _curFrame = nil; switch (type) { case YYAnimatedImageTypeNone: break; case YYAnimatedImageTypeImage: super.image = image; break; case YYAnimatedImageTypeHighlightedImage: super.highlightedImage = image; break; case YYAnimatedImageTypeImages: super.animationImages = image; break; case YYAnimatedImageTypeHighlightedImages: super.highlightedAnimationImages = image; break; } [self imageChanged]; } - (void)imageChanged { YYAnimatedImageType newType = [self currentImageType]; id newVisibleImage = [self imageForType:newType]; NSUInteger newImageFrameCount = 0; BOOL hasContentsRect = NO; if ([newVisibleImage isKindOfClass:[UIImage class]] && [newVisibleImage conformsToProtocol:@protocol(YYAnimatedImage)]) { newImageFrameCount = ((UIImage<YYAnimatedImage> *) newVisibleImage).animatedImageFrameCount; if (newImageFrameCount > 1) { hasContentsRect = [((UIImage<YYAnimatedImage> *) newVisibleImage) respondsToSelector:@selector(animatedImageContentsRectAtIndex:)]; } } if (!hasContentsRect && _curImageHasContentsRect) { if (!CGRectEqualToRect(self.layer.contentsRect, CGRectMake(0, 0, 1, 1)) ) { [CATransaction begin]; [CATransaction setDisableActions:YES]; self.layer.contentsRect = CGRectMake(0, 0, 1, 1); [CATransaction commit]; } } _curImageHasContentsRect = hasContentsRect; if (hasContentsRect) { CGRect rect = [((UIImage<YYAnimatedImage> *) newVisibleImage) animatedImageContentsRectAtIndex:0]; [self setContentsRect:rect forImage:newVisibleImage]; } if (newImageFrameCount > 1) { [self resetAnimated]; _curAnimatedImage = newVisibleImage; _curFrame = newVisibleImage; _totalLoop = _curAnimatedImage.animatedImageLoopCount; _totalFrameCount = _curAnimatedImage.animatedImageFrameCount; [self calcMaxBufferCount]; } [self setNeedsDisplay]; [self didMoved]; } // dynamically adjust buffer size for current memory. - (void)calcMaxBufferCount { int64_t bytes = (int64_t)_curAnimatedImage.animatedImageBytesPerFrame; if (bytes == 0) bytes = 1024; int64_t total = [UIDevice currentDevice].memoryTotal; int64_t free = [UIDevice currentDevice].memoryFree; int64_t max = MIN(total * 0.2, free * 0.6); max = MAX(max, BUFFER_SIZE); if (_maxBufferSize) max = max > _maxBufferSize ? _maxBufferSize : max; double maxBufferCount = (double)max / (double)bytes; maxBufferCount = YY_CLAMP(maxBufferCount, 1, 512); _maxBufferCount = maxBufferCount; } - (void)dealloc { [_requestQueue cancelAllOperations]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; [_link invalidate]; } - (BOOL)isAnimating { return self.currentIsPlayingAnimation; } - (void)stopAnimating { [super stopAnimating]; [_requestQueue cancelAllOperations]; _link.paused = YES; self.currentIsPlayingAnimation = NO; } - (void)startAnimating { YYAnimatedImageType type = [self currentImageType]; if (type == YYAnimatedImageTypeImages || type == YYAnimatedImageTypeHighlightedImages) { NSArray *images = [self imageForType:type]; if (images.count > 0) { [super startAnimating]; self.currentIsPlayingAnimation = YES; } } else { if (_curAnimatedImage && _link.paused) { _curLoop = 0; _loopEnd = NO; _link.paused = NO; self.currentIsPlayingAnimation = YES; } } } - (void)didReceiveMemoryWarning:(NSNotification *)notification { [_requestQueue cancelAllOperations]; [_requestQueue addOperationWithBlock: ^{ _incrBufferCount = -60 - (int)(arc4random() % 120); // about 1~3 seconds to grow back.. NSNumber *next = @((_curIndex + 1) % _totalFrameCount); LOCK( NSArray * keys = _buffer.allKeys; for (NSNumber * key in keys) { if (![key isEqualToNumber:next]) { // keep the next frame for smoothly animation [_buffer removeObjectForKey:key]; } } )//LOCK }]; } - (void)didEnterBackground:(NSNotification *)notification { [_requestQueue cancelAllOperations]; NSNumber *next = @((_curIndex + 1) % _totalFrameCount); LOCK( NSArray * keys = _buffer.allKeys; for (NSNumber * key in keys) { if (![key isEqualToNumber:next]) { // keep the next frame for smoothly animation [_buffer removeObjectForKey:key]; } } )//LOCK } - (void)step:(CADisplayLink *)link { UIImage <YYAnimatedImage> *image = _curAnimatedImage; NSMutableDictionary *buffer = _buffer; UIImage *bufferedImage = nil; NSUInteger nextIndex = (_curIndex + 1) % _totalFrameCount; BOOL bufferIsFull = NO; if (!image) return; if (_loopEnd) { // view will keep in last frame [self stopAnimating]; return; } NSTimeInterval delay = 0; if (!_bufferMiss) { _time += link.duration; delay = [image animatedImageDurationAtIndex:_curIndex]; if (_time < delay) return; _time -= delay; if (nextIndex == 0) { _curLoop++; if (_curLoop >= _totalLoop && _totalLoop != 0) { _loopEnd = YES; [self stopAnimating]; [self.layer setNeedsDisplay]; // let system call `displayLayer:` before runloop sleep return; // stop at last frame } } delay = [image animatedImageDurationAtIndex:nextIndex]; if (_time > delay) _time = delay; // do not jump over frame } LOCK( bufferedImage = buffer[@(nextIndex)]; if (bufferedImage) { if ((int)_incrBufferCount < _totalFrameCount) { [buffer removeObjectForKey:@(nextIndex)]; } [self willChangeValueForKey:@"currentAnimatedImageIndex"]; _curIndex = nextIndex; [self didChangeValueForKey:@"currentAnimatedImageIndex"]; _curFrame = bufferedImage == (id)[NSNull null] ? nil : bufferedImage; if (_curImageHasContentsRect) { _curContentsRect = [image animatedImageContentsRectAtIndex:_curIndex]; [self setContentsRect:_curContentsRect forImage:_curFrame]; } nextIndex = (_curIndex + 1) % _totalFrameCount; _bufferMiss = NO; if (buffer.count == _totalFrameCount) { bufferIsFull = YES; } } else { _bufferMiss = YES; } )//LOCK if (!_bufferMiss) { [self.layer setNeedsDisplay]; // let system call `displayLayer:` before runloop sleep } if (!bufferIsFull && _requestQueue.operationCount == 0) { // if some work not finished, wait for next opportunity _YYAnimatedImageViewFetchOperation *operation = [_YYAnimatedImageViewFetchOperation new]; operation.view = self; operation.nextIndex = nextIndex; operation.curImage = image; [_requestQueue addOperation:operation]; } } - (void)displayLayer:(CALayer *)layer { if (_curFrame) { layer.contents = (__bridge id)_curFrame.CGImage; } } - (void)setContentsRect:(CGRect)rect forImage:(UIImage *)image{ CGRect layerRect = CGRectMake(0, 0, 1, 1); if (image) { CGSize imageSize = image.size; if (imageSize.width > 0.01 && imageSize.height > 0.01) { layerRect.origin.x = rect.origin.x / imageSize.width; layerRect.origin.y = rect.origin.y / imageSize.height; layerRect.size.width = rect.size.width / imageSize.width; layerRect.size.height = rect.size.height / imageSize.height; layerRect = CGRectIntersection(layerRect, CGRectMake(0, 0, 1, 1)); if (CGRectIsNull(layerRect) || CGRectIsEmpty(layerRect)) { layerRect = CGRectMake(0, 0, 1, 1); } } } [CATransaction begin]; [CATransaction setDisableActions:YES]; self.layer.contentsRect = layerRect; [CATransaction commit]; } - (void)didMoved { if (self.autoPlayAnimatedImage) { if(self.superview && self.window) { [self startAnimating]; } else { [self stopAnimating]; } } } - (void)didMoveToWindow { [super didMoveToWindow]; [self didMoved]; } - (void)didMoveToSuperview { [super didMoveToSuperview]; [self didMoved]; } - (void)setCurrentAnimatedImageIndex:(NSUInteger)currentAnimatedImageIndex { if (!_curAnimatedImage) return; if (currentAnimatedImageIndex >= _curAnimatedImage.animatedImageFrameCount) return; if (_curIndex == currentAnimatedImageIndex) return; dispatch_async_on_main_queue(^{ LOCK( [_requestQueue cancelAllOperations]; [_buffer removeAllObjects]; [self willChangeValueForKey:@"currentAnimatedImageIndex"]; _curIndex = currentAnimatedImageIndex; [self didChangeValueForKey:@"currentAnimatedImageIndex"]; _curFrame = [_curAnimatedImage animatedImageFrameAtIndex:_curIndex]; if (_curImageHasContentsRect) { _curContentsRect = [_curAnimatedImage animatedImageContentsRectAtIndex:_curIndex]; } _time = 0; _loopEnd = NO; _bufferMiss = NO; [self.layer setNeedsDisplay]; )//LOCK }); } - (NSUInteger)currentAnimatedImageIndex { return _curIndex; } - (void)setRunloopMode:(NSString *)runloopMode { if ([_runloopMode isEqual:runloopMode]) return; if (_link) { if (_runloopMode) { [_link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runloopMode]; } if (runloopMode.length) { [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:runloopMode]; } } _runloopMode = runloopMode.copy; } #pragma mark - Overrice NSObject(NSKeyValueObservingCustomization) + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { if ([key isEqualToString:@"currentAnimatedImageIndex"]) { return NO; } return [super automaticallyNotifiesObserversForKey:key]; } #pragma mark - NSCoding - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; _runloopMode = [aDecoder decodeObjectForKey:@"runloopMode"]; if (_runloopMode.length == 0) _runloopMode = NSRunLoopCommonModes; if ([aDecoder containsValueForKey:@"autoPlayAnimatedImage"]) { _autoPlayAnimatedImage = [aDecoder decodeBoolForKey:@"autoPlayAnimatedImage"]; } else { _autoPlayAnimatedImage = YES; } UIImage *image = [aDecoder decodeObjectForKey:@"YYAnimatedImage"]; UIImage *highlightedImage = [aDecoder decodeObjectForKey:@"YYHighlightedAnimatedImage"]; if (image) { self.image = image; [self setImage:image withType:YYAnimatedImageTypeImage]; } if (highlightedImage) { self.highlightedImage = highlightedImage; [self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [super encodeWithCoder:aCoder]; [aCoder encodeObject:_runloopMode forKey:@"runloopMode"]; [aCoder encodeBool:_autoPlayAnimatedImage forKey:@"autoPlayAnimatedImage"]; BOOL ani, multi; ani = [self.image conformsToProtocol:@protocol(YYAnimatedImage)]; multi = (ani && ((UIImage <YYAnimatedImage> *)self.image).animatedImageFrameCount > 1); if (multi) [aCoder encodeObject:self.image forKey:@"YYAnimatedImage"]; ani = [self.highlightedImage conformsToProtocol:@protocol(YYAnimatedImage)]; multi = (ani && ((UIImage <YYAnimatedImage> *)self.highlightedImage).animatedImageFrameCount > 1); if (multi) [aCoder encodeObject:self.highlightedImage forKey:@"YYHighlightedAnimatedImage"]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYAnimatedImageView.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
4,814
```objective-c // // YYWebImageOperation.m // YYKit <path_to_url // // Created by ibireme on 15/2/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYWebImageOperation.h" #import "UIApplication+YYAdd.h" #import "YYImage.h" #import "YYWeakProxy.h" #import "UIImage+YYAdd.h" #import <ImageIO/ImageIO.h> #import "YYKitMacro.h" #if __has_include("YYDispatchQueuePool.h") #import "YYDispatchQueuePool.h" #else #import <libkern/OSAtomic.h> #endif #define MIN_PROGRESSIVE_TIME_INTERVAL 0.2 #define MIN_PROGRESSIVE_BLUR_TIME_INTERVAL 0.4 /// Returns YES if the right-bottom pixel is filled. static BOOL YYCGImageLastPixelFilled(CGImageRef image) { if (!image) return NO; size_t width = CGImageGetWidth(image); size_t height = CGImageGetHeight(image); if (width == 0 || height == 0) return NO; CGContextRef ctx = CGBitmapContextCreate(NULL, 1, 1, 8, 0, YYCGColorSpaceGetDeviceRGB(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrderDefault); if (!ctx) return NO; CGContextDrawImage(ctx, CGRectMake( -(int)width + 1, 0, width, height), image); uint8_t *bytes = CGBitmapContextGetData(ctx); BOOL isAlpha = bytes && bytes[0] == 0; CFRelease(ctx); return !isAlpha; } /// Returns JPEG SOS (Start Of Scan) Marker static NSData *JPEGSOSMarker() { // "Start Of Scan" Marker static NSData *marker = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ uint8_t bytes[2] = {0xFF, 0xDA}; marker = [NSData dataWithBytes:bytes length:2]; }); return marker; } static NSMutableSet *URLBlacklist; static dispatch_semaphore_t URLBlacklistLock; static void URLBlacklistInit() { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ URLBlacklist = [NSMutableSet new]; URLBlacklistLock = dispatch_semaphore_create(1); }); } static BOOL URLBlackListContains(NSURL *url) { if (!url || url == (id)[NSNull null]) return NO; URLBlacklistInit(); dispatch_semaphore_wait(URLBlacklistLock, DISPATCH_TIME_FOREVER); BOOL contains = [URLBlacklist containsObject:url]; dispatch_semaphore_signal(URLBlacklistLock); return contains; } static void URLInBlackListAdd(NSURL *url) { if (!url || url == (id)[NSNull null]) return; URLBlacklistInit(); dispatch_semaphore_wait(URLBlacklistLock, DISPATCH_TIME_FOREVER); [URLBlacklist addObject:url]; dispatch_semaphore_signal(URLBlacklistLock); } @interface YYWebImageOperation() <NSURLConnectionDelegate> @property (readwrite, getter=isExecuting) BOOL executing; @property (readwrite, getter=isFinished) BOOL finished; @property (readwrite, getter=isCancelled) BOOL cancelled; @property (readwrite, getter=isStarted) BOOL started; @property (nonatomic, strong) NSRecursiveLock *lock; @property (nonatomic, strong) NSURLConnection *connection; @property (nonatomic, strong) NSMutableData *data; @property (nonatomic, assign) NSInteger expectedSize; @property (nonatomic, assign) UIBackgroundTaskIdentifier taskID; @property (nonatomic, assign) NSTimeInterval lastProgressiveDecodeTimestamp; @property (nonatomic, strong) YYImageDecoder *progressiveDecoder; @property (nonatomic, assign) BOOL progressiveIgnored; @property (nonatomic, assign) BOOL progressiveDetected; @property (nonatomic, assign) NSUInteger progressiveScanedLength; @property (nonatomic, assign) NSUInteger progressiveDisplayCount; @property (nonatomic, copy) YYWebImageProgressBlock progress; @property (nonatomic, copy) YYWebImageTransformBlock transform; @property (nonatomic, copy) YYWebImageCompletionBlock completion; @end @implementation YYWebImageOperation @synthesize executing = _executing; @synthesize finished = _finished; @synthesize cancelled = _cancelled; /// Network thread entry point. + (void)_networkThreadMain:(id)object { @autoreleasepool { [[NSThread currentThread] setName:@"com.ibireme.yykit.webimage.request"]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; [runLoop run]; } } /// Global image request network thread, used by NSURLConnection delegate. + (NSThread *)_networkThread { static NSThread *thread = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ thread = [[NSThread alloc] initWithTarget:self selector:@selector(_networkThreadMain:) object:nil]; if ([thread respondsToSelector:@selector(setQualityOfService:)]) { thread.qualityOfService = NSQualityOfServiceBackground; } [thread start]; }); return thread; } /// Global image queue, used for image reading and decoding. + (dispatch_queue_t)_imageQueue { #ifdef YYDispatchQueuePool_h return YYDispatchQueueGetForQOS(NSQualityOfServiceUtility); #else #define MAX_QUEUE_COUNT 16 static int queueCount; static dispatch_queue_t queues[MAX_QUEUE_COUNT]; static dispatch_once_t onceToken; static int32_t counter = 0; dispatch_once(&onceToken, ^{ queueCount = (int)[NSProcessInfo processInfo].activeProcessorCount; queueCount = queueCount < 1 ? 1 : queueCount > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : queueCount; if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) { for (NSUInteger i = 0; i < queueCount; i++) { dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0); queues[i] = dispatch_queue_create("com.ibireme.yykit.decode", attr); } } else { for (NSUInteger i = 0; i < queueCount; i++) { queues[i] = dispatch_queue_create("com.ibireme.yykit.decode", DISPATCH_QUEUE_SERIAL); dispatch_set_target_queue(queues[i], dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)); } } }); int32_t cur = OSAtomicIncrement32(&counter); if (cur < 0) cur = -cur; return queues[(cur) % queueCount]; #undef MAX_QUEUE_COUNT #endif } - (instancetype)init { @throw [NSException exceptionWithName:@"YYWebImageOperation init error" reason:@"YYWebImageOperation must be initialized with a request. Use the designated initializer to init." userInfo:nil]; return [self initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]] options:0 cache:nil cacheKey:nil progress:nil transform:nil completion:nil]; } - (instancetype)initWithRequest:(NSURLRequest *)request options:(YYWebImageOptions)options cache:(YYImageCache *)cache cacheKey:(NSString *)cacheKey progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { self = [super init]; if (!self) return nil; if (!request) return nil; _request = request; _options = options; _cache = cache; _cacheKey = cacheKey ? cacheKey : request.URL.absoluteString; _shouldUseCredentialStorage = YES; _progress = progress; _transform = transform; _completion = completion; _executing = NO; _finished = NO; _cancelled = NO; _taskID = UIBackgroundTaskInvalid; _lock = [NSRecursiveLock new]; return self; } - (void)dealloc { [_lock lock]; if (_taskID != UIBackgroundTaskInvalid) { [[UIApplication sharedExtensionApplication] endBackgroundTask:_taskID]; _taskID = UIBackgroundTaskInvalid; } if ([self isExecuting]) { self.cancelled = YES; self.finished = YES; if (_connection) { [_connection cancel]; if (![_request.URL isFileURL] && (_options & YYWebImageOptionShowNetworkActivity)) { [[UIApplication sharedExtensionApplication] decrementNetworkActivityCount]; } } if (_completion) { @autoreleasepool { _completion(nil, _request.URL, YYWebImageFromNone, YYWebImageStageCancelled, nil); } } } [_lock unlock]; } - (void)_endBackgroundTask { [_lock lock]; if (_taskID != UIBackgroundTaskInvalid) { [[UIApplication sharedExtensionApplication] endBackgroundTask:_taskID]; _taskID = UIBackgroundTaskInvalid; } [_lock unlock]; } #pragma mark - Runs in operation thread - (void)_finish { self.executing = NO; self.finished = YES; [self _endBackgroundTask]; } // runs on network thread - (void)_startOperation { if ([self isCancelled]) return; @autoreleasepool { // get image from cache if (_cache && !(_options & YYWebImageOptionUseNSURLCache) && !(_options & YYWebImageOptionRefreshImageCache)) { UIImage *image = [_cache getImageForKey:_cacheKey withType:YYImageCacheTypeMemory]; if (image) { [_lock lock]; if (![self isCancelled]) { if (_completion) _completion(image, _request.URL, YYWebImageFromMemoryCache, YYWebImageStageFinished, nil); } [self _finish]; [_lock unlock]; return; } if (!(_options & YYWebImageOptionIgnoreDiskCache)) { __weak typeof(self) _self = self; dispatch_async([self.class _imageQueue], ^{ __strong typeof(_self) self = _self; if (!self || [self isCancelled]) return; UIImage *image = [self.cache getImageForKey:self.cacheKey withType:YYImageCacheTypeDisk]; if (image) { [self.cache setImage:image imageData:nil forKey:self.cacheKey withType:YYImageCacheTypeMemory]; [self performSelector:@selector(_didReceiveImageFromDiskCache:) onThread:[self.class _networkThread] withObject:image waitUntilDone:NO]; } else { [self performSelector:@selector(_startRequest:) onThread:[self.class _networkThread] withObject:nil waitUntilDone:NO]; } }); return; } } } [self performSelector:@selector(_startRequest:) onThread:[self.class _networkThread] withObject:nil waitUntilDone:NO]; } // runs on network thread - (void)_startRequest:(id)object { if ([self isCancelled]) return; @autoreleasepool { if ((_options & YYWebImageOptionIgnoreFailedURL) && URLBlackListContains(_request.URL)) { NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:@{ NSLocalizedDescriptionKey : @"Failed to load URL, blacklisted." }]; [_lock lock]; if (![self isCancelled]) { if (_completion) _completion(nil, _request.URL, YYWebImageFromNone, YYWebImageStageFinished, error); } [self _finish]; [_lock unlock]; return; } if (_request.URL.isFileURL) { NSArray *keys = @[NSURLFileSizeKey]; NSDictionary *attr = [_request.URL resourceValuesForKeys:keys error:nil]; NSNumber *fileSize = attr[NSURLFileSizeKey]; _expectedSize = fileSize ? fileSize.unsignedIntegerValue : -1; } // request image from web [_lock lock]; if (![self isCancelled]) { _connection = [[NSURLConnection alloc] initWithRequest:_request delegate:[YYWeakProxy proxyWithTarget:self]]; if (![_request.URL isFileURL] && (_options & YYWebImageOptionShowNetworkActivity)) { [[UIApplication sharedExtensionApplication] incrementNetworkActivityCount]; } } [_lock unlock]; } } // runs on network thread, called from outer "cancel" - (void)_cancelOperation { @autoreleasepool { if (_connection) { if (![_request.URL isFileURL] && (_options & YYWebImageOptionShowNetworkActivity)) { [[UIApplication sharedExtensionApplication] decrementNetworkActivityCount]; } } [_connection cancel]; _connection = nil; if (_completion) _completion(nil, _request.URL, YYWebImageFromNone, YYWebImageStageCancelled, nil); [self _endBackgroundTask]; } } // runs on network thread - (void)_didReceiveImageFromDiskCache:(UIImage *)image { @autoreleasepool { [_lock lock]; if (![self isCancelled]) { if (image) { if (_completion) _completion(image, _request.URL, YYWebImageFromDiskCache, YYWebImageStageFinished, nil); [self _finish]; } else { [self _startRequest:nil]; } } [_lock unlock]; } } - (void)_didReceiveImageFromWeb:(UIImage *)image { @autoreleasepool { [_lock lock]; if (![self isCancelled]) { if (_cache) { if (image || (_options & YYWebImageOptionRefreshImageCache)) { NSData *data = _data; dispatch_async([YYWebImageOperation _imageQueue], ^{ [_cache setImage:image imageData:data forKey:_cacheKey withType:YYImageCacheTypeAll]; }); } } _data = nil; NSError *error = nil; if (!image) { error = [NSError errorWithDomain:@"com.ibireme.yykit.image" code:-1 userInfo:@{ NSLocalizedDescriptionKey : @"Web image decode fail." }]; if (_options & YYWebImageOptionIgnoreFailedURL) { if (URLBlackListContains(_request.URL)) { error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:@{ NSLocalizedDescriptionKey : @"Failed to load URL, blacklisted." }]; } else { URLInBlackListAdd(_request.URL); } } } if (_completion) _completion(image, _request.URL, YYWebImageFromRemote, YYWebImageStageFinished, error); [self _finish]; } [_lock unlock]; } } #pragma mark - NSURLConnectionDelegate runs in operation thread - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection { return _shouldUseCredentialStorage; } - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { @autoreleasepool { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if (!(_options & YYWebImageOptionAllowInvalidSSLCertificates) && [challenge.sender respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)]) { [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge]; } else { NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } } else { if ([challenge previousFailureCount] == 0) { if (_credential) { [[challenge sender] useCredential:_credential forAuthenticationChallenge:challenge]; } else { [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; } } else { [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; } } } } - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { if (!cachedResponse) return cachedResponse; if (_options & YYWebImageOptionUseNSURLCache) { return cachedResponse; } else { // ignore NSURLCache return nil; } } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { @autoreleasepool { NSError *error = nil; if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSHTTPURLResponse *httpResponse = (id) response; NSInteger statusCode = httpResponse.statusCode; if (statusCode >= 400 || statusCode == 304) { error = [NSError errorWithDomain:NSURLErrorDomain code:statusCode userInfo:nil]; } } if (error) { [_connection cancel]; [self connection:_connection didFailWithError:error]; } else { if (response.expectedContentLength) { _expectedSize = (NSInteger)response.expectedContentLength; if (_expectedSize < 0) _expectedSize = -1; } _data = [NSMutableData dataWithCapacity:_expectedSize > 0 ? _expectedSize : 0]; if (_progress) { [_lock lock]; if (![self isCancelled]) _progress(0, _expectedSize); [_lock unlock]; } } } } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { @autoreleasepool { [_lock lock]; BOOL canceled = [self isCancelled]; [_lock unlock]; if (canceled) return; if (data) [_data appendData:data]; if (_progress) { [_lock lock]; if (![self isCancelled]) { _progress(_data.length, _expectedSize); } [_lock unlock]; } /*--------------------------- progressive ----------------------------*/ BOOL progressive = (_options & YYWebImageOptionProgressive) > 0; BOOL progressiveBlur = (_options & YYWebImageOptionProgressiveBlur) > 0; if (!_completion || !(progressive || progressiveBlur)) return; if (data.length <= 16) return; if (_expectedSize > 0 && data.length >= _expectedSize * 0.99) return; if (_progressiveIgnored) return; NSTimeInterval min = progressiveBlur ? MIN_PROGRESSIVE_BLUR_TIME_INTERVAL : MIN_PROGRESSIVE_TIME_INTERVAL; NSTimeInterval now = CACurrentMediaTime(); if (now - _lastProgressiveDecodeTimestamp < min) return; if (!_progressiveDecoder) { _progressiveDecoder = [[YYImageDecoder alloc] initWithScale:[UIScreen mainScreen].scale]; } [_progressiveDecoder updateData:_data final:NO]; if ([self isCancelled]) return; if (_progressiveDecoder.type == YYImageTypeUnknown || _progressiveDecoder.type == YYImageTypeWebP || _progressiveDecoder.type == YYImageTypeOther) { _progressiveDecoder = nil; _progressiveIgnored = YES; return; } if (progressiveBlur) { // only support progressive JPEG and interlaced PNG if (_progressiveDecoder.type != YYImageTypeJPEG && _progressiveDecoder.type != YYImageTypePNG) { _progressiveDecoder = nil; _progressiveIgnored = YES; return; } } if (_progressiveDecoder.frameCount == 0) return; if (!progressiveBlur) { YYImageFrame *frame = [_progressiveDecoder frameAtIndex:0 decodeForDisplay:YES]; if (frame.image) { [_lock lock]; if (![self isCancelled]) { _completion(frame.image, _request.URL, YYWebImageFromRemote, YYWebImageStageProgress, nil); _lastProgressiveDecodeTimestamp = now; } [_lock unlock]; } return; } else { if (_progressiveDecoder.type == YYImageTypeJPEG) { if (!_progressiveDetected) { NSDictionary *dic = [_progressiveDecoder framePropertiesAtIndex:0]; NSDictionary *jpeg = dic[(id)kCGImagePropertyJFIFDictionary]; NSNumber *isProg = jpeg[(id)kCGImagePropertyJFIFIsProgressive]; if (!isProg.boolValue) { _progressiveIgnored = YES; _progressiveDecoder = nil; return; } _progressiveDetected = YES; } NSInteger scanLength = (NSInteger)_data.length - (NSInteger)_progressiveScanedLength - 4; if (scanLength <= 2) return; NSRange scanRange = NSMakeRange(_progressiveScanedLength, scanLength); NSRange markerRange = [_data rangeOfData:JPEGSOSMarker() options:kNilOptions range:scanRange]; _progressiveScanedLength = _data.length; if (markerRange.location == NSNotFound) return; if ([self isCancelled]) return; } else if (_progressiveDecoder.type == YYImageTypePNG) { if (!_progressiveDetected) { NSDictionary *dic = [_progressiveDecoder framePropertiesAtIndex:0]; NSDictionary *png = dic[(id)kCGImagePropertyPNGDictionary]; NSNumber *isProg = png[(id)kCGImagePropertyPNGInterlaceType]; if (!isProg.boolValue) { _progressiveIgnored = YES; _progressiveDecoder = nil; return; } _progressiveDetected = YES; } } YYImageFrame *frame = [_progressiveDecoder frameAtIndex:0 decodeForDisplay:YES]; UIImage *image = frame.image; if (!image) return; if ([self isCancelled]) return; if (!YYCGImageLastPixelFilled(image.CGImage)) return; _progressiveDisplayCount++; CGFloat radius = 32; if (_expectedSize > 0) { radius *= 1.0 / (3 * _data.length / (CGFloat)_expectedSize + 0.6) - 0.25; } else { radius /= (_progressiveDisplayCount); } image = [image imageByBlurRadius:radius tintColor:nil tintMode:0 saturation:1 maskImage:nil]; if (image) { [_lock lock]; if (![self isCancelled]) { _completion(image, _request.URL, YYWebImageFromRemote, YYWebImageStageProgress, nil); _lastProgressiveDecodeTimestamp = now; } [_lock unlock]; } } } } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { @autoreleasepool { [_lock lock]; _connection = nil; if (![self isCancelled]) { __weak typeof(self) _self = self; dispatch_async([self.class _imageQueue], ^{ __strong typeof(_self) self = _self; if (!self) return; BOOL shouldDecode = (self.options & YYWebImageOptionIgnoreImageDecoding) == 0; BOOL allowAnimation = (self.options & YYWebImageOptionIgnoreAnimatedImage) == 0; UIImage *image; BOOL hasAnimation = NO; if (allowAnimation) { image = [[YYImage alloc] initWithData:self.data scale:[UIScreen mainScreen].scale]; if (shouldDecode) image = [image imageByDecoded]; if ([((YYImage *)image) animatedImageFrameCount] > 1) { hasAnimation = YES; } } else { YYImageDecoder *decoder = [YYImageDecoder decoderWithData:self.data scale:[UIScreen mainScreen].scale]; image = [decoder frameAtIndex:0 decodeForDisplay:shouldDecode].image; } /* If the image has animation, save the original image data to disk cache. If the image is not PNG or JPEG, re-encode the image to PNG or JPEG for better decoding performance. */ YYImageType imageType = YYImageDetectType((__bridge CFDataRef)self.data); switch (imageType) { case YYImageTypeJPEG: case YYImageTypeGIF: case YYImageTypePNG: case YYImageTypeWebP: { // save to disk cache if (!hasAnimation) { if (imageType == YYImageTypeGIF || imageType == YYImageTypeWebP) { self.data = nil; // clear the data, re-encode for disk cache } } } break; default: { self.data = nil; // clear the data, re-encode for disk cache } break; } if ([self isCancelled]) return; if (self.transform && image) { UIImage *newImage = self.transform(image, self.request.URL); if (newImage != image) { self.data = nil; } image = newImage; if ([self isCancelled]) return; } [self performSelector:@selector(_didReceiveImageFromWeb:) onThread:[self.class _networkThread] withObject:image waitUntilDone:NO]; }); if (![self.request.URL isFileURL] && (self.options & YYWebImageOptionShowNetworkActivity)) { [[UIApplication sharedExtensionApplication] decrementNetworkActivityCount]; } } [_lock unlock]; } } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { @autoreleasepool { [_lock lock]; if (![self isCancelled]) { if (_completion) { _completion(nil, _request.URL, YYWebImageFromNone, YYWebImageStageFinished, error); } _connection = nil; _data = nil; if (![_request.URL isFileURL] && (_options & YYWebImageOptionShowNetworkActivity)) { [[UIApplication sharedExtensionApplication] decrementNetworkActivityCount]; } [self _finish]; if (_options & YYWebImageOptionIgnoreFailedURL) { if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut && error.code != NSURLErrorUserCancelledAuthentication) { URLInBlackListAdd(_request.URL); } } } [_lock unlock]; } } #pragma mark - Override NSOperation - (void)start { @autoreleasepool { [_lock lock]; self.started = YES; if ([self isCancelled]) { [self performSelector:@selector(_cancelOperation) onThread:[[self class] _networkThread] withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]]; self.finished = YES; } else if ([self isReady] && ![self isFinished] && ![self isExecuting]) { if (!_request) { self.finished = YES; if (_completion) { NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:@{NSLocalizedDescriptionKey:@"request in nil"}]; _completion(nil, _request.URL, YYWebImageFromNone, YYWebImageStageFinished, error); } } else { self.executing = YES; [self performSelector:@selector(_startOperation) onThread:[[self class] _networkThread] withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]]; if ((_options & YYWebImageOptionAllowBackgroundTask) && ![UIApplication isAppExtension]) { __weak __typeof__ (self) _self = self; if (_taskID == UIBackgroundTaskInvalid) { _taskID = [[UIApplication sharedExtensionApplication] beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof (_self) self = _self; if (self) { [self cancel]; self.finished = YES; } }]; } } } } [_lock unlock]; } } - (void)cancel { [_lock lock]; if (![self isCancelled]) { [super cancel]; self.cancelled = YES; if ([self isExecuting]) { self.executing = NO; [self performSelector:@selector(_cancelOperation) onThread:[[self class] _networkThread] withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]]; } if (self.started) { self.finished = YES; } } [_lock unlock]; } - (void)setExecuting:(BOOL)executing { [_lock lock]; if (_executing != executing) { [self willChangeValueForKey:@"isExecuting"]; _executing = executing; [self didChangeValueForKey:@"isExecuting"]; } [_lock unlock]; } - (BOOL)isExecuting { [_lock lock]; BOOL executing = _executing; [_lock unlock]; return executing; } - (void)setFinished:(BOOL)finished { [_lock lock]; if (_finished != finished) { [self willChangeValueForKey:@"isFinished"]; _finished = finished; [self didChangeValueForKey:@"isFinished"]; } [_lock unlock]; } - (BOOL)isFinished { [_lock lock]; BOOL finished = _finished; [_lock unlock]; return finished; } - (void)setCancelled:(BOOL)cancelled { [_lock lock]; if (_cancelled != cancelled) { [self willChangeValueForKey:@"isCancelled"]; _cancelled = cancelled; [self didChangeValueForKey:@"isCancelled"]; } [_lock unlock]; } - (BOOL)isCancelled { [_lock lock]; BOOL cancelled = _cancelled; [_lock unlock]; return cancelled; } - (BOOL)isConcurrent { return YES; } - (BOOL)isAsynchronous { return YES; } + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { if ([key isEqualToString:@"isExecuting"] || [key isEqualToString:@"isFinished"] || [key isEqualToString:@"isCancelled"]) { return NO; } return [super automaticallyNotifiesObserversForKey:key]; } - (NSString *)description { NSMutableString *string = [NSMutableString stringWithFormat:@"<%@: %p ",self.class, self]; [string appendFormat:@" executing:%@", [self isExecuting] ? @"YES" : @"NO"]; [string appendFormat:@" finished:%@", [self isFinished] ? @"YES" : @"NO"]; [string appendFormat:@" cancelled:%@", [self isCancelled] ? @"YES" : @"NO"]; [string appendString:@">"]; return string; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYWebImageOperation.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
6,541
```objective-c // // YYImageCache.h // YYKit <path_to_url // // Created by ibireme on 15/2/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> @class YYMemoryCache, YYDiskCache; NS_ASSUME_NONNULL_BEGIN /// Image cache type typedef NS_OPTIONS(NSUInteger, YYImageCacheType) { /// No value. YYImageCacheTypeNone = 0, /// Get/store image with memory cache. YYImageCacheTypeMemory = 1 << 0, /// Get/store image with disk cache. YYImageCacheTypeDisk = 1 << 1, /// Get/store image with both memory cache and disk cache. YYImageCacheTypeAll = YYImageCacheTypeMemory | YYImageCacheTypeDisk, }; /** YYImageCache is a cache that stores UIImage and image data based on memory cache and disk cache. @discussion The disk cache will try to protect the original image data: * If the original image is still image, it will be saved as png/jpeg file based on alpha information. * If the original image is animated gif, apng or webp, it will be saved as original format. * If the original image's scale is not 1, the scale value will be saved as extended data. Although UIImage can be serialized with NSCoding protocol, but it's not a good idea: Apple actually use UIImagePNGRepresentation() to encode all kind of image, it may lose the original multi-frame data. The result is packed to plist file and cannot view with photo viewer directly. If the image has no alpha channel, using JPEG instead of PNG can save more disk size and encoding/decoding time. */ @interface YYImageCache : NSObject #pragma mark - Attribute ///============================================================================= /// @name Attribute ///============================================================================= /** The name of the cache. Default is nil. */ @property (nullable, copy) NSString *name; /** The underlying memory cache. see `YYMemoryCache` for more information.*/ @property (strong, readonly) YYMemoryCache *memoryCache; /** The underlying disk cache. see `YYDiskCache` for more information.*/ @property (strong, readonly) YYDiskCache *diskCache; /** Whether decode animated image when fetch image from disk cache. Default is YES. @discussion When fetch image from disk cache, it will use 'YYImage' to decode animated image such as WebP/APNG/GIF. Set to 'NO' to ignore animated image. */ @property BOOL allowAnimatedImage; /** Whether decode the image to memory bitmap. Default is YES. @discussion If the value is YES, then the image will be decoded to memory bitmap for better display performance, but may cost more memory. */ @property BOOL decodeForDisplay; #pragma mark - Initializer ///============================================================================= /// @name Initializer ///============================================================================= - (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)new UNAVAILABLE_ATTRIBUTE; /** Returns global shared image cache instance. @return The singleton YYImageCache instance. */ + (instancetype)sharedCache; /** The designated initializer. Multiple instances with the same path will make the cache unstable. @param path Full path of a directory in which the cache will write data. Once initialized you should not read and write to this directory. @result A new cache object, or nil if an error occurs. */ - (nullable instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER; #pragma mark - Access Methods ///============================================================================= /// @name Access Methods ///============================================================================= /** Sets the image with the specified key in the cache (both memory and disk). This method returns immediately and executes the store operation in background. @param image The image to be stored in the cache. If nil, this method has no effect. @param key The key with which to associate the image. If nil, this method has no effect. */ - (void)setImage:(UIImage *)image forKey:(NSString *)key; /** Sets the image with the specified key in the cache. This method returns immediately and executes the store operation in background. @discussion If the `type` contain `YYImageCacheTypeMemory`, then the `image` will be stored in the memory cache; `imageData` will be used instead if `image` is nil. If the `type` contain `YYImageCacheTypeDisk`, then the `imageData` will be stored in the disk cache; `image` will be used instead if `imageData` is nil. @param image The image to be stored in the cache. @param imageData The image data to be stored in the cache. @param key The key with which to associate the image. If nil, this method has no effect. @param type The cache type to store image. */ - (void)setImage:(nullable UIImage *)image imageData:(nullable NSData *)imageData forKey:(NSString *)key withType:(YYImageCacheType)type; /** Removes the image of the specified key in the cache (both memory and disk). This method returns immediately and executes the remove operation in background. @param key The key identifying the image to be removed. If nil, this method has no effect. */ - (void)removeImageForKey:(NSString *)key; /** Removes the image of the specified key in the cache. This method returns immediately and executes the remove operation in background. @param key The key identifying the image to be removed. If nil, this method has no effect. @param type The cache type to remove image. */ - (void)removeImageForKey:(NSString *)key withType:(YYImageCacheType)type; /** Returns a Boolean value that indicates whether a given key is in cache. If the image is not in memory, this method may blocks the calling thread until file read finished. @param key A string identifying the image. If nil, just return NO. @return Whether the image is in cache. */ - (BOOL)containsImageForKey:(NSString *)key; /** Returns a Boolean value that indicates whether a given key is in cache. If the image is not in memory and the `type` contains `YYImageCacheTypeDisk`, this method may blocks the calling thread until file read finished. @param key A string identifying the image. If nil, just return NO. @param type The cache type. @return Whether the image is in cache. */ - (BOOL)containsImageForKey:(NSString *)key withType:(YYImageCacheType)type; /** Returns the image associated with a given key. If the image is not in memory, this method may blocks the calling thread until file read finished. @param key A string identifying the image. If nil, just return nil. @return The image associated with key, or nil if no image is associated with key. */ - (nullable UIImage *)getImageForKey:(NSString *)key; /** Returns the image associated with a given key. If the image is not in memory and the `type` contains `YYImageCacheTypeDisk`, this method may blocks the calling thread until file read finished. @param key A string identifying the image. If nil, just return nil. @return The image associated with key, or nil if no image is associated with key. */ - (nullable UIImage *)getImageForKey:(NSString *)key withType:(YYImageCacheType)type; /** Asynchronously get the image associated with a given key. @param key A string identifying the image. If nil, just return nil. @param type The cache type. @param block A completion block which will be called on main thread. */ - (void)getImageForKey:(NSString *)key withType:(YYImageCacheType)type withBlock:(void(^)(UIImage * _Nullable image, YYImageCacheType type))block; /** Returns the image data associated with a given key. This method may blocks the calling thread until file read finished. @param key A string identifying the image. If nil, just return nil. @return The image data associated with key, or nil if no image is associated with key. */ - (nullable NSData *)getImageDataForKey:(NSString *)key; /** Asynchronously get the image data associated with a given key. @param key A string identifying the image. If nil, just return nil. @param block A completion block which will be called on main thread. */ - (void)getImageDataForKey:(NSString *)key withBlock:(void(^)(NSData * _Nullable imageData))block; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYImageCache.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,812
```objective-c // // YYImageCache.m // YYKit <path_to_url // // Created by ibireme on 15/2/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYImageCache.h" #import "YYMemoryCache.h" #import "YYDiskCache.h" #import "UIImage+YYAdd.h" #import "NSObject+YYAdd.h" #import "YYImage.h" #if __has_include("YYDispatchQueuePool.h") #import "YYDispatchQueuePool.h" #endif static inline dispatch_queue_t YYImageCacheIOQueue() { #ifdef YYDispatchQueuePool_h return YYDispatchQueueGetForQOS(NSQualityOfServiceDefault); #else return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); #endif } static inline dispatch_queue_t YYImageCacheDecodeQueue() { #ifdef YYDispatchQueuePool_h return YYDispatchQueueGetForQOS(NSQualityOfServiceUtility); #else return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0); #endif } @interface YYImageCache () - (NSUInteger)imageCost:(UIImage *)image; - (UIImage *)imageFromData:(NSData *)data; @end @implementation YYImageCache - (NSUInteger)imageCost:(UIImage *)image { CGImageRef cgImage = image.CGImage; if (!cgImage) return 1; CGFloat height = CGImageGetHeight(cgImage); size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); NSUInteger cost = bytesPerRow * height; if (cost == 0) cost = 1; return cost; } - (UIImage *)imageFromData:(NSData *)data { NSData *scaleData = [YYDiskCache getExtendedDataFromObject:data]; CGFloat scale = 0; if (scaleData) { scale = ((NSNumber *)[NSKeyedUnarchiver unarchiveObjectWithData:scaleData]).doubleValue; } if (scale <= 0) scale = [UIScreen mainScreen].scale; UIImage *image; if (_allowAnimatedImage) { image = [[YYImage alloc] initWithData:data scale:scale]; if (_decodeForDisplay) image = [image imageByDecoded]; } else { YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:scale]; image = [decoder frameAtIndex:0 decodeForDisplay:_decodeForDisplay].image; } return image; } #pragma mark Public + (instancetype)sharedCache { static YYImageCache *cache = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; cachePath = [cachePath stringByAppendingPathComponent:@"com.ibireme.yykit"]; cachePath = [cachePath stringByAppendingPathComponent:@"images"]; cache = [[self alloc] initWithPath:cachePath]; }); return cache; } - (instancetype)init { @throw [NSException exceptionWithName:@"YYImageCache init error" reason:@"YYImageCache must be initialized with a path. Use 'initWithPath:' instead." userInfo:nil]; return [self initWithPath:@""]; } - (instancetype)initWithPath:(NSString *)path { YYMemoryCache *memoryCache = [YYMemoryCache new]; memoryCache.shouldRemoveAllObjectsOnMemoryWarning = YES; memoryCache.shouldRemoveAllObjectsWhenEnteringBackground = YES; memoryCache.countLimit = NSUIntegerMax; memoryCache.costLimit = NSUIntegerMax; memoryCache.ageLimit = 12 * 60 * 60; YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:path]; diskCache.customArchiveBlock = ^(id object) { return (NSData *)object; }; diskCache.customUnarchiveBlock = ^(NSData *data) { return (id)data; }; if (!memoryCache || !diskCache) return nil; self = [super init]; _memoryCache = memoryCache; _diskCache = diskCache; _allowAnimatedImage = YES; _decodeForDisplay = YES; return self; } - (void)setImage:(UIImage *)image forKey:(NSString *)key { [self setImage:image imageData:nil forKey:key withType:YYImageCacheTypeAll]; } - (void)setImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key withType:(YYImageCacheType)type { if (!key || (image == nil && imageData.length == 0)) return; __weak typeof(self) _self = self; if (type & YYImageCacheTypeMemory) { // add to memory cache if (image) { if (image.isDecodedForDisplay) { [_memoryCache setObject:image forKey:key withCost:[_self imageCost:image]]; } else { dispatch_async(YYImageCacheDecodeQueue(), ^{ __strong typeof(_self) self = _self; if (!self) return; [self.memoryCache setObject:[image imageByDecoded] forKey:key withCost:[self imageCost:image]]; }); } } else if (imageData) { dispatch_async(YYImageCacheDecodeQueue(), ^{ __strong typeof(_self) self = _self; if (!self) return; UIImage *newImage = [self imageFromData:imageData]; [self.memoryCache setObject:newImage forKey:key withCost:[self imageCost:newImage]]; }); } } if (type & YYImageCacheTypeDisk) { // add to disk cache if (imageData) { if (image) { [YYDiskCache setExtendedData:[NSKeyedArchiver archivedDataWithRootObject:@(image.scale)] toObject:imageData]; } [_diskCache setObject:imageData forKey:key]; } else if (image) { dispatch_async(YYImageCacheIOQueue(), ^{ __strong typeof(_self) self = _self; if (!self) return; NSData *data = [image imageDataRepresentation]; [YYDiskCache setExtendedData:[NSKeyedArchiver archivedDataWithRootObject:@(image.scale)] toObject:data]; [self.diskCache setObject:data forKey:key]; }); } } } - (void)removeImageForKey:(NSString *)key { [self removeImageForKey:key withType:YYImageCacheTypeAll]; } - (void)removeImageForKey:(NSString *)key withType:(YYImageCacheType)type { if (type & YYImageCacheTypeMemory) [_memoryCache removeObjectForKey:key]; if (type & YYImageCacheTypeDisk) [_diskCache removeObjectForKey:key]; } - (BOOL)containsImageForKey:(NSString *)key { return [self containsImageForKey:key withType:YYImageCacheTypeAll]; } - (BOOL)containsImageForKey:(NSString *)key withType:(YYImageCacheType)type { if (type & YYImageCacheTypeMemory) { if ([_memoryCache containsObjectForKey:key]) return YES; } if (type & YYImageCacheTypeDisk) { if ([_diskCache containsObjectForKey:key]) return YES; } return NO; } - (UIImage *)getImageForKey:(NSString *)key { return [self getImageForKey:key withType:YYImageCacheTypeAll]; } - (UIImage *)getImageForKey:(NSString *)key withType:(YYImageCacheType)type { if (!key) return nil; if (type & YYImageCacheTypeMemory) { UIImage *image = [_memoryCache objectForKey:key]; if (image) return image; } if (type & YYImageCacheTypeDisk) { NSData *data = (id)[_diskCache objectForKey:key]; UIImage *image = [self imageFromData:data]; if (image && (type & YYImageCacheTypeMemory)) { [_memoryCache setObject:image forKey:key withCost:[self imageCost:image]]; } return image; } return nil; } - (void)getImageForKey:(NSString *)key withType:(YYImageCacheType)type withBlock:(void (^)(UIImage *image, YYImageCacheType type))block { if (!block) return; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage *image = nil; if (type & YYImageCacheTypeMemory) { image = [_memoryCache objectForKey:key]; if (image) { dispatch_async(dispatch_get_main_queue(), ^{ block(image, YYImageCacheTypeMemory); }); return; } } if (type & YYImageCacheTypeDisk) { NSData *data = (id)[_diskCache objectForKey:key]; image = [self imageFromData:data]; if (image) { [_memoryCache setObject:image forKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ block(image, YYImageCacheTypeDisk); }); return; } } dispatch_async(dispatch_get_main_queue(), ^{ block(nil, YYImageCacheTypeNone); }); }); } - (NSData *)getImageDataForKey:(NSString *)key { return (id)[_diskCache objectForKey:key]; } - (void)getImageDataForKey:(NSString *)key withBlock:(void (^)(NSData *imageData))block { if (!block) return; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *data = (id)[_diskCache objectForKey:key]; dispatch_async(dispatch_get_main_queue(), ^{ block(data); }); }); } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYImageCache.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,053
```objective-c // // YYImage.h // YYKit <path_to_url // // Created by ibireme on 14/10/20. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYAnimatedImageView.h> #import <YYKit/YYImageCoder.h> #else #import "YYAnimatedImageView.h" #import "YYImageCoder.h" #endif NS_ASSUME_NONNULL_BEGIN /** A YYImage object is a high-level way to display animated image data. @discussion It is a fully compatible `UIImage` subclass. It extends the UIImage to support animated WebP, APNG and GIF format image data decoding. It also support NSCoding protocol to archive and unarchive multi-frame image data. If the image is created from multi-frame image data, and you want to play the animation, try replace UIImageView with `YYAnimatedImageView`. Sample Code: // animation@3x.webp YYImage *image = [YYImage imageNamed:@"animation.webp"]; YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image]; [view addSubView:imageView]; */ @interface YYImage : UIImage <YYAnimatedImage> + (nullable YYImage *)imageNamed:(NSString *)name; // no cache! + (nullable YYImage *)imageWithContentsOfFile:(NSString *)path; + (nullable YYImage *)imageWithData:(NSData *)data; + (nullable YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale; /** If the image is created from data or file, then the value indicates the data type. */ @property (nonatomic, readonly) YYImageType animatedImageType; /** If the image is created from animated image data (multi-frame GIF/APNG/WebP), this property stores the original image data. */ @property (nullable, nonatomic, readonly) NSData *animatedImageData; /** The total memory usage (in bytes) if all frame images was loaded into memory. The value is 0 if the image is not created from a multi-frame image data. */ @property (nonatomic, readonly) NSUInteger animatedImageMemorySize; /** Preload all frame image to memory. @discussion Set this property to `YES` will block the calling thread to decode all animation frame image to memory, set to `NO` will release the preloaded frames. If the image is shared by lots of image views (such as emoticon), preload all frames will reduce the CPU cost. See `animatedImageMemorySize` for memory cost. */ @property (nonatomic) BOOL preloadAllAnimatedImageFrames; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYImage.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
577
```objective-c // // YYImageCoder.m // YYKit <path_to_url // // Created by ibireme on 15/5/13. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYImageCoder.h" #import <CoreFoundation/CoreFoundation.h> #import <ImageIO/ImageIO.h> #import <Accelerate/Accelerate.h> #import <QuartzCore/QuartzCore.h> #import <MobileCoreServices/MobileCoreServices.h> #import <AssetsLibrary/AssetsLibrary.h> #import <objc/runtime.h> #import <pthread.h> #import <zlib.h> #import "YYImage.h" #import "YYKitMacro.h" #ifndef YYIMAGE_WEBP_ENABLED #if __has_include(<webp/decode.h>) && __has_include(<webp/encode.h>) && \ __has_include(<webp/demux.h>) && __has_include(<webp/mux.h>) #define YYIMAGE_WEBP_ENABLED 1 #import <webp/decode.h> #import <webp/encode.h> #import <webp/demux.h> #import <webp/mux.h> #elif __has_include("webp/decode.h") && __has_include("webp/encode.h") && \ __has_include("webp/demux.h") && __has_include("webp/mux.h") #define YYIMAGE_WEBP_ENABLED 1 #import "webp/decode.h" #import "webp/encode.h" #import "webp/demux.h" #import "webp/mux.h" #else #define YYIMAGE_WEBP_ENABLED 0 #endif #endif //////////////////////////////////////////////////////////////////////////////// #pragma mark - Utility (for little endian platform) #define YY_FOUR_CC(c1,c2,c3,c4) ((uint32_t)(((c4) << 24) | ((c3) << 16) | ((c2) << 8) | (c1))) #define YY_TWO_CC(c1,c2) ((uint16_t)(((c2) << 8) | (c1))) static inline uint16_t yy_swap_endian_uint16(uint16_t value) { return (uint16_t) ((value & 0x00FF) << 8) | (uint16_t) ((value & 0xFF00) >> 8) ; } static inline uint32_t yy_swap_endian_uint32(uint32_t value) { return (uint32_t)((value & 0x000000FFU) << 24) | (uint32_t)((value & 0x0000FF00U) << 8) | (uint32_t)((value & 0x00FF0000U) >> 8) | (uint32_t)((value & 0xFF000000U) >> 24) ; } //////////////////////////////////////////////////////////////////////////////// #pragma mark - APNG /* PNG spec: path_to_url APNG spec: path_to_url =============================================================================== PNG format: header (8): 89 50 4e 47 0d 0a 1a 0a chunk, chunk, chunk, ... =============================================================================== chunk format: length (4): uint32_t big endian fourcc (4): chunk type code data (length): data crc32 (4): uint32_t big endian crc32(fourcc + data) =============================================================================== PNG chunk define: IHDR (Image Header) required, must appear first, 13 bytes width (4) pixel count, should not be zero height (4) pixel count, should not be zero bit depth (1) expected: 1, 2, 4, 8, 16 color type (1) 1<<0 (palette used), 1<<1 (color used), 1<<2 (alpha channel used) compression method (1) 0 (deflate/inflate) filter method (1) 0 (adaptive filtering with five basic filter types) interlace method (1) 0 (no interlace) or 1 (Adam7 interlace) IDAT (Image Data) required, must appear consecutively if there's multiple 'IDAT' chunk IEND (End) required, must appear last, 0 bytes =============================================================================== APNG chunk define: acTL (Animation Control) required, must appear before 'IDAT', 8 bytes num frames (4) number of frames num plays (4) number of times to loop, 0 indicates infinite looping fcTL (Frame Control) required, must appear before the 'IDAT' or 'fdAT' chunks of the frame to which it applies, 26 bytes sequence number (4) sequence number of the animation chunk, starting from 0 width (4) width of the following frame height (4) height of the following frame x offset (4) x position at which to render the following frame y offset (4) y position at which to render the following frame delay num (2) frame delay fraction numerator delay den (2) frame delay fraction denominator dispose op (1) type of frame area disposal to be done after rendering this frame (0:none, 1:background 2:previous) blend op (1) type of frame area rendering for this frame (0:source, 1:over) fdAT (Frame Data) required sequence number (4) sequence number of the animation chunk frame data (x) frame data for this frame (same as 'IDAT') =============================================================================== `dispose_op` specifies how the output buffer should be changed at the end of the delay (before rendering the next frame). * NONE: no disposal is done on this frame before rendering the next; the contents of the output buffer are left as is. * BACKGROUND: the frame's region of the output buffer is to be cleared to fully transparent black before rendering the next frame. * PREVIOUS: the frame's region of the output buffer is to be reverted to the previous contents before rendering the next frame. `blend_op` specifies whether the frame is to be alpha blended into the current output buffer content, or whether it should completely replace its region in the output buffer. * SOURCE: all color components of the frame, including alpha, overwrite the current contents of the frame's output buffer region. * OVER: the frame should be composited onto the output buffer based on its alpha, using a simple OVER operation as described in the "Alpha Channel Processing" section of the PNG specification */ typedef enum { YY_PNG_ALPHA_TYPE_PALEETE = 1 << 0, YY_PNG_ALPHA_TYPE_COLOR = 1 << 1, YY_PNG_ALPHA_TYPE_ALPHA = 1 << 2, } yy_png_alpha_type; typedef enum { YY_PNG_DISPOSE_OP_NONE = 0, YY_PNG_DISPOSE_OP_BACKGROUND = 1, YY_PNG_DISPOSE_OP_PREVIOUS = 2, } yy_png_dispose_op; typedef enum { YY_PNG_BLEND_OP_SOURCE = 0, YY_PNG_BLEND_OP_OVER = 1, } yy_png_blend_op; typedef struct { uint32_t width; ///< pixel count, should not be zero uint32_t height; ///< pixel count, should not be zero uint8_t bit_depth; ///< expected: 1, 2, 4, 8, 16 uint8_t color_type; ///< see yy_png_alpha_type uint8_t compression_method; ///< 0 (deflate/inflate) uint8_t filter_method; ///< 0 (adaptive filtering with five basic filter types) uint8_t interlace_method; ///< 0 (no interlace) or 1 (Adam7 interlace) } yy_png_chunk_IHDR; typedef struct { uint32_t sequence_number; ///< sequence number of the animation chunk, starting from 0 uint32_t width; ///< width of the following frame uint32_t height; ///< height of the following frame uint32_t x_offset; ///< x position at which to render the following frame uint32_t y_offset; ///< y position at which to render the following frame uint16_t delay_num; ///< frame delay fraction numerator uint16_t delay_den; ///< frame delay fraction denominator uint8_t dispose_op; ///< see yy_png_dispose_op uint8_t blend_op; ///< see yy_png_blend_op } yy_png_chunk_fcTL; typedef struct { uint32_t offset; ///< chunk offset in PNG data uint32_t fourcc; ///< chunk fourcc uint32_t length; ///< chunk data length uint32_t crc32; ///< chunk crc32 } yy_png_chunk_info; typedef struct { uint32_t chunk_index; ///< the first `fdAT`/`IDAT` chunk index uint32_t chunk_num; ///< the `fdAT`/`IDAT` chunk count uint32_t chunk_size; ///< the `fdAT`/`IDAT` chunk bytes yy_png_chunk_fcTL frame_control; } yy_png_frame_info; typedef struct { yy_png_chunk_IHDR header; ///< png header yy_png_chunk_info *chunks; ///< chunks uint32_t chunk_num; ///< count of chunks yy_png_frame_info *apng_frames; ///< frame info, NULL if not apng uint32_t apng_frame_num; ///< 0 if not apng uint32_t apng_loop_num; ///< 0 indicates infinite looping uint32_t *apng_shared_chunk_indexs; ///< shared chunk index uint32_t apng_shared_chunk_num; ///< shared chunk count uint32_t apng_shared_chunk_size; ///< shared chunk bytes uint32_t apng_shared_insert_index; ///< shared chunk insert index bool apng_first_frame_is_cover; ///< the first frame is same as png (cover) } yy_png_info; static void yy_png_chunk_IHDR_read(yy_png_chunk_IHDR *IHDR, const uint8_t *data) { IHDR->width = yy_swap_endian_uint32(*((uint32_t *)(data))); IHDR->height = yy_swap_endian_uint32(*((uint32_t *)(data + 4))); IHDR->bit_depth = data[8]; IHDR->color_type = data[9]; IHDR->compression_method = data[10]; IHDR->filter_method = data[11]; IHDR->interlace_method = data[12]; } static void yy_png_chunk_IHDR_write(yy_png_chunk_IHDR *IHDR, uint8_t *data) { *((uint32_t *)(data)) = yy_swap_endian_uint32(IHDR->width); *((uint32_t *)(data + 4)) = yy_swap_endian_uint32(IHDR->height); data[8] = IHDR->bit_depth; data[9] = IHDR->color_type; data[10] = IHDR->compression_method; data[11] = IHDR->filter_method; data[12] = IHDR->interlace_method; } static void yy_png_chunk_fcTL_read(yy_png_chunk_fcTL *fcTL, const uint8_t *data) { fcTL->sequence_number = yy_swap_endian_uint32(*((uint32_t *)(data))); fcTL->width = yy_swap_endian_uint32(*((uint32_t *)(data + 4))); fcTL->height = yy_swap_endian_uint32(*((uint32_t *)(data + 8))); fcTL->x_offset = yy_swap_endian_uint32(*((uint32_t *)(data + 12))); fcTL->y_offset = yy_swap_endian_uint32(*((uint32_t *)(data + 16))); fcTL->delay_num = yy_swap_endian_uint16(*((uint16_t *)(data + 20))); fcTL->delay_den = yy_swap_endian_uint16(*((uint16_t *)(data + 22))); fcTL->dispose_op = data[24]; fcTL->blend_op = data[25]; } static void yy_png_chunk_fcTL_write(yy_png_chunk_fcTL *fcTL, uint8_t *data) { *((uint32_t *)(data)) = yy_swap_endian_uint32(fcTL->sequence_number); *((uint32_t *)(data + 4)) = yy_swap_endian_uint32(fcTL->width); *((uint32_t *)(data + 8)) = yy_swap_endian_uint32(fcTL->height); *((uint32_t *)(data + 12)) = yy_swap_endian_uint32(fcTL->x_offset); *((uint32_t *)(data + 16)) = yy_swap_endian_uint32(fcTL->y_offset); *((uint16_t *)(data + 20)) = yy_swap_endian_uint16(fcTL->delay_num); *((uint16_t *)(data + 22)) = yy_swap_endian_uint16(fcTL->delay_den); data[24] = fcTL->dispose_op; data[25] = fcTL->blend_op; } // convert double value to fraction static void yy_png_delay_to_fraction(double duration, uint16_t *num, uint16_t *den) { if (duration >= 0xFF) { *num = 0xFF; *den = 1; } else if (duration <= 1.0 / (double)0xFF) { *num = 1; *den = 0xFF; } else { // Use continued fraction to calculate the num and den. long MAX = 10; double eps = (0.5 / (double)0xFF); long p[MAX], q[MAX], a[MAX], i, numl = 0, denl = 0; // The first two convergents are 0/1 and 1/0 p[0] = 0; q[0] = 1; p[1] = 1; q[1] = 0; // The rest of the convergents (and continued fraction) for (i = 2; i < MAX; i++) { a[i] = lrint(floor(duration)); p[i] = a[i] * p[i - 1] + p[i - 2]; q[i] = a[i] * q[i - 1] + q[i - 2]; if (p[i] <= 0xFF && q[i] <= 0xFF) { // uint16_t numl = p[i]; denl = q[i]; } else break; if (fabs(duration - a[i]) < eps) break; duration = 1.0 / (duration - a[i]); } if (numl != 0 && denl != 0) { *num = numl; *den = denl; } else { *num = 1; *den = 100; } } } // convert fraction to double value static double yy_png_delay_to_seconds(uint16_t num, uint16_t den) { if (den == 0) { return num / 100.0; } else { return (double)num / (double)den; } } static bool yy_png_validate_animation_chunk_order(yy_png_chunk_info *chunks, /* input */ uint32_t chunk_num, /* input */ uint32_t *first_idat_index, /* output */ bool *first_frame_is_cover /* output */) { /* PNG at least contains 3 chunks: IHDR, IDAT, IEND. `IHDR` must appear first. `IDAT` must appear consecutively. `IEND` must appear end. APNG must contains one `acTL` and at least one 'fcTL' and `fdAT`. `fdAT` must appear consecutively. `fcTL` must appear before `IDAT` or `fdAT`. */ if (chunk_num <= 2) return false; if (chunks->fourcc != YY_FOUR_CC('I', 'H', 'D', 'R')) return false; if ((chunks + chunk_num - 1)->fourcc != YY_FOUR_CC('I', 'E', 'N', 'D')) return false; uint32_t prev_fourcc = 0; uint32_t IHDR_num = 0; uint32_t IDAT_num = 0; uint32_t acTL_num = 0; uint32_t fcTL_num = 0; uint32_t first_IDAT = 0; bool first_frame_cover = false; for (uint32_t i = 0; i < chunk_num; i++) { yy_png_chunk_info *chunk = chunks + i; switch (chunk->fourcc) { case YY_FOUR_CC('I', 'H', 'D', 'R'): { // png header if (i != 0) return false; if (IHDR_num > 0) return false; IHDR_num++; } break; case YY_FOUR_CC('I', 'D', 'A', 'T'): { // png data if (prev_fourcc != YY_FOUR_CC('I', 'D', 'A', 'T')) { if (IDAT_num == 0) first_IDAT = i; else return false; } IDAT_num++; } break; case YY_FOUR_CC('a', 'c', 'T', 'L'): { // apng control if (acTL_num > 0) return false; acTL_num++; } break; case YY_FOUR_CC('f', 'c', 'T', 'L'): { // apng frame control if (i + 1 == chunk_num) return false; if ((chunk + 1)->fourcc != YY_FOUR_CC('f', 'd', 'A', 'T') && (chunk + 1)->fourcc != YY_FOUR_CC('I', 'D', 'A', 'T')) { return false; } if (fcTL_num == 0) { if ((chunk + 1)->fourcc == YY_FOUR_CC('I', 'D', 'A', 'T')) { first_frame_cover = true; } } fcTL_num++; } break; case YY_FOUR_CC('f', 'd', 'A', 'T'): { // apng data if (prev_fourcc != YY_FOUR_CC('f', 'd', 'A', 'T') && prev_fourcc != YY_FOUR_CC('f', 'c', 'T', 'L')) { return false; } } break; } prev_fourcc = chunk->fourcc; } if (IHDR_num != 1) return false; if (IDAT_num == 0) return false; if (acTL_num != 1) return false; if (fcTL_num < acTL_num) return false; *first_idat_index = first_IDAT; *first_frame_is_cover = first_frame_cover; return true; } static void yy_png_info_release(yy_png_info *info) { if (info) { if (info->chunks) free(info->chunks); if (info->apng_frames) free(info->apng_frames); if (info->apng_shared_chunk_indexs) free(info->apng_shared_chunk_indexs); free(info); } } /** Create a png info from a png file. See struct png_info for more information. @param data png/apng file data. @param length the data's length in bytes. @return A png info object, you may call yy_png_info_release() to release it. Returns NULL if an error occurs. */ static yy_png_info *yy_png_info_create(const uint8_t *data, uint32_t length) { if (length < 32) return NULL; if (*((uint32_t *)data) != YY_FOUR_CC(0x89, 0x50, 0x4E, 0x47)) return NULL; if (*((uint32_t *)(data + 4)) != YY_FOUR_CC(0x0D, 0x0A, 0x1A, 0x0A)) return NULL; uint32_t chunk_realloc_num = 16; yy_png_chunk_info *chunks = malloc(sizeof(yy_png_chunk_info) * chunk_realloc_num); if (!chunks) return NULL; // parse png chunks uint32_t offset = 8; uint32_t chunk_num = 0; uint32_t chunk_capacity = chunk_realloc_num; uint32_t apng_loop_num = 0; int32_t apng_sequence_index = -1; int32_t apng_frame_index = 0; int32_t apng_frame_number = -1; bool apng_chunk_error = false; do { if (chunk_num >= chunk_capacity) { yy_png_chunk_info *new_chunks = realloc(chunks, sizeof(yy_png_chunk_info) * (chunk_capacity + chunk_realloc_num)); if (!new_chunks) { free(chunks); return NULL; } chunks = new_chunks; chunk_capacity += chunk_realloc_num; } yy_png_chunk_info *chunk = chunks + chunk_num; const uint8_t *chunk_data = data + offset; chunk->offset = offset; chunk->length = yy_swap_endian_uint32(*((uint32_t *)chunk_data)); if ((uint64_t)chunk->offset + (uint64_t)chunk->length + 12 > length) { free(chunks); return NULL; } chunk->fourcc = *((uint32_t *)(chunk_data + 4)); if ((uint64_t)chunk->offset + 4 + chunk->length + 4 > (uint64_t)length) break; chunk->crc32 = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 8 + chunk->length))); chunk_num++; offset += 12 + chunk->length; switch (chunk->fourcc) { case YY_FOUR_CC('a', 'c', 'T', 'L') : { if (chunk->length == 8) { apng_frame_number = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 8))); apng_loop_num = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 12))); } else { apng_chunk_error = true; } } break; case YY_FOUR_CC('f', 'c', 'T', 'L') : case YY_FOUR_CC('f', 'd', 'A', 'T') : { if (chunk->fourcc == YY_FOUR_CC('f', 'c', 'T', 'L')) { if (chunk->length != 26) { apng_chunk_error = true; } else { apng_frame_index++; } } if (chunk->length > 4) { uint32_t sequence = yy_swap_endian_uint32(*((uint32_t *)(chunk_data + 8))); if (apng_sequence_index + 1 == sequence) { apng_sequence_index++; } else { apng_chunk_error = true; } } else { apng_chunk_error = true; } } break; case YY_FOUR_CC('I', 'E', 'N', 'D') : { offset = length; // end, break do-while loop } break; } } while (offset + 12 <= length); if (chunk_num < 3 || chunks->fourcc != YY_FOUR_CC('I', 'H', 'D', 'R') || chunks->length != 13) { free(chunks); return NULL; } // png info yy_png_info *info = calloc(1, sizeof(yy_png_info)); if (!info) { free(chunks); return NULL; } info->chunks = chunks; info->chunk_num = chunk_num; yy_png_chunk_IHDR_read(&info->header, data + chunks->offset + 8); // apng info if (!apng_chunk_error && apng_frame_number == apng_frame_index && apng_frame_number >= 1) { bool first_frame_is_cover = false; uint32_t first_IDAT_index = 0; if (!yy_png_validate_animation_chunk_order(info->chunks, info->chunk_num, &first_IDAT_index, &first_frame_is_cover)) { return info; // ignore apng chunk } info->apng_loop_num = apng_loop_num; info->apng_frame_num = apng_frame_number; info->apng_first_frame_is_cover = first_frame_is_cover; info->apng_shared_insert_index = first_IDAT_index; info->apng_frames = calloc(apng_frame_number, sizeof(yy_png_frame_info)); if (!info->apng_frames) { yy_png_info_release(info); return NULL; } info->apng_shared_chunk_indexs = calloc(info->chunk_num, sizeof(uint32_t)); if (!info->apng_shared_chunk_indexs) { yy_png_info_release(info); return NULL; } int32_t frame_index = -1; uint32_t *shared_chunk_index = info->apng_shared_chunk_indexs; for (int32_t i = 0; i < info->chunk_num; i++) { yy_png_chunk_info *chunk = info->chunks + i; switch (chunk->fourcc) { case YY_FOUR_CC('I', 'D', 'A', 'T'): { if (info->apng_shared_insert_index == 0) { info->apng_shared_insert_index = i; } if (first_frame_is_cover) { yy_png_frame_info *frame = info->apng_frames + frame_index; frame->chunk_num++; frame->chunk_size += chunk->length + 12; } } break; case YY_FOUR_CC('a', 'c', 'T', 'L'): { } break; case YY_FOUR_CC('f', 'c', 'T', 'L'): { frame_index++; yy_png_frame_info *frame = info->apng_frames + frame_index; frame->chunk_index = i + 1; yy_png_chunk_fcTL_read(&frame->frame_control, data + chunk->offset + 8); } break; case YY_FOUR_CC('f', 'd', 'A', 'T'): { yy_png_frame_info *frame = info->apng_frames + frame_index; frame->chunk_num++; frame->chunk_size += chunk->length + 12; } break; default: { *shared_chunk_index = i; shared_chunk_index++; info->apng_shared_chunk_size += chunk->length + 12; info->apng_shared_chunk_num++; } break; } } } return info; } /** Copy a png frame data from an apng file. @param data apng file data @param info png info @param index frame index (zero-based) @param size output, the size of the frame data @return A frame data (single-frame png file), call free() to release the data. Returns NULL if an error occurs. */ static uint8_t *yy_png_copy_frame_data_at_index(const uint8_t *data, const yy_png_info *info, const uint32_t index, uint32_t *size) { if (index >= info->apng_frame_num) return NULL; yy_png_frame_info *frame_info = info->apng_frames + index; uint32_t frame_remux_size = 8 /* PNG Header */ + info->apng_shared_chunk_size + frame_info->chunk_size; if (!(info->apng_first_frame_is_cover && index == 0)) { frame_remux_size -= frame_info->chunk_num * 4; // remove fdAT sequence number } uint8_t *frame_data = malloc(frame_remux_size); if (!frame_data) return NULL; *size = frame_remux_size; uint32_t data_offset = 0; bool inserted = false; memcpy(frame_data, data, 8); // PNG File Header data_offset += 8; for (uint32_t i = 0; i < info->apng_shared_chunk_num; i++) { uint32_t shared_chunk_index = info->apng_shared_chunk_indexs[i]; yy_png_chunk_info *shared_chunk_info = info->chunks + shared_chunk_index; if (shared_chunk_index >= info->apng_shared_insert_index && !inserted) { // replace IDAT with fdAT inserted = true; for (uint32_t c = 0; c < frame_info->chunk_num; c++) { yy_png_chunk_info *insert_chunk_info = info->chunks + frame_info->chunk_index + c; if (insert_chunk_info->fourcc == YY_FOUR_CC('f', 'd', 'A', 'T')) { *((uint32_t *)(frame_data + data_offset)) = yy_swap_endian_uint32(insert_chunk_info->length - 4); *((uint32_t *)(frame_data + data_offset + 4)) = YY_FOUR_CC('I', 'D', 'A', 'T'); memcpy(frame_data + data_offset + 8, data + insert_chunk_info->offset + 12, insert_chunk_info->length - 4); uint32_t crc = (uint32_t)crc32(0, frame_data + data_offset + 4, insert_chunk_info->length); *((uint32_t *)(frame_data + data_offset + insert_chunk_info->length + 4)) = yy_swap_endian_uint32(crc); data_offset += insert_chunk_info->length + 8; } else { // IDAT memcpy(frame_data + data_offset, data + insert_chunk_info->offset, insert_chunk_info->length + 12); data_offset += insert_chunk_info->length + 12; } } } if (shared_chunk_info->fourcc == YY_FOUR_CC('I', 'H', 'D', 'R')) { uint8_t tmp[25] = {0}; memcpy(tmp, data + shared_chunk_info->offset, 25); yy_png_chunk_IHDR IHDR = info->header; IHDR.width = frame_info->frame_control.width; IHDR.height = frame_info->frame_control.height; yy_png_chunk_IHDR_write(&IHDR, tmp + 8); *((uint32_t *)(tmp + 21)) = yy_swap_endian_uint32((uint32_t)crc32(0, tmp + 4, 17)); memcpy(frame_data + data_offset, tmp, 25); data_offset += 25; } else { memcpy(frame_data + data_offset, data + shared_chunk_info->offset, shared_chunk_info->length + 12); data_offset += shared_chunk_info->length + 12; } } return frame_data; } //////////////////////////////////////////////////////////////////////////////// #pragma mark - Helper /// Returns byte-aligned size. static inline size_t YYImageByteAlign(size_t size, size_t alignment) { return ((size + (alignment - 1)) / alignment) * alignment; } /// Convert degree to radians static inline CGFloat YYImageDegreesToRadians(CGFloat degrees) { return degrees * M_PI / 180; } CGColorSpaceRef YYCGColorSpaceGetDeviceRGB() { static CGColorSpaceRef space; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ space = CGColorSpaceCreateDeviceRGB(); }); return space; } CGColorSpaceRef YYCGColorSpaceGetDeviceGray() { static CGColorSpaceRef space; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ space = CGColorSpaceCreateDeviceGray(); }); return space; } BOOL YYCGColorSpaceIsDeviceRGB(CGColorSpaceRef space) { return space && CFEqual(space, YYCGColorSpaceGetDeviceRGB()); } BOOL YYCGColorSpaceIsDeviceGray(CGColorSpaceRef space) { return space && CFEqual(space, YYCGColorSpaceGetDeviceGray()); } /** A callback used in CGDataProviderCreateWithData() to release data. Example: void *data = malloc(size); CGDataProviderRef provider = CGDataProviderCreateWithData(data, data, size, YYCGDataProviderReleaseDataCallback); */ static void YYCGDataProviderReleaseDataCallback(void *info, const void *data, size_t size) { if (info) free(info); } /** Decode an image to bitmap buffer with the specified format. @param srcImage Source image. @param dest Destination buffer. It should be zero before call this method. If decode succeed, you should release the dest->data using free(). @param destFormat Destination bitmap format. @return Whether succeed. @warning This method support iOS7.0 and later. If call it on iOS6, it just returns NO. CG_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0) */ static BOOL YYCGImageDecodeToBitmapBufferWithAnyFormat(CGImageRef srcImage, vImage_Buffer *dest, vImage_CGImageFormat *destFormat) { if (!srcImage || (((long)vImageConvert_AnyToAny) + 1 == 1) || !destFormat || !dest) return NO; size_t width = CGImageGetWidth(srcImage); size_t height = CGImageGetHeight(srcImage); if (width == 0 || height == 0) return NO; dest->data = NULL; vImage_Error error = kvImageNoError; CFDataRef srcData = NULL; vImageConverterRef convertor = NULL; vImage_CGImageFormat srcFormat = {0}; srcFormat.bitsPerComponent = (uint32_t)CGImageGetBitsPerComponent(srcImage); srcFormat.bitsPerPixel = (uint32_t)CGImageGetBitsPerPixel(srcImage); srcFormat.colorSpace = CGImageGetColorSpace(srcImage); srcFormat.bitmapInfo = CGImageGetBitmapInfo(srcImage) | CGImageGetAlphaInfo(srcImage); convertor = vImageConverter_CreateWithCGImageFormat(&srcFormat, destFormat, NULL, kvImageNoFlags, NULL); if (!convertor) goto fail; CGDataProviderRef srcProvider = CGImageGetDataProvider(srcImage); srcData = srcProvider ? CGDataProviderCopyData(srcProvider) : NULL; // decode size_t srcLength = srcData ? CFDataGetLength(srcData) : 0; const void *srcBytes = srcData ? CFDataGetBytePtr(srcData) : NULL; if (srcLength == 0 || !srcBytes) goto fail; vImage_Buffer src = {0}; src.data = (void *)srcBytes; src.width = width; src.height = height; src.rowBytes = CGImageGetBytesPerRow(srcImage); error = vImageBuffer_Init(dest, height, width, 32, kvImageNoFlags); if (error != kvImageNoError) goto fail; error = vImageConvert_AnyToAny(convertor, &src, dest, NULL, kvImageNoFlags); // convert if (error != kvImageNoError) goto fail; CFRelease(convertor); CFRelease(srcData); return YES; fail: if (convertor) CFRelease(convertor); if (srcData) CFRelease(srcData); if (dest->data) free(dest->data); dest->data = NULL; return NO; } /** Decode an image to bitmap buffer with the 32bit format (such as ARGB8888). @param srcImage Source image. @param dest Destination buffer. It should be zero before call this method. If decode succeed, you should release the dest->data using free(). @param bitmapInfo Destination bitmap format. @return Whether succeed. */ static BOOL YYCGImageDecodeToBitmapBufferWith32BitFormat(CGImageRef srcImage, vImage_Buffer *dest, CGBitmapInfo bitmapInfo) { if (!srcImage || !dest) return NO; size_t width = CGImageGetWidth(srcImage); size_t height = CGImageGetHeight(srcImage); if (width == 0 || height == 0) return NO; BOOL hasAlpha = NO; BOOL alphaFirst = NO; BOOL alphaPremultiplied = NO; BOOL byteOrderNormal = NO; switch (bitmapInfo & kCGBitmapAlphaInfoMask) { case kCGImageAlphaPremultipliedLast: { hasAlpha = YES; alphaPremultiplied = YES; } break; case kCGImageAlphaPremultipliedFirst: { hasAlpha = YES; alphaPremultiplied = YES; alphaFirst = YES; } break; case kCGImageAlphaLast: { hasAlpha = YES; } break; case kCGImageAlphaFirst: { hasAlpha = YES; alphaFirst = YES; } break; case kCGImageAlphaNoneSkipLast: { } break; case kCGImageAlphaNoneSkipFirst: { alphaFirst = YES; } break; default: { return NO; } break; } switch (bitmapInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrderDefault: { byteOrderNormal = YES; } break; case kCGBitmapByteOrder32Little: { } break; case kCGBitmapByteOrder32Big: { byteOrderNormal = YES; } break; default: { return NO; } break; } /* Try convert with vImageConvert_AnyToAny() (avaliable since iOS 7.0). If fail, try decode with CGContextDrawImage(). CGBitmapContext use a premultiplied alpha format, unpremultiply may lose precision. */ vImage_CGImageFormat destFormat = {0}; destFormat.bitsPerComponent = 8; destFormat.bitsPerPixel = 32; destFormat.colorSpace = YYCGColorSpaceGetDeviceRGB(); destFormat.bitmapInfo = bitmapInfo; dest->data = NULL; if (YYCGImageDecodeToBitmapBufferWithAnyFormat(srcImage, dest, &destFormat)) return YES; CGBitmapInfo contextBitmapInfo = bitmapInfo & kCGBitmapByteOrderMask; if (!hasAlpha || alphaPremultiplied) { contextBitmapInfo |= (bitmapInfo & kCGBitmapAlphaInfoMask); } else { contextBitmapInfo |= alphaFirst ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaPremultipliedLast; } CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, YYCGColorSpaceGetDeviceRGB(), contextBitmapInfo); if (!context) goto fail; CGContextDrawImage(context, CGRectMake(0, 0, width, height), srcImage); // decode and convert size_t bytesPerRow = CGBitmapContextGetBytesPerRow(context); size_t length = height * bytesPerRow; void *data = CGBitmapContextGetData(context); if (length == 0 || !data) goto fail; dest->data = malloc(length); dest->width = width; dest->height = height; dest->rowBytes = bytesPerRow; if (!dest->data) goto fail; if (hasAlpha && !alphaPremultiplied) { vImage_Buffer tmpSrc = {0}; tmpSrc.data = data; tmpSrc.width = width; tmpSrc.height = height; tmpSrc.rowBytes = bytesPerRow; vImage_Error error; if (alphaFirst && byteOrderNormal) { error = vImageUnpremultiplyData_ARGB8888(&tmpSrc, dest, kvImageNoFlags); } else { error = vImageUnpremultiplyData_RGBA8888(&tmpSrc, dest, kvImageNoFlags); } if (error != kvImageNoError) goto fail; } else { memcpy(dest->data, data, length); } CFRelease(context); return YES; fail: if (context) CFRelease(context); if (dest->data) free(dest->data); dest->data = NULL; return NO; return NO; } CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay) { if (!imageRef) return NULL; size_t width = CGImageGetWidth(imageRef); size_t height = CGImageGetHeight(imageRef); if (width == 0 || height == 0) return NULL; if (decodeForDisplay) { //decode with redraw (may lose some precision) CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef) & kCGBitmapAlphaInfoMask; BOOL hasAlpha = NO; if (alphaInfo == kCGImageAlphaPremultipliedLast || alphaInfo == kCGImageAlphaPremultipliedFirst || alphaInfo == kCGImageAlphaLast || alphaInfo == kCGImageAlphaFirst) { hasAlpha = YES; } // BGRA8888 (premultiplied) or BGRX8888 // same as UIGraphicsBeginImageContext() and -[UIView drawRect:] CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host; bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst; CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, YYCGColorSpaceGetDeviceRGB(), bitmapInfo); if (!context) return NULL; CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); // decode CGImageRef newImage = CGBitmapContextCreateImage(context); CFRelease(context); return newImage; } else { CGColorSpaceRef space = CGImageGetColorSpace(imageRef); size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); size_t bitsPerPixel = CGImageGetBitsPerPixel(imageRef); size_t bytesPerRow = CGImageGetBytesPerRow(imageRef); CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); if (bytesPerRow == 0 || width == 0 || height == 0) return NULL; CGDataProviderRef dataProvider = CGImageGetDataProvider(imageRef); if (!dataProvider) return NULL; CFDataRef data = CGDataProviderCopyData(dataProvider); // decode if (!data) return NULL; CGDataProviderRef newProvider = CGDataProviderCreateWithCFData(data); CFRelease(data); if (!newProvider) return NULL; CGImageRef newImage = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, space, bitmapInfo, newProvider, NULL, false, kCGRenderingIntentDefault); CFRelease(newProvider); return newImage; } } CGImageRef YYCGImageCreateAffineTransformCopy(CGImageRef imageRef, CGAffineTransform transform, CGSize destSize, CGBitmapInfo destBitmapInfo) { if (!imageRef) return NULL; size_t srcWidth = CGImageGetWidth(imageRef); size_t srcHeight = CGImageGetHeight(imageRef); size_t destWidth = round(destSize.width); size_t destHeight = round(destSize.height); if (srcWidth == 0 || srcHeight == 0 || destWidth == 0 || destHeight == 0) return NULL; CGDataProviderRef tmpProvider = NULL, destProvider = NULL; CGImageRef tmpImage = NULL, destImage = NULL; vImage_Buffer src = {0}, tmp = {0}, dest = {0}; if(!YYCGImageDecodeToBitmapBufferWith32BitFormat(imageRef, &src, kCGImageAlphaFirst | kCGBitmapByteOrderDefault)) return NULL; size_t destBytesPerRow = YYImageByteAlign(destWidth * 4, 32); tmp.data = malloc(destHeight * destBytesPerRow); if (!tmp.data) goto fail; tmp.width = destWidth; tmp.height = destHeight; tmp.rowBytes = destBytesPerRow; vImage_CGAffineTransform vTransform = *((vImage_CGAffineTransform *)&transform); uint8_t backColor[4] = {0}; vImage_Error error = vImageAffineWarpCG_ARGB8888(&src, &tmp, NULL, &vTransform, backColor, kvImageBackgroundColorFill); if (error != kvImageNoError) goto fail; free(src.data); src.data = NULL; tmpProvider = CGDataProviderCreateWithData(tmp.data, tmp.data, destHeight * destBytesPerRow, YYCGDataProviderReleaseDataCallback); if (!tmpProvider) goto fail; tmp.data = NULL; // hold by provider tmpImage = CGImageCreate(destWidth, destHeight, 8, 32, destBytesPerRow, YYCGColorSpaceGetDeviceRGB(), kCGImageAlphaFirst | kCGBitmapByteOrderDefault, tmpProvider, NULL, false, kCGRenderingIntentDefault); if (!tmpImage) goto fail; CFRelease(tmpProvider); tmpProvider = NULL; if ((destBitmapInfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaFirst && (destBitmapInfo & kCGBitmapByteOrderMask) != kCGBitmapByteOrder32Little) { return tmpImage; } if (!YYCGImageDecodeToBitmapBufferWith32BitFormat(tmpImage, &dest, destBitmapInfo)) goto fail; CFRelease(tmpImage); tmpImage = NULL; destProvider = CGDataProviderCreateWithData(dest.data, dest.data, destHeight * destBytesPerRow, YYCGDataProviderReleaseDataCallback); if (!destProvider) goto fail; dest.data = NULL; // hold by provider destImage = CGImageCreate(destWidth, destHeight, 8, 32, destBytesPerRow, YYCGColorSpaceGetDeviceRGB(), destBitmapInfo, destProvider, NULL, false, kCGRenderingIntentDefault); if (!destImage) goto fail; CFRelease(destProvider); destProvider = NULL; return destImage; fail: if (src.data) free(src.data); if (tmp.data) free(tmp.data); if (dest.data) free(dest.data); if (tmpProvider) CFRelease(tmpProvider); if (tmpImage) CFRelease(tmpImage); if (destProvider) CFRelease(destProvider); return NULL; } UIImageOrientation YYUIImageOrientationFromEXIFValue(NSInteger value) { switch (value) { case kCGImagePropertyOrientationUp: return UIImageOrientationUp; case kCGImagePropertyOrientationDown: return UIImageOrientationDown; case kCGImagePropertyOrientationLeft: return UIImageOrientationLeft; case kCGImagePropertyOrientationRight: return UIImageOrientationRight; case kCGImagePropertyOrientationUpMirrored: return UIImageOrientationUpMirrored; case kCGImagePropertyOrientationDownMirrored: return UIImageOrientationDownMirrored; case kCGImagePropertyOrientationLeftMirrored: return UIImageOrientationLeftMirrored; case kCGImagePropertyOrientationRightMirrored: return UIImageOrientationRightMirrored; default: return UIImageOrientationUp; } } NSInteger YYUIImageOrientationToEXIFValue(UIImageOrientation orientation) { switch (orientation) { case UIImageOrientationUp: return kCGImagePropertyOrientationUp; case UIImageOrientationDown: return kCGImagePropertyOrientationDown; case UIImageOrientationLeft: return kCGImagePropertyOrientationLeft; case UIImageOrientationRight: return kCGImagePropertyOrientationRight; case UIImageOrientationUpMirrored: return kCGImagePropertyOrientationUpMirrored; case UIImageOrientationDownMirrored: return kCGImagePropertyOrientationDownMirrored; case UIImageOrientationLeftMirrored: return kCGImagePropertyOrientationLeftMirrored; case UIImageOrientationRightMirrored: return kCGImagePropertyOrientationRightMirrored; default: return kCGImagePropertyOrientationUp; } } CGImageRef YYCGImageCreateCopyWithOrientation(CGImageRef imageRef, UIImageOrientation orientation, CGBitmapInfo destBitmapInfo) { if (!imageRef) return NULL; if (orientation == UIImageOrientationUp) return (CGImageRef)CFRetain(imageRef); size_t width = CGImageGetWidth(imageRef); size_t height = CGImageGetHeight(imageRef); CGAffineTransform transform = CGAffineTransformIdentity; BOOL swapWidthAndHeight = NO; switch (orientation) { case UIImageOrientationDown: { transform = CGAffineTransformMakeRotation(YYImageDegreesToRadians(180)); transform = CGAffineTransformTranslate(transform, -(CGFloat)width, -(CGFloat)height); } break; case UIImageOrientationLeft: { transform = CGAffineTransformMakeRotation(YYImageDegreesToRadians(90)); transform = CGAffineTransformTranslate(transform, -(CGFloat)0, -(CGFloat)height); swapWidthAndHeight = YES; } break; case UIImageOrientationRight: { transform = CGAffineTransformMakeRotation(YYImageDegreesToRadians(-90)); transform = CGAffineTransformTranslate(transform, -(CGFloat)width, (CGFloat)0); swapWidthAndHeight = YES; } break; case UIImageOrientationUpMirrored: { transform = CGAffineTransformTranslate(transform, (CGFloat)width, 0); transform = CGAffineTransformScale(transform, -1, 1); } break; case UIImageOrientationDownMirrored: { transform = CGAffineTransformTranslate(transform, 0, (CGFloat)height); transform = CGAffineTransformScale(transform, 1, -1); } break; case UIImageOrientationLeftMirrored: { transform = CGAffineTransformMakeRotation(YYImageDegreesToRadians(-90)); transform = CGAffineTransformScale(transform, 1, -1); transform = CGAffineTransformTranslate(transform, -(CGFloat)width, -(CGFloat)height); swapWidthAndHeight = YES; } break; case UIImageOrientationRightMirrored: { transform = CGAffineTransformMakeRotation(YYImageDegreesToRadians(90)); transform = CGAffineTransformScale(transform, 1, -1); swapWidthAndHeight = YES; } break; default: break; } if (CGAffineTransformIsIdentity(transform)) return (CGImageRef)CFRetain(imageRef); CGSize destSize = {width, height}; if (swapWidthAndHeight) { destSize.width = height; destSize.height = width; } return YYCGImageCreateAffineTransformCopy(imageRef, transform, destSize, destBitmapInfo); } YYImageType YYImageDetectType(CFDataRef data) { if (!data) return YYImageTypeUnknown; uint64_t length = CFDataGetLength(data); if (length < 16) return YYImageTypeUnknown; const char *bytes = (char *)CFDataGetBytePtr(data); uint32_t magic4 = *((uint32_t *)bytes); switch (magic4) { case YY_FOUR_CC(0x4D, 0x4D, 0x00, 0x2A): { // big endian TIFF return YYImageTypeTIFF; } break; case YY_FOUR_CC(0x49, 0x49, 0x2A, 0x00): { // little endian TIFF return YYImageTypeTIFF; } break; case YY_FOUR_CC(0x00, 0x00, 0x01, 0x00): { // ICO return YYImageTypeICO; } break; case YY_FOUR_CC(0x00, 0x00, 0x02, 0x00): { // CUR return YYImageTypeICO; } break; case YY_FOUR_CC('i', 'c', 'n', 's'): { // ICNS return YYImageTypeICNS; } break; case YY_FOUR_CC('G', 'I', 'F', '8'): { // GIF return YYImageTypeGIF; } break; case YY_FOUR_CC(0x89, 'P', 'N', 'G'): { // PNG uint32_t tmp = *((uint32_t *)(bytes + 4)); if (tmp == YY_FOUR_CC('\r', '\n', 0x1A, '\n')) { return YYImageTypePNG; } } break; case YY_FOUR_CC('R', 'I', 'F', 'F'): { // WebP uint32_t tmp = *((uint32_t *)(bytes + 8)); if (tmp == YY_FOUR_CC('W', 'E', 'B', 'P')) { return YYImageTypeWebP; } } break; /* case YY_FOUR_CC('B', 'P', 'G', 0xFB): { // BPG return YYImageTypeBPG; } break; */ } uint16_t magic2 = *((uint16_t *)bytes); switch (magic2) { case YY_TWO_CC('B', 'A'): case YY_TWO_CC('B', 'M'): case YY_TWO_CC('I', 'C'): case YY_TWO_CC('P', 'I'): case YY_TWO_CC('C', 'I'): case YY_TWO_CC('C', 'P'): { // BMP return YYImageTypeBMP; } case YY_TWO_CC(0xFF, 0x4F): { // JPEG2000 return YYImageTypeJPEG2000; } } // JPG FF D8 FF if (memcmp(bytes,"\377\330\377",3) == 0) return YYImageTypeJPEG; // JP2 if (memcmp(bytes + 4, "\152\120\040\040\015", 5) == 0) return YYImageTypeJPEG2000; return YYImageTypeUnknown; } CFStringRef YYImageTypeToUTType(YYImageType type) { switch (type) { case YYImageTypeJPEG: return kUTTypeJPEG; case YYImageTypeJPEG2000: return kUTTypeJPEG2000; case YYImageTypeTIFF: return kUTTypeTIFF; case YYImageTypeBMP: return kUTTypeBMP; case YYImageTypeICO: return kUTTypeICO; case YYImageTypeICNS: return kUTTypeAppleICNS; case YYImageTypeGIF: return kUTTypeGIF; case YYImageTypePNG: return kUTTypePNG; default: return NULL; } } YYImageType YYImageTypeFromUTType(CFStringRef uti) { static NSDictionary *dic; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ dic = @{(id)kUTTypeJPEG : @(YYImageTypeJPEG), (id)kUTTypeJPEG2000 : @(YYImageTypeJPEG2000), (id)kUTTypeTIFF : @(YYImageTypeTIFF), (id)kUTTypeBMP : @(YYImageTypeBMP), (id)kUTTypeICO : @(YYImageTypeICO), (id)kUTTypeAppleICNS : @(YYImageTypeICNS), (id)kUTTypeGIF : @(YYImageTypeGIF), (id)kUTTypePNG : @(YYImageTypePNG)}; }); if (!uti) return YYImageTypeUnknown; NSNumber *num = dic[(__bridge __strong id)(uti)]; return num.unsignedIntegerValue; } NSString *YYImageTypeGetExtension(YYImageType type) { switch (type) { case YYImageTypeJPEG: return @"jpg"; case YYImageTypeJPEG2000: return @"jp2"; case YYImageTypeTIFF: return @"tiff"; case YYImageTypeBMP: return @"bmp"; case YYImageTypeICO: return @"ico"; case YYImageTypeICNS: return @"icns"; case YYImageTypeGIF: return @"gif"; case YYImageTypePNG: return @"png"; case YYImageTypeWebP: return @"webp"; default: return nil; } } CFDataRef YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality) { if (!imageRef) return nil; quality = quality < 0 ? 0 : quality > 1 ? 1 : quality; if (type == YYImageTypeWebP) { #if YYIMAGE_WEBP_ENABLED if (quality == 1) { return YYCGImageCreateEncodedWebPData(imageRef, YES, quality, 4, YYImagePresetDefault); } else { return YYCGImageCreateEncodedWebPData(imageRef, NO, quality, 4, YYImagePresetDefault); } #else return NULL; #endif } CFStringRef uti = YYImageTypeToUTType(type); if (!uti) return nil; CFMutableDataRef data = CFDataCreateMutable(CFAllocatorGetDefault(), 0); if (!data) return NULL; CGImageDestinationRef dest = CGImageDestinationCreateWithData(data, uti, 1, NULL); if (!dest) { CFRelease(data); return NULL; } NSDictionary *options = @{(id)kCGImageDestinationLossyCompressionQuality : @(quality) }; CGImageDestinationAddImage(dest, imageRef, (CFDictionaryRef)options); if (!CGImageDestinationFinalize(dest)) { CFRelease(data); CFRelease(dest); return nil; } CFRelease(dest); if (CFDataGetLength(data) == 0) { CFRelease(data); return NULL; } return data; } #if YYIMAGE_WEBP_ENABLED BOOL YYImageWebPAvailable() { return YES; } CFDataRef YYCGImageCreateEncodedWebPData(CGImageRef imageRef, BOOL lossless, CGFloat quality, int compressLevel, YYImagePreset preset) { if (!imageRef) return nil; size_t width = CGImageGetWidth(imageRef); size_t height = CGImageGetHeight(imageRef); if (width == 0 || width > WEBP_MAX_DIMENSION) return nil; if (height == 0 || height > WEBP_MAX_DIMENSION) return nil; vImage_Buffer buffer = {0}; if(!YYCGImageDecodeToBitmapBufferWith32BitFormat(imageRef, &buffer, kCGImageAlphaLast | kCGBitmapByteOrderDefault)) return nil; WebPConfig config = {0}; WebPPicture picture = {0}; WebPMemoryWriter writer = {0}; CFDataRef webpData = NULL; BOOL pictureNeedFree = NO; quality = quality < 0 ? 0 : quality > 1 ? 1 : quality; preset = preset > YYImagePresetText ? YYImagePresetDefault : preset; compressLevel = compressLevel < 0 ? 0 : compressLevel > 6 ? 6 : compressLevel; if (!WebPConfigPreset(&config, (WebPPreset)preset, quality)) goto fail; config.quality = round(quality * 100.0); config.lossless = lossless; config.method = compressLevel; switch ((WebPPreset)preset) { case WEBP_PRESET_DEFAULT: { config.image_hint = WEBP_HINT_DEFAULT; } break; case WEBP_PRESET_PICTURE: { config.image_hint = WEBP_HINT_PICTURE; } break; case WEBP_PRESET_PHOTO: { config.image_hint = WEBP_HINT_PHOTO; } break; case WEBP_PRESET_DRAWING: case WEBP_PRESET_ICON: case WEBP_PRESET_TEXT: { config.image_hint = WEBP_HINT_GRAPH; } break; } if (!WebPValidateConfig(&config)) goto fail; if (!WebPPictureInit(&picture)) goto fail; pictureNeedFree = YES; picture.width = (int)buffer.width; picture.height = (int)buffer.height; picture.use_argb = lossless; if(!WebPPictureImportRGBA(&picture, buffer.data, (int)buffer.rowBytes)) goto fail; WebPMemoryWriterInit(&writer); picture.writer = WebPMemoryWrite; picture.custom_ptr = &writer; if(!WebPEncode(&config, &picture)) goto fail; webpData = CFDataCreate(CFAllocatorGetDefault(), writer.mem, writer.size); free(writer.mem); WebPPictureFree(&picture); free(buffer.data); return webpData; fail: if (buffer.data) free(buffer.data); if (pictureNeedFree) WebPPictureFree(&picture); return nil; } NSUInteger YYImageGetWebPFrameCount(CFDataRef webpData) { if (!webpData || CFDataGetLength(webpData) == 0) return 0; WebPData data = {CFDataGetBytePtr(webpData), CFDataGetLength(webpData)}; WebPDemuxer *demuxer = WebPDemux(&data); if (!demuxer) return 0; NSUInteger webpFrameCount = WebPDemuxGetI(demuxer, WEBP_FF_FRAME_COUNT); WebPDemuxDelete(demuxer); return webpFrameCount; } CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData, BOOL decodeForDisplay, BOOL useThreads, BOOL bypassFiltering, BOOL noFancyUpsampling) { /* Call WebPDecode() on a multi-frame webp data will get an error (VP8_STATUS_UNSUPPORTED_FEATURE). Use WebPDemuxer to unpack it first. */ WebPData data = {0}; WebPDemuxer *demuxer = NULL; int frameCount = 0, canvasWidth = 0, canvasHeight = 0; WebPIterator iter = {0}; BOOL iterInited = NO; const uint8_t *payload = NULL; size_t payloadSize = 0; WebPDecoderConfig config = {0}; BOOL hasAlpha = NO; size_t bitsPerComponent = 0, bitsPerPixel = 0, bytesPerRow = 0, destLength = 0; CGBitmapInfo bitmapInfo = 0; WEBP_CSP_MODE colorspace = 0; void *destBytes = NULL; CGDataProviderRef provider = NULL; CGImageRef imageRef = NULL; if (!webpData || CFDataGetLength(webpData) == 0) return NULL; data.bytes = CFDataGetBytePtr(webpData); data.size = CFDataGetLength(webpData); demuxer = WebPDemux(&data); if (!demuxer) goto fail; frameCount = WebPDemuxGetI(demuxer, WEBP_FF_FRAME_COUNT); if (frameCount == 0) { goto fail; } else if (frameCount == 1) { // single-frame payload = data.bytes; payloadSize = data.size; if (!WebPInitDecoderConfig(&config)) goto fail; if (WebPGetFeatures(payload , payloadSize, &config.input) != VP8_STATUS_OK) goto fail; canvasWidth = config.input.width; canvasHeight = config.input.height; } else { // multi-frame canvasWidth = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_WIDTH); canvasHeight = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_HEIGHT); if (canvasWidth < 1 || canvasHeight < 1) goto fail; if (!WebPDemuxGetFrame(demuxer, 1, &iter)) goto fail; iterInited = YES; if (iter.width > canvasWidth || iter.height > canvasHeight) goto fail; payload = iter.fragment.bytes; payloadSize = iter.fragment.size; if (!WebPInitDecoderConfig(&config)) goto fail; if (WebPGetFeatures(payload , payloadSize, &config.input) != VP8_STATUS_OK) goto fail; } if (payload == NULL || payloadSize == 0) goto fail; hasAlpha = config.input.has_alpha; bitsPerComponent = 8; bitsPerPixel = 32; bytesPerRow = YYImageByteAlign(bitsPerPixel / 8 * canvasWidth, 32); destLength = bytesPerRow * canvasHeight; if (decodeForDisplay) { bitmapInfo = kCGBitmapByteOrder32Host; bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst; colorspace = MODE_bgrA; // small endian } else { bitmapInfo = kCGBitmapByteOrderDefault; bitmapInfo |= hasAlpha ? kCGImageAlphaLast : kCGImageAlphaNoneSkipLast; colorspace = MODE_RGBA; } destBytes = calloc(1, destLength); if (!destBytes) goto fail; config.options.use_threads = useThreads; //speed up 23% config.options.bypass_filtering = bypassFiltering; //speed up 11%, cause some banding config.options.no_fancy_upsampling = noFancyUpsampling; //speed down 16%, lose some details config.output.colorspace = colorspace; config.output.is_external_memory = 1; config.output.u.RGBA.rgba = destBytes; config.output.u.RGBA.stride = (int)bytesPerRow; config.output.u.RGBA.size = destLength; VP8StatusCode result = WebPDecode(payload, payloadSize, &config); if ((result != VP8_STATUS_OK) && (result != VP8_STATUS_NOT_ENOUGH_DATA)) goto fail; if (iter.x_offset != 0 || iter.y_offset != 0) { void *tmp = calloc(1, destLength); if (tmp) { vImage_Buffer src = {destBytes, canvasHeight, canvasWidth, bytesPerRow}; vImage_Buffer dest = {tmp, canvasHeight, canvasWidth, bytesPerRow}; vImage_CGAffineTransform transform = {1, 0, 0, 1, iter.x_offset, -iter.y_offset}; uint8_t backColor[4] = {0}; vImageAffineWarpCG_ARGB8888(&src, &dest, NULL, &transform, backColor, kvImageBackgroundColorFill); memcpy(destBytes, tmp, destLength); free(tmp); } } provider = CGDataProviderCreateWithData(destBytes, destBytes, destLength, YYCGDataProviderReleaseDataCallback); if (!provider) goto fail; destBytes = NULL; // hold by provider imageRef = CGImageCreate(canvasWidth, canvasHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, YYCGColorSpaceGetDeviceRGB(), bitmapInfo, provider, NULL, false, kCGRenderingIntentDefault); CFRelease(provider); if (iterInited) WebPDemuxReleaseIterator(&iter); WebPDemuxDelete(demuxer); return imageRef; fail: if (destBytes) free(destBytes); if (provider) CFRelease(provider); if (iterInited) WebPDemuxReleaseIterator(&iter); if (demuxer) WebPDemuxDelete(demuxer); return NULL; } #else BOOL YYImageWebPAvailable() { return NO; } CFDataRef YYCGImageCreateEncodedWebPData(CGImageRef imageRef, BOOL lossless, CGFloat quality, int compressLevel, YYImagePreset preset) { NSLog(@"WebP decoder is disabled"); return NULL; } NSUInteger YYImageGetWebPFrameCount(CFDataRef webpData) { NSLog(@"WebP decoder is disabled"); return 0; } CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData, BOOL decodeForDisplay, BOOL useThreads, BOOL bypassFiltering, BOOL noFancyUpsampling) { NSLog(@"WebP decoder is disabled"); return NULL; } #endif //////////////////////////////////////////////////////////////////////////////// #pragma mark - Decoder @implementation YYImageFrame + (instancetype)frameWithImage:(UIImage *)image { YYImageFrame *frame = [self new]; frame.image = image; return frame; } - (id)copyWithZone:(NSZone *)zone { YYImageFrame *frame = [self.class new]; frame.index = _index; frame.width = _width; frame.height = _height; frame.offsetX = _offsetX; frame.offsetY = _offsetY; frame.duration = _duration; frame.dispose = _dispose; frame.blend = _blend; frame.image = _image.copy; return frame; } @end // Internal frame object. @interface _YYImageDecoderFrame : YYImageFrame @property (nonatomic, assign) BOOL hasAlpha; ///< Whether frame has alpha. @property (nonatomic, assign) BOOL isFullSize; ///< Whether frame fill the canvas. @property (nonatomic, assign) NSUInteger blendFromIndex; ///< Blend from frame index to current frame. @end @implementation _YYImageDecoderFrame - (id)copyWithZone:(NSZone *)zone { _YYImageDecoderFrame *frame = [super copyWithZone:zone]; frame.hasAlpha = _hasAlpha; frame.isFullSize = _isFullSize; frame.blendFromIndex = _blendFromIndex; return frame; } @end @implementation YYImageDecoder { pthread_mutex_t _lock; // recursive lock BOOL _sourceTypeDetected; CGImageSourceRef _source; yy_png_info *_apngSource; #if YYIMAGE_WEBP_ENABLED WebPDemuxer *_webpSource; #endif UIImageOrientation _orientation; dispatch_semaphore_t _framesLock; NSArray *_frames; ///< Array<GGImageDecoderFrame>, without image BOOL _needBlend; NSUInteger _blendFrameIndex; CGContextRef _blendCanvas; } - (void)dealloc { if (_source) CFRelease(_source); if (_apngSource) yy_png_info_release(_apngSource); #if YYIMAGE_WEBP_ENABLED if (_webpSource) WebPDemuxDelete(_webpSource); #endif if (_blendCanvas) CFRelease(_blendCanvas); pthread_mutex_destroy(&_lock); } + (instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale { if (!data) return nil; YYImageDecoder *decoder = [[YYImageDecoder alloc] initWithScale:scale]; [decoder updateData:data final:YES]; if (decoder.frameCount == 0) return nil; return decoder; } - (instancetype)init { return [self initWithScale:[UIScreen mainScreen].scale]; } - (instancetype)initWithScale:(CGFloat)scale { self = [super init]; if (scale <= 0) scale = 1; _scale = scale; _framesLock = dispatch_semaphore_create(1); pthread_mutex_init_recursive(&_lock, true); return self; } - (BOOL)updateData:(NSData *)data final:(BOOL)final { BOOL result = NO; pthread_mutex_lock(&_lock); result = [self _updateData:data final:final]; pthread_mutex_unlock(&_lock); return result; } - (YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay { YYImageFrame *result = nil; pthread_mutex_lock(&_lock); result = [self _frameAtIndex:index decodeForDisplay:decodeForDisplay]; pthread_mutex_unlock(&_lock); return result; } - (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index { NSTimeInterval result = 0; dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER); if (index < _frames.count) { result = ((_YYImageDecoderFrame *)_frames[index]).duration; } dispatch_semaphore_signal(_framesLock); return result; } - (NSDictionary *)framePropertiesAtIndex:(NSUInteger)index { NSDictionary *result = nil; pthread_mutex_lock(&_lock); result = [self _framePropertiesAtIndex:index]; pthread_mutex_unlock(&_lock); return result; } - (NSDictionary *)imageProperties { NSDictionary *result = nil; pthread_mutex_lock(&_lock); result = [self _imageProperties]; pthread_mutex_unlock(&_lock); return result; } #pragma private (wrap) - (BOOL)_updateData:(NSData *)data final:(BOOL)final { if (_finalized) return NO; if (data.length < _data.length) return NO; _finalized = final; _data = data; YYImageType type = YYImageDetectType((__bridge CFDataRef)data); if (_sourceTypeDetected) { if (_type != type) { return NO; } else { [self _updateSource]; } } else { if (_data.length > 16) { _type = type; _sourceTypeDetected = YES; [self _updateSource]; } } return YES; } - (YYImageFrame *)_frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay { if (index >= _frames.count) return 0; _YYImageDecoderFrame *frame = [(_YYImageDecoderFrame *)_frames[index] copy]; BOOL decoded = NO; BOOL extendToCanvas = NO; if (_type != YYImageTypeICO && decodeForDisplay) { // ICO contains multi-size frame and should not extend to canvas. extendToCanvas = YES; } if (!_needBlend) { CGImageRef imageRef = [self _newUnblendedImageAtIndex:index extendToCanvas:extendToCanvas decoded:&decoded]; if (!imageRef) return nil; if (decodeForDisplay && !decoded) { CGImageRef imageRefDecoded = YYCGImageCreateDecodedCopy(imageRef, YES); if (imageRefDecoded) { CFRelease(imageRef); imageRef = imageRefDecoded; decoded = YES; } } UIImage *image = [UIImage imageWithCGImage:imageRef scale:_scale orientation:_orientation]; CFRelease(imageRef); if (!image) return nil; image.isDecodedForDisplay = decoded; frame.image = image; return frame; } // blend if (![self _createBlendContextIfNeeded]) return nil; CGImageRef imageRef = NULL; if (_blendFrameIndex + 1 == frame.index) { imageRef = [self _newBlendedImageWithFrame:frame]; _blendFrameIndex = index; } else { // should draw canvas from previous frame _blendFrameIndex = NSNotFound; CGContextClearRect(_blendCanvas, CGRectMake(0, 0, _width, _height)); if (frame.blendFromIndex == frame.index) { CGImageRef unblendedImage = [self _newUnblendedImageAtIndex:index extendToCanvas:NO decoded:NULL]; if (unblendedImage) { CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendedImage); CFRelease(unblendedImage); } imageRef = CGBitmapContextCreateImage(_blendCanvas); if (frame.dispose == YYImageDisposeBackground) { CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); } _blendFrameIndex = index; } else { // canvas is not ready for (uint32_t i = (uint32_t)frame.blendFromIndex; i <= (uint32_t)frame.index; i++) { if (i == frame.index) { if (!imageRef) imageRef = [self _newBlendedImageWithFrame:frame]; } else { [self _blendImageWithFrame:_frames[i]]; } } _blendFrameIndex = index; } } if (!imageRef) return nil; UIImage *image = [UIImage imageWithCGImage:imageRef scale:_scale orientation:_orientation]; CFRelease(imageRef); if (!image) return nil; image.isDecodedForDisplay = YES; frame.image = image; if (extendToCanvas) { frame.width = _width; frame.height = _height; frame.offsetX = 0; frame.offsetY = 0; frame.dispose = YYImageDisposeNone; frame.blend = YYImageBlendNone; } return frame; } - (NSDictionary *)_framePropertiesAtIndex:(NSUInteger)index { if (index >= _frames.count) return nil; if (!_source) return nil; CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_source, index, NULL); if (!properties) return nil; return CFBridgingRelease(properties); } - (NSDictionary *)_imageProperties { if (!_source) return nil; CFDictionaryRef properties = CGImageSourceCopyProperties(_source, NULL); if (!properties) return nil; return CFBridgingRelease(properties); } #pragma private - (void)_updateSource { switch (_type) { case YYImageTypeWebP: { [self _updateSourceWebP]; } break; case YYImageTypePNG: { [self _updateSourceAPNG]; } break; default: { [self _updateSourceImageIO]; } break; } } - (void)_updateSourceWebP { #if YYIMAGE_WEBP_ENABLED _width = 0; _height = 0; _loopCount = 0; if (_webpSource) WebPDemuxDelete(_webpSource); _webpSource = NULL; dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER); _frames = nil; dispatch_semaphore_signal(_framesLock); /* path_to_url The documentation said we can use WebPIDecoder to decode webp progressively, but currently it can only returns an empty image (not same as progressive jpegs), so we don't use progressive decoding. When using WebPDecode() to decode multi-frame webp, we will get the error "VP8_STATUS_UNSUPPORTED_FEATURE", so we first use WebPDemuxer to unpack it. */ WebPData webPData = {0}; webPData.bytes = _data.bytes; webPData.size = _data.length; WebPDemuxer *demuxer = WebPDemux(&webPData); if (!demuxer) return; uint32_t webpFrameCount = WebPDemuxGetI(demuxer, WEBP_FF_FRAME_COUNT); uint32_t webpLoopCount = WebPDemuxGetI(demuxer, WEBP_FF_LOOP_COUNT); uint32_t canvasWidth = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_WIDTH); uint32_t canvasHeight = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_HEIGHT); if (webpFrameCount == 0 || canvasWidth < 1 || canvasHeight < 1) { WebPDemuxDelete(demuxer); return; } NSMutableArray *frames = [NSMutableArray new]; BOOL needBlend = NO; uint32_t iterIndex = 0; uint32_t lastBlendIndex = 0; WebPIterator iter = {0}; if (WebPDemuxGetFrame(demuxer, 1, &iter)) { // one-based index... do { _YYImageDecoderFrame *frame = [_YYImageDecoderFrame new]; [frames addObject:frame]; if (iter.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND) { frame.dispose = YYImageDisposeBackground; } if (iter.blend_method == WEBP_MUX_BLEND) { frame.blend = YYImageBlendOver; } int canvasWidth = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_WIDTH); int canvasHeight = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_HEIGHT); frame.index = iterIndex; frame.duration = iter.duration / 1000.0; frame.width = iter.width; frame.height = iter.height; frame.hasAlpha = iter.has_alpha; frame.blend = iter.blend_method == WEBP_MUX_BLEND; frame.offsetX = iter.x_offset; frame.offsetY = canvasHeight - iter.y_offset - iter.height; BOOL sizeEqualsToCanvas = (iter.width == canvasWidth && iter.height == canvasHeight); BOOL offsetIsZero = (iter.x_offset == 0 && iter.y_offset == 0); frame.isFullSize = (sizeEqualsToCanvas && offsetIsZero); if ((!frame.blend || !frame.hasAlpha) && frame.isFullSize) { frame.blendFromIndex = lastBlendIndex = iterIndex; } else { if (frame.dispose && frame.isFullSize) { frame.blendFromIndex = lastBlendIndex; lastBlendIndex = iterIndex + 1; } else { frame.blendFromIndex = lastBlendIndex; } } if (frame.index != frame.blendFromIndex) needBlend = YES; iterIndex++; } while (WebPDemuxNextFrame(&iter)); WebPDemuxReleaseIterator(&iter); } if (frames.count != webpFrameCount) { WebPDemuxDelete(demuxer); return; } _width = canvasWidth; _height = canvasHeight; _frameCount = frames.count; _loopCount = webpLoopCount; _needBlend = needBlend; _webpSource = demuxer; dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER); _frames = frames; dispatch_semaphore_signal(_framesLock); #else static const char *func = __FUNCTION__; static const int line = __LINE__; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSLog(@"[%s: %d] WebP is not available, check the documentation to see how to install WebP component: path_to_url#installation", func, line); }); #endif } - (void)_updateSourceAPNG { /* APNG extends PNG format to support animation, it was supported by ImageIO since iOS 8. We use a custom APNG decoder to make APNG available in old system, so we ignore the ImageIO's APNG frame info. Typically the custom decoder is a bit faster than ImageIO. */ yy_png_info_release(_apngSource); _apngSource = nil; [self _updateSourceImageIO]; // decode first frame if (_frameCount == 0) return; // png decode failed if (!_finalized) return; // ignore multi-frame before finalized yy_png_info *apng = yy_png_info_create(_data.bytes, (uint32_t)_data.length); if (!apng) return; // apng decode failed if (apng->apng_frame_num == 0 || (apng->apng_frame_num == 1 && apng->apng_first_frame_is_cover)) { yy_png_info_release(apng); return; // no animation } if (_source) { // apng decode succeed, no longer need image souce CFRelease(_source); _source = NULL; } uint32_t canvasWidth = apng->header.width; uint32_t canvasHeight = apng->header.height; NSMutableArray *frames = [NSMutableArray new]; BOOL needBlend = NO; uint32_t lastBlendIndex = 0; for (uint32_t i = 0; i < apng->apng_frame_num; i++) { _YYImageDecoderFrame *frame = [_YYImageDecoderFrame new]; [frames addObject:frame]; yy_png_frame_info *fi = apng->apng_frames + i; frame.index = i; frame.duration = yy_png_delay_to_seconds(fi->frame_control.delay_num, fi->frame_control.delay_den); frame.hasAlpha = YES; frame.width = fi->frame_control.width; frame.height = fi->frame_control.height; frame.offsetX = fi->frame_control.x_offset; frame.offsetY = canvasHeight - fi->frame_control.y_offset - fi->frame_control.height; BOOL sizeEqualsToCanvas = (frame.width == canvasWidth && frame.height == canvasHeight); BOOL offsetIsZero = (fi->frame_control.x_offset == 0 && fi->frame_control.y_offset == 0); frame.isFullSize = (sizeEqualsToCanvas && offsetIsZero); switch (fi->frame_control.dispose_op) { case YY_PNG_DISPOSE_OP_BACKGROUND: { frame.dispose = YYImageDisposeBackground; } break; case YY_PNG_DISPOSE_OP_PREVIOUS: { frame.dispose = YYImageDisposePrevious; } break; default: { frame.dispose = YYImageDisposeNone; } break; } switch (fi->frame_control.blend_op) { case YY_PNG_BLEND_OP_OVER: { frame.blend = YYImageBlendOver; } break; default: { frame.blend = YYImageBlendNone; } break; } if (frame.blend == YYImageBlendNone && frame.isFullSize) { frame.blendFromIndex = i; if (frame.dispose != YYImageDisposePrevious) lastBlendIndex = i; } else { if (frame.dispose == YYImageDisposeBackground && frame.isFullSize) { frame.blendFromIndex = lastBlendIndex; lastBlendIndex = i + 1; } else { frame.blendFromIndex = lastBlendIndex; } } if (frame.index != frame.blendFromIndex) needBlend = YES; } _width = canvasWidth; _height = canvasHeight; _frameCount = frames.count; _loopCount = apng->apng_loop_num; _needBlend = needBlend; _apngSource = apng; dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER); _frames = frames; dispatch_semaphore_signal(_framesLock); } - (void)_updateSourceImageIO { _width = 0; _height = 0; _orientation = UIImageOrientationUp; _loopCount = 0; dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER); _frames = nil; dispatch_semaphore_signal(_framesLock); if (!_source) { if (_finalized) { _source = CGImageSourceCreateWithData((__bridge CFDataRef)_data, NULL); } else { _source = CGImageSourceCreateIncremental(NULL); if (_source) CGImageSourceUpdateData(_source, (__bridge CFDataRef)_data, false); } } else { CGImageSourceUpdateData(_source, (__bridge CFDataRef)_data, _finalized); } if (!_source) return; _frameCount = CGImageSourceGetCount(_source); if (_frameCount == 0) return; if (!_finalized) { // ignore multi-frame before finalized _frameCount = 1; } else { if (_type == YYImageTypePNG) { // use custom apng decoder and ignore multi-frame _frameCount = 1; } if (_type == YYImageTypeGIF) { // get gif loop count CFDictionaryRef properties = CGImageSourceCopyProperties(_source, NULL); if (properties) { CFDictionaryRef gif = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary); if (gif) { CFTypeRef loop = CFDictionaryGetValue(gif, kCGImagePropertyGIFLoopCount); if (loop) CFNumberGetValue(loop, kCFNumberNSIntegerType, &_loopCount); } CFRelease(properties); } } } /* ICO, GIF, APNG may contains multi-frame. */ NSMutableArray *frames = [NSMutableArray new]; for (NSUInteger i = 0; i < _frameCount; i++) { _YYImageDecoderFrame *frame = [_YYImageDecoderFrame new]; frame.index = i; frame.blendFromIndex = i; frame.hasAlpha = YES; frame.isFullSize = YES; [frames addObject:frame]; CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_source, i, NULL); if (properties) { NSTimeInterval duration = 0; NSInteger orientationValue = 0, width = 0, height = 0; CFTypeRef value = NULL; value = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); if (value) CFNumberGetValue(value, kCFNumberNSIntegerType, &width); value = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); if (value) CFNumberGetValue(value, kCFNumberNSIntegerType, &height); if (_type == YYImageTypeGIF) { CFDictionaryRef gif = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary); if (gif) { // Use the unclamped frame delay if it exists. value = CFDictionaryGetValue(gif, kCGImagePropertyGIFUnclampedDelayTime); if (!value) { // Fall back to the clamped frame delay if the unclamped frame delay does not exist. value = CFDictionaryGetValue(gif, kCGImagePropertyGIFDelayTime); } if (value) CFNumberGetValue(value, kCFNumberDoubleType, &duration); } } frame.width = width; frame.height = height; frame.duration = duration; if (i == 0 && _width + _height == 0) { // init first frame _width = width; _height = height; value = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); if (value) { CFNumberGetValue(value, kCFNumberNSIntegerType, &orientationValue); _orientation = YYUIImageOrientationFromEXIFValue(orientationValue); } } CFRelease(properties); } } dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER); _frames = frames; dispatch_semaphore_signal(_framesLock); } - (CGImageRef)_newUnblendedImageAtIndex:(NSUInteger)index extendToCanvas:(BOOL)extendToCanvas decoded:(BOOL *)decoded CF_RETURNS_RETAINED { if (!_finalized && index > 0) return NULL; if (_frames.count <= index) return NULL; _YYImageDecoderFrame *frame = _frames[index]; if (_source) { CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_source, index, (CFDictionaryRef)@{(id)kCGImageSourceShouldCache:@(YES)}); if (imageRef && extendToCanvas) { size_t width = CGImageGetWidth(imageRef); size_t height = CGImageGetHeight(imageRef); if (width == _width && height == _height) { CGImageRef imageRefExtended = YYCGImageCreateDecodedCopy(imageRef, YES); if (imageRefExtended) { CFRelease(imageRef); imageRef = imageRefExtended; if (decoded) *decoded = YES; } } else { CGContextRef context = CGBitmapContextCreate(NULL, _width, _height, 8, 0, YYCGColorSpaceGetDeviceRGB(), kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); if (context) { CGContextDrawImage(context, CGRectMake(0, _height - height, width, height), imageRef); CGImageRef imageRefExtended = CGBitmapContextCreateImage(context); CFRelease(context); if (imageRefExtended) { CFRelease(imageRef); imageRef = imageRefExtended; if (decoded) *decoded = YES; } } } } return imageRef; } if (_apngSource) { uint32_t size = 0; uint8_t *bytes = yy_png_copy_frame_data_at_index(_data.bytes, _apngSource, (uint32_t)index, &size); if (!bytes) return NULL; CGDataProviderRef provider = CGDataProviderCreateWithData(bytes, bytes, size, YYCGDataProviderReleaseDataCallback); if (!provider) { free(bytes); return NULL; } bytes = NULL; // hold by provider CGImageSourceRef source = CGImageSourceCreateWithDataProvider(provider, NULL); if (!source) { CFRelease(provider); return NULL; } CFRelease(provider); if(CGImageSourceGetCount(source) < 1) { CFRelease(source); return NULL; } CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)@{(id)kCGImageSourceShouldCache:@(YES)}); CFRelease(source); if (!imageRef) return NULL; if (extendToCanvas) { CGContextRef context = CGBitmapContextCreate(NULL, _width, _height, 8, 0, YYCGColorSpaceGetDeviceRGB(), kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); //bgrA if (context) { CGContextDrawImage(context, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), imageRef); CFRelease(imageRef); imageRef = CGBitmapContextCreateImage(context); CFRelease(context); if (decoded) *decoded = YES; } } return imageRef; } #if YYIMAGE_WEBP_ENABLED if (_webpSource) { WebPIterator iter; if (!WebPDemuxGetFrame(_webpSource, (int)(index + 1), &iter)) return NULL; // demux webp frame data // frame numbers are one-based in webp -----------^ int frameWidth = iter.width; int frameHeight = iter.height; if (frameWidth < 1 || frameHeight < 1) return NULL; int width = extendToCanvas ? (int)_width : frameWidth; int height = extendToCanvas ? (int)_height : frameHeight; if (width > _width || height > _height) return NULL; const uint8_t *payload = iter.fragment.bytes; size_t payloadSize = iter.fragment.size; WebPDecoderConfig config; if (!WebPInitDecoderConfig(&config)) { WebPDemuxReleaseIterator(&iter); return NULL; } if (WebPGetFeatures(payload , payloadSize, &config.input) != VP8_STATUS_OK) { WebPDemuxReleaseIterator(&iter); return NULL; } size_t bitsPerComponent = 8; size_t bitsPerPixel = 32; size_t bytesPerRow = YYImageByteAlign(bitsPerPixel / 8 * width, 32); size_t length = bytesPerRow * height; CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst; //bgrA void *pixels = calloc(1, length); if (!pixels) { WebPDemuxReleaseIterator(&iter); return NULL; } config.output.colorspace = MODE_bgrA; config.output.is_external_memory = 1; config.output.u.RGBA.rgba = pixels; config.output.u.RGBA.stride = (int)bytesPerRow; config.output.u.RGBA.size = length; VP8StatusCode result = WebPDecode(payload, payloadSize, &config); // decode if ((result != VP8_STATUS_OK) && (result != VP8_STATUS_NOT_ENOUGH_DATA)) { WebPDemuxReleaseIterator(&iter); free(pixels); return NULL; } WebPDemuxReleaseIterator(&iter); if (extendToCanvas && (iter.x_offset != 0 || iter.y_offset != 0)) { void *tmp = calloc(1, length); if (tmp) { vImage_Buffer src = {pixels, height, width, bytesPerRow}; vImage_Buffer dest = {tmp, height, width, bytesPerRow}; vImage_CGAffineTransform transform = {1, 0, 0, 1, iter.x_offset, -iter.y_offset}; uint8_t backColor[4] = {0}; vImage_Error error = vImageAffineWarpCG_ARGB8888(&src, &dest, NULL, &transform, backColor, kvImageBackgroundColorFill); if (error == kvImageNoError) { memcpy(pixels, tmp, length); } free(tmp); } } CGDataProviderRef provider = CGDataProviderCreateWithData(pixels, pixels, length, YYCGDataProviderReleaseDataCallback); if (!provider) { free(pixels); return NULL; } pixels = NULL; // hold by provider CGImageRef image = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, YYCGColorSpaceGetDeviceRGB(), bitmapInfo, provider, NULL, false, kCGRenderingIntentDefault); CFRelease(provider); if (decoded) *decoded = YES; return image; } #endif return NULL; } - (BOOL)_createBlendContextIfNeeded { if (!_blendCanvas) { _blendFrameIndex = NSNotFound; _blendCanvas = CGBitmapContextCreate(NULL, _width, _height, 8, 0, YYCGColorSpaceGetDeviceRGB(), kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); } BOOL suc = _blendCanvas != NULL; return suc; } - (void)_blendImageWithFrame:(_YYImageDecoderFrame *)frame { if (frame.dispose == YYImageDisposePrevious) { // nothing } else if (frame.dispose == YYImageDisposeBackground) { CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); } else { // no dispose if (frame.blend == YYImageBlendOver) { CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } } else { CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } } } } - (CGImageRef)_newBlendedImageWithFrame:(_YYImageDecoderFrame *)frame CF_RETURNS_RETAINED{ CGImageRef imageRef = NULL; if (frame.dispose == YYImageDisposePrevious) { if (frame.blend == YYImageBlendOver) { CGImageRef previousImage = CGBitmapContextCreateImage(_blendCanvas); CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } imageRef = CGBitmapContextCreateImage(_blendCanvas); CGContextClearRect(_blendCanvas, CGRectMake(0, 0, _width, _height)); if (previousImage) { CGContextDrawImage(_blendCanvas, CGRectMake(0, 0, _width, _height), previousImage); CFRelease(previousImage); } } else { CGImageRef previousImage = CGBitmapContextCreateImage(_blendCanvas); CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } imageRef = CGBitmapContextCreateImage(_blendCanvas); CGContextClearRect(_blendCanvas, CGRectMake(0, 0, _width, _height)); if (previousImage) { CGContextDrawImage(_blendCanvas, CGRectMake(0, 0, _width, _height), previousImage); CFRelease(previousImage); } } } else if (frame.dispose == YYImageDisposeBackground) { if (frame.blend == YYImageBlendOver) { CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } imageRef = CGBitmapContextCreateImage(_blendCanvas); CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); } else { CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } imageRef = CGBitmapContextCreateImage(_blendCanvas); CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); } } else { // no dispose if (frame.blend == YYImageBlendOver) { CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } imageRef = CGBitmapContextCreateImage(_blendCanvas); } else { CGImageRef unblendImage = [self _newUnblendedImageAtIndex:frame.index extendToCanvas:NO decoded:NULL]; if (unblendImage) { CGContextClearRect(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height)); CGContextDrawImage(_blendCanvas, CGRectMake(frame.offsetX, frame.offsetY, frame.width, frame.height), unblendImage); CFRelease(unblendImage); } imageRef = CGBitmapContextCreateImage(_blendCanvas); } } return imageRef; } @end //////////////////////////////////////////////////////////////////////////////// #pragma mark - Encoder @implementation YYImageEncoder { NSMutableArray *_images; NSMutableArray *_durations; } - (instancetype)init { @throw [NSException exceptionWithName:@"YYImageEncoder init error" reason:@"YYImageEncoder must be initialized with a type. Use 'initWithType:' instead." userInfo:nil]; return [self initWithType:YYImageTypeUnknown]; } - (instancetype)initWithType:(YYImageType)type { if (type == YYImageTypeUnknown || type >= YYImageTypeOther) { NSLog(@"[%s: %d] Unsupported image type:%d",__FUNCTION__, __LINE__, (int)type); return nil; } #if !YYIMAGE_WEBP_ENABLED if (type == YYImageTypeWebP) { NSLog(@"[%s: %d] WebP is not available, check the documentation to see how to install WebP component: path_to_url#installation", __FUNCTION__, __LINE__); return nil; } #endif self = [super init]; if (!self) return nil; _type = type; _images = [NSMutableArray new]; _durations = [NSMutableArray new]; switch (type) { case YYImageTypeJPEG: case YYImageTypeJPEG2000: { _quality = 0.9; } break; case YYImageTypeTIFF: case YYImageTypeBMP: case YYImageTypeGIF: case YYImageTypeICO: case YYImageTypeICNS: case YYImageTypePNG: { _quality = 1; _lossless = YES; } break; case YYImageTypeWebP: { _quality = 0.8; } break; default: break; } return self; } - (void)setQuality:(CGFloat)quality { _quality = quality < 0 ? 0 : quality > 1 ? 1 : quality; } - (void)addImage:(UIImage *)image duration:(NSTimeInterval)duration { if (!image.CGImage) return; duration = duration < 0 ? 0 : duration; [_images addObject:image]; [_durations addObject:@(duration)]; } - (void)addImageWithData:(NSData *)data duration:(NSTimeInterval)duration { if (data.length == 0) return; duration = duration < 0 ? 0 : duration; [_images addObject:data]; [_durations addObject:@(duration)]; } - (void)addImageWithFile:(NSString *)path duration:(NSTimeInterval)duration { if (path.length == 0) return; duration = duration < 0 ? 0 : duration; NSURL *url = [NSURL URLWithString:path]; if (!url) return; [_images addObject:url]; [_durations addObject:@(duration)]; } - (BOOL)_imageIOAvaliable { switch (_type) { case YYImageTypeJPEG: case YYImageTypeJPEG2000: case YYImageTypeTIFF: case YYImageTypeBMP: case YYImageTypeICO: case YYImageTypeICNS: case YYImageTypeGIF: { return _images.count > 0; } break; case YYImageTypePNG: { return _images.count == 1; } break; case YYImageTypeWebP: { return NO; } break; default: return NO; } } - (CGImageDestinationRef)_newImageDestination:(id)dest imageCount:(NSUInteger)count CF_RETURNS_RETAINED { if (!dest) return nil; CGImageDestinationRef destination = NULL; if ([dest isKindOfClass:[NSString class]]) { NSURL *url = [[NSURL alloc] initFileURLWithPath:dest]; if (url) { destination = CGImageDestinationCreateWithURL((CFURLRef)url, YYImageTypeToUTType(_type), count, NULL); } } else if ([dest isKindOfClass:[NSMutableData class]]) { destination = CGImageDestinationCreateWithData((CFMutableDataRef)dest, YYImageTypeToUTType(_type), count, NULL); } return destination; } - (void)_encodeImageWithDestination:(CGImageDestinationRef)destination imageCount:(NSUInteger)count { if (_type == YYImageTypeGIF) { NSDictionary *gifProperty = @{(__bridge id)kCGImagePropertyGIFDictionary: @{(__bridge id)kCGImagePropertyGIFLoopCount: @(_loopCount)}}; CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperty); } for (int i = 0; i < count; i++) { @autoreleasepool { id imageSrc = _images[i]; NSDictionary *frameProperty = NULL; if (_type == YYImageTypeGIF && count > 1) { frameProperty = @{(NSString *)kCGImagePropertyGIFDictionary : @{(NSString *) kCGImagePropertyGIFDelayTime:_durations[i]}}; } else { frameProperty = @{(id)kCGImageDestinationLossyCompressionQuality : @(_quality)}; } if ([imageSrc isKindOfClass:[UIImage class]]) { UIImage *image = imageSrc; if (image.imageOrientation != UIImageOrientationUp && image.CGImage) { CGBitmapInfo info = CGImageGetBitmapInfo(image.CGImage) | CGImageGetAlphaInfo(image.CGImage); CGImageRef rotated = YYCGImageCreateCopyWithOrientation(image.CGImage, image.imageOrientation, info); if (rotated) { image = [UIImage imageWithCGImage:rotated]; CFRelease(rotated); } } if (image.CGImage) CGImageDestinationAddImage(destination, ((UIImage *)imageSrc).CGImage, (CFDictionaryRef)frameProperty); } else if ([imageSrc isKindOfClass:[NSURL class]]) { CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)imageSrc, NULL); if (source) { CGImageDestinationAddImageFromSource(destination, source, 0, (CFDictionaryRef)frameProperty); CFRelease(source); } } else if ([imageSrc isKindOfClass:[NSData class]]) { CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)imageSrc, NULL); if (source) { CGImageDestinationAddImageFromSource(destination, source, 0, (CFDictionaryRef)frameProperty); CFRelease(source); } } } } } - (CGImageRef)_newCGImageFromIndex:(NSUInteger)index decoded:(BOOL)decoded CF_RETURNS_RETAINED { UIImage *image = nil; id imageSrc= _images[index]; if ([imageSrc isKindOfClass:[UIImage class]]) { image = imageSrc; } else if ([imageSrc isKindOfClass:[NSURL class]]) { image = [UIImage imageWithContentsOfFile:((NSURL *)imageSrc).absoluteString]; } else if ([imageSrc isKindOfClass:[NSData class]]) { image = [UIImage imageWithData:imageSrc]; } if (!image) return NULL; CGImageRef imageRef = image.CGImage; if (!imageRef) return NULL; if (image.imageOrientation != UIImageOrientationUp) { return YYCGImageCreateCopyWithOrientation(imageRef, image.imageOrientation, kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); } if (decoded) { return YYCGImageCreateDecodedCopy(imageRef, YES); } return (CGImageRef)CFRetain(imageRef); } - (NSData *)_encodeWithImageIO { NSMutableData *data = [NSMutableData new]; NSUInteger count = _type == YYImageTypeGIF ? _images.count : 1; CGImageDestinationRef destination = [self _newImageDestination:data imageCount:count]; BOOL suc = NO; if (destination) { [self _encodeImageWithDestination:destination imageCount:count]; suc = CGImageDestinationFinalize(destination); CFRelease(destination); } if (suc && data.length > 0) { return data; } else { return nil; } } - (BOOL)_encodeWithImageIO:(NSString *)path { NSUInteger count = _type == YYImageTypeGIF ? _images.count : 1; CGImageDestinationRef destination = [self _newImageDestination:path imageCount:count]; BOOL suc = NO; if (destination) { [self _encodeImageWithDestination:destination imageCount:count]; suc = CGImageDestinationFinalize(destination); CFRelease(destination); } return suc; } - (NSData *)_encodeAPNG { // encode APNG (ImageIO doesn't support APNG encoding, so we use a custom encoder) NSMutableArray *pngDatas = [NSMutableArray new]; NSMutableArray *pngSizes = [NSMutableArray new]; NSUInteger canvasWidth = 0, canvasHeight = 0; for (int i = 0; i < _images.count; i++) { CGImageRef decoded = [self _newCGImageFromIndex:i decoded:YES]; if (!decoded) return nil; CGSize size = CGSizeMake(CGImageGetWidth(decoded), CGImageGetHeight(decoded)); [pngSizes addObject:[NSValue valueWithCGSize:size]]; if (canvasWidth < size.width) canvasWidth = size.width; if (canvasHeight < size.height) canvasHeight = size.height; CFDataRef frameData = YYCGImageCreateEncodedData(decoded, YYImageTypePNG, 1); CFRelease(decoded); if (!frameData) return nil; [pngDatas addObject:(__bridge id)(frameData)]; CFRelease(frameData); if (size.width < 1 || size.height < 1) return nil; } CGSize firstFrameSize = [(NSValue *)[pngSizes firstObject] CGSizeValue]; if (firstFrameSize.width < canvasWidth || firstFrameSize.height < canvasHeight) { CGImageRef decoded = [self _newCGImageFromIndex:0 decoded:YES]; if (!decoded) return nil; CGContextRef context = CGBitmapContextCreate(NULL, canvasWidth, canvasHeight, 8, 0, YYCGColorSpaceGetDeviceRGB(), kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); if (!context) { CFRelease(decoded); return nil; } CGContextDrawImage(context, CGRectMake(0, canvasHeight - firstFrameSize.height, firstFrameSize.width, firstFrameSize.height), decoded); CFRelease(decoded); CGImageRef extendedImage = CGBitmapContextCreateImage(context); CFRelease(context); if (!extendedImage) return nil; CFDataRef frameData = YYCGImageCreateEncodedData(extendedImage, YYImageTypePNG, 1); if (!frameData) { CFRelease(extendedImage); return nil; } pngDatas[0] = (__bridge id)(frameData); CFRelease(frameData); } NSData *firstFrameData = pngDatas[0]; yy_png_info *info = yy_png_info_create(firstFrameData.bytes, (uint32_t)firstFrameData.length); if (!info) return nil; NSMutableData *result = [NSMutableData new]; BOOL insertBefore = NO, insertAfter = NO; uint32_t apngSequenceIndex = 0; uint32_t png_header[2]; png_header[0] = YY_FOUR_CC(0x89, 0x50, 0x4E, 0x47); png_header[1] = YY_FOUR_CC(0x0D, 0x0A, 0x1A, 0x0A); [result appendBytes:png_header length:8]; for (int i = 0; i < info->chunk_num; i++) { yy_png_chunk_info *chunk = info->chunks + i; if (!insertBefore && chunk->fourcc == YY_FOUR_CC('I', 'D', 'A', 'T')) { insertBefore = YES; // insert acTL (APNG Control) uint32_t acTL[5] = {0}; acTL[0] = yy_swap_endian_uint32(8); //length acTL[1] = YY_FOUR_CC('a', 'c', 'T', 'L'); // fourcc acTL[2] = yy_swap_endian_uint32((uint32_t)pngDatas.count); // num frames acTL[3] = yy_swap_endian_uint32((uint32_t)_loopCount); // num plays acTL[4] = yy_swap_endian_uint32((uint32_t)crc32(0, (const Bytef *)(acTL + 1), 12)); //crc32 [result appendBytes:acTL length:20]; // insert fcTL (first frame control) yy_png_chunk_fcTL chunk_fcTL = {0}; chunk_fcTL.sequence_number = apngSequenceIndex; chunk_fcTL.width = (uint32_t)firstFrameSize.width; chunk_fcTL.height = (uint32_t)firstFrameSize.height; yy_png_delay_to_fraction([(NSNumber *)_durations[0] doubleValue], &chunk_fcTL.delay_num, &chunk_fcTL.delay_den); chunk_fcTL.delay_num = chunk_fcTL.delay_num; chunk_fcTL.delay_den = chunk_fcTL.delay_den; chunk_fcTL.dispose_op = YY_PNG_DISPOSE_OP_BACKGROUND; chunk_fcTL.blend_op = YY_PNG_BLEND_OP_SOURCE; uint8_t fcTL[38] = {0}; *((uint32_t *)fcTL) = yy_swap_endian_uint32(26); //length *((uint32_t *)(fcTL + 4)) = YY_FOUR_CC('f', 'c', 'T', 'L'); // fourcc yy_png_chunk_fcTL_write(&chunk_fcTL, fcTL + 8); *((uint32_t *)(fcTL + 34)) = yy_swap_endian_uint32((uint32_t)crc32(0, (const Bytef *)(fcTL + 4), 30)); [result appendBytes:fcTL length:38]; apngSequenceIndex++; } if (!insertAfter && insertBefore && chunk->fourcc != YY_FOUR_CC('I', 'D', 'A', 'T')) { insertAfter = YES; // insert fcTL and fdAT (APNG frame control and data) for (int i = 1; i < pngDatas.count; i++) { NSData *frameData = pngDatas[i]; yy_png_info *frame = yy_png_info_create(frameData.bytes, (uint32_t)frameData.length); if (!frame) { yy_png_info_release(info); return nil; } // insert fcTL (first frame control) yy_png_chunk_fcTL chunk_fcTL = {0}; chunk_fcTL.sequence_number = apngSequenceIndex; chunk_fcTL.width = frame->header.width; chunk_fcTL.height = frame->header.height; yy_png_delay_to_fraction([(NSNumber *)_durations[i] doubleValue], &chunk_fcTL.delay_num, &chunk_fcTL.delay_den); chunk_fcTL.delay_num = chunk_fcTL.delay_num; chunk_fcTL.delay_den = chunk_fcTL.delay_den; chunk_fcTL.dispose_op = YY_PNG_DISPOSE_OP_BACKGROUND; chunk_fcTL.blend_op = YY_PNG_BLEND_OP_SOURCE; uint8_t fcTL[38] = {0}; *((uint32_t *)fcTL) = yy_swap_endian_uint32(26); //length *((uint32_t *)(fcTL + 4)) = YY_FOUR_CC('f', 'c', 'T', 'L'); // fourcc yy_png_chunk_fcTL_write(&chunk_fcTL, fcTL + 8); *((uint32_t *)(fcTL + 34)) = yy_swap_endian_uint32((uint32_t)crc32(0, (const Bytef *)(fcTL + 4), 30)); [result appendBytes:fcTL length:38]; apngSequenceIndex++; // insert fdAT (frame data) for (int d = 0; d < frame->chunk_num; d++) { yy_png_chunk_info *dchunk = frame->chunks + d; if (dchunk->fourcc == YY_FOUR_CC('I', 'D', 'A', 'T')) { uint32_t length = yy_swap_endian_uint32(dchunk->length + 4); [result appendBytes:&length length:4]; //length uint32_t fourcc = YY_FOUR_CC('f', 'd', 'A', 'T'); [result appendBytes:&fourcc length:4]; //fourcc uint32_t sq = yy_swap_endian_uint32(apngSequenceIndex); [result appendBytes:&sq length:4]; //data (sq) [result appendBytes:(((uint8_t *)frameData.bytes) + dchunk->offset + 8) length:dchunk->length]; //data uint8_t *bytes = ((uint8_t *)result.bytes) + result.length - dchunk->length - 8; uint32_t crc = yy_swap_endian_uint32((uint32_t)crc32(0, bytes, dchunk->length + 8)); [result appendBytes:&crc length:4]; //crc apngSequenceIndex++; } } yy_png_info_release(frame); } } [result appendBytes:((uint8_t *)firstFrameData.bytes) + chunk->offset length:chunk->length + 12]; } yy_png_info_release(info); return result; } - (NSData *)_encodeWebP { #if YYIMAGE_WEBP_ENABLED // encode webp NSMutableArray *webpDatas = [NSMutableArray new]; for (NSUInteger i = 0; i < _images.count; i++) { CGImageRef image = [self _newCGImageFromIndex:i decoded:NO]; if (!image) return nil; CFDataRef frameData = YYCGImageCreateEncodedWebPData(image, _lossless, _quality, 4, YYImagePresetDefault); CFRelease(image); if (!frameData) return nil; [webpDatas addObject:(__bridge id)frameData]; CFRelease(frameData); } if (webpDatas.count == 1) { return webpDatas.firstObject; } else { // multi-frame webp WebPMux *mux = WebPMuxNew(); if (!mux) return nil; for (NSUInteger i = 0; i < _images.count; i++) { NSData *data = webpDatas[i]; NSNumber *duration = _durations[i]; WebPMuxFrameInfo frame = {0}; frame.bitstream.bytes = data.bytes; frame.bitstream.size = data.length; frame.duration = (int)(duration.floatValue * 1000.0); frame.id = WEBP_CHUNK_ANMF; frame.dispose_method = WEBP_MUX_DISPOSE_BACKGROUND; frame.blend_method = WEBP_MUX_NO_BLEND; if (WebPMuxPushFrame(mux, &frame, 0) != WEBP_MUX_OK) { WebPMuxDelete(mux); return nil; } } WebPMuxAnimParams params = {(uint32_t)0, (int)_loopCount}; if (WebPMuxSetAnimationParams(mux, &params) != WEBP_MUX_OK) { WebPMuxDelete(mux); return nil; } WebPData output_data; WebPMuxError error = WebPMuxAssemble(mux, &output_data); WebPMuxDelete(mux); if (error != WEBP_MUX_OK) { return nil; } NSData *result = [NSData dataWithBytes:output_data.bytes length:output_data.size]; WebPDataClear(&output_data); return result.length ? result : nil; } #else return nil; #endif } - (NSData *)encode { if (_images.count == 0) return nil; if ([self _imageIOAvaliable]) return [self _encodeWithImageIO]; if (_type == YYImageTypePNG) return [self _encodeAPNG]; if (_type == YYImageTypeWebP) return [self _encodeWebP]; return nil; } - (BOOL)encodeToFile:(NSString *)path { if (_images.count == 0 || path.length == 0) return NO; if ([self _imageIOAvaliable]) return [self _encodeWithImageIO:path]; NSData *data = [self encode]; if (!data) return NO; return [data writeToFile:path atomically:YES]; } + (NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality { YYImageEncoder *encoder = [[YYImageEncoder alloc] initWithType:type]; encoder.quality = quality; [encoder addImage:image duration:0]; return [encoder encode]; } + (NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality { if (!decoder || decoder.frameCount == 0) return nil; YYImageEncoder *encoder = [[YYImageEncoder alloc] initWithType:type]; encoder.quality = quality; for (int i = 0; i < decoder.frameCount; i++) { UIImage *frame = [decoder frameAtIndex:i decodeForDisplay:YES].image; [encoder addImageWithData:UIImagePNGRepresentation(frame) duration:[decoder frameDurationAtIndex:i]]; } return encoder.encode; } @end @implementation UIImage (YYImageCoder) - (instancetype)imageByDecoded { if (self.isDecodedForDisplay) return self; CGImageRef imageRef = self.CGImage; if (!imageRef) return self; CGImageRef newImageRef = YYCGImageCreateDecodedCopy(imageRef, YES); if (!newImageRef) return self; UIImage *newImage = [[self.class alloc] initWithCGImage:newImageRef scale:self.scale orientation:self.imageOrientation]; CGImageRelease(newImageRef); if (!newImage) newImage = self; // decode failed, return self. newImage.isDecodedForDisplay = YES; return newImage; } - (BOOL)isDecodedForDisplay { if (self.images.count > 1) return YES; NSNumber *num = objc_getAssociatedObject(self, @selector(isDecodedForDisplay)); return [num boolValue]; } - (void)setIsDecodedForDisplay:(BOOL)isDecodedForDisplay { objc_setAssociatedObject(self, @selector(isDecodedForDisplay), @(isDecodedForDisplay), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)saveToAlbumWithCompletionBlock:(void(^)(NSURL *assetURL, NSError *error))completionBlock { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *data = [self _imageDataRepresentationForSystem:YES]; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:^(NSURL *assetURL, NSError *error){ if (!completionBlock) return; if (pthread_main_np()) { completionBlock(assetURL, error); } else { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(assetURL, error); }); } }]; }); } - (NSData *)imageDataRepresentation { return [self _imageDataRepresentationForSystem:NO]; } /// @param forSystem YES: used for system album (PNG/JPEG/GIF), NO: used for YYImage (PNG/JPEG/GIF/WebP) - (NSData *)_imageDataRepresentationForSystem:(BOOL)forSystem { NSData *data = nil; if ([self isKindOfClass:[YYImage class]]) { YYImage *image = (id)self; if (image.animatedImageData) { if (forSystem) { // system only support GIF and PNG if (image.animatedImageType == YYImageTypeGIF || image.animatedImageType == YYImageTypePNG) { data = image.animatedImageData; } } else { data = image.animatedImageData; } } } if (!data) { CGImageRef imageRef = self.CGImage ? (CGImageRef)CFRetain(self.CGImage) : nil; if (imageRef) { CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef) & kCGBitmapAlphaInfoMask; BOOL hasAlpha = NO; if (alphaInfo == kCGImageAlphaPremultipliedLast || alphaInfo == kCGImageAlphaPremultipliedFirst || alphaInfo == kCGImageAlphaLast || alphaInfo == kCGImageAlphaFirst) { hasAlpha = YES; } if (self.imageOrientation != UIImageOrientationUp) { CGImageRef rotated = YYCGImageCreateCopyWithOrientation(imageRef, self.imageOrientation, bitmapInfo | alphaInfo); if (rotated) { CFRelease(imageRef); imageRef = rotated; } } @autoreleasepool { UIImage *newImage = [UIImage imageWithCGImage:imageRef]; if (newImage) { if (hasAlpha) { data = UIImagePNGRepresentation([UIImage imageWithCGImage:imageRef]); } else { data = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 0.9); // same as Apple's example } } } CFRelease(imageRef); } } if (!data) { data = UIImagePNGRepresentation(self); } return data; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYImageCoder.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
28,241
```objective-c // // YYFrameImage.m // YYKit <path_to_url // // Created by ibireme on 14/12/9. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYFrameImage.h" #import "NSString+YYAdd.h" #import "UIImage+YYAdd.h" #import "YYImageCoder.h" @implementation YYFrameImage { NSUInteger _loopCount; NSUInteger _oneFrameBytes; NSArray *_imagePaths; NSArray *_imageDatas; NSArray *_frameDurations; } - (instancetype)initWithImagePaths:(NSArray *)paths oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount { NSMutableArray *durations = [NSMutableArray new]; for (int i = 0, max = (int)paths.count; i < max; i++) { [durations addObject:@(oneFrameDuration)]; } return [self initWithImagePaths:paths frameDurations:durations loopCount:loopCount]; } - (instancetype)initWithImagePaths:(NSArray *)paths frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount { if (paths.count == 0) return nil; if (paths.count != frameDurations.count) return nil; NSString *firstPath = paths[0]; NSData *firstData = [NSData dataWithContentsOfFile:firstPath]; CGFloat scale = firstPath.pathScale; UIImage *firstCG = [[[UIImage alloc] initWithData:firstData] imageByDecoded]; self = [self initWithCGImage:firstCG.CGImage scale:scale orientation:UIImageOrientationUp]; if (!self) return nil; long frameByte = CGImageGetBytesPerRow(firstCG.CGImage) * CGImageGetHeight(firstCG.CGImage); _oneFrameBytes = (NSUInteger)frameByte; _imagePaths = paths.copy; _frameDurations = frameDurations.copy; _loopCount = loopCount; return self; } - (instancetype)initWithImageDataArray:(NSArray *)dataArray oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount { NSMutableArray *durations = [NSMutableArray new]; for (int i = 0, max = (int)dataArray.count; i < max; i++) { [durations addObject:@(oneFrameDuration)]; } return [self initWithImageDataArray:dataArray frameDurations:durations loopCount:loopCount]; } - (instancetype)initWithImageDataArray:(NSArray *)dataArray frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount { if (dataArray.count == 0) return nil; if (dataArray.count != frameDurations.count) return nil; NSData *firstData = dataArray[0]; CGFloat scale = [UIScreen mainScreen].scale; UIImage *firstCG = [[[UIImage alloc] initWithData:firstData] imageByDecoded]; self = [self initWithCGImage:firstCG.CGImage scale:scale orientation:UIImageOrientationUp]; if (!self) return nil; long frameByte = CGImageGetBytesPerRow(firstCG.CGImage) * CGImageGetHeight(firstCG.CGImage); _oneFrameBytes = (NSUInteger)frameByte; _imageDatas = dataArray.copy; _frameDurations = frameDurations.copy; _loopCount = loopCount; return self; } #pragma mark - YYAnimtedImage - (NSUInteger)animatedImageFrameCount { if (_imagePaths) { return _imagePaths.count; } else if (_imageDatas) { return _imageDatas.count; } else { return 1; } } - (NSUInteger)animatedImageLoopCount { return _loopCount; } - (NSUInteger)animatedImageBytesPerFrame { return _oneFrameBytes; } - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { if (_imagePaths) { if (index >= _imagePaths.count) return nil; NSString *path = _imagePaths[index]; CGFloat scale = [path pathScale]; NSData *data = [NSData dataWithContentsOfFile:path]; return [[UIImage imageWithData:data scale:scale] imageByDecoded]; } else if (_imageDatas) { if (index >= _imageDatas.count) return nil; NSData *data = _imageDatas[index]; return [[UIImage imageWithData:data scale:[UIScreen mainScreen].scale] imageByDecoded]; } else { return index == 0 ? self : nil; } } - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { if (index >= _frameDurations.count) return 0; NSNumber *num = _frameDurations[index]; return [num doubleValue]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYFrameImage.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,012
```objective-c // // YYWebImageManager.m // YYKit <path_to_url // // Created by ibireme on 15/2/19. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYWebImageManager.h" #import "YYImageCache.h" #import "YYWebImageOperation.h" #import "YYImageCoder.h" @implementation YYWebImageManager + (instancetype)sharedManager { static YYWebImageManager *manager; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ YYImageCache *cache = [YYImageCache sharedCache]; NSOperationQueue *queue = [NSOperationQueue new]; if ([queue respondsToSelector:@selector(setQualityOfService:)]) { queue.qualityOfService = NSQualityOfServiceBackground; } manager = [[self alloc] initWithCache:cache queue:queue]; }); return manager; } - (instancetype)init { @throw [NSException exceptionWithName:@"YYWebImageManager init error" reason:@"Use the designated initializer to init." userInfo:nil]; return [self initWithCache:nil queue:nil]; } - (instancetype)initWithCache:(YYImageCache *)cache queue:(NSOperationQueue *)queue{ self = [super init]; if (!self) return nil; _cache = cache; _queue = queue; _timeout = 15.0; if (YYImageWebPAvailable()) { _headers = @{ @"Accept" : @"image/webp,image/*;q=0.8" }; } else { _headers = @{ @"Accept" : @"image/*;q=0.8" }; } return self; } - (YYWebImageOperation *)requestImageWithURL:(NSURL *)url options:(YYWebImageOptions)options progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.timeoutInterval = _timeout; request.HTTPShouldHandleCookies = (options & YYWebImageOptionHandleCookies) != 0; request.allHTTPHeaderFields = [self headersForURL:url]; request.HTTPShouldUsePipelining = YES; request.cachePolicy = (options & YYWebImageOptionUseNSURLCache) ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData; YYWebImageOperation *operation = [[YYWebImageOperation alloc] initWithRequest:request options:options cache:_cache cacheKey:[self cacheKeyForURL:url] progress:progress transform:transform ? transform : _sharedTransformBlock completion:completion]; if (_username && _password) { operation.credential = [NSURLCredential credentialWithUser:_username password:_password persistence:NSURLCredentialPersistenceForSession]; } if (operation) { NSOperationQueue *queue = _queue; if (queue) { [queue addOperation:operation]; } else { [operation start]; } } return operation; } - (NSDictionary *)headersForURL:(NSURL *)url { if (!url) return nil; return _headersFilter ? _headersFilter(url, _headers) : _headers; } - (NSString *)cacheKeyForURL:(NSURL *)url { if (!url) return nil; return _cacheKeyFilter ? _cacheKeyFilter(url) : url.absoluteString; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYWebImageManager.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
758
```objective-c // // YYSpriteImage.h // YYKit <path_to_url // // Created by ibireme on 15/4/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYAnimatedImageView.h> #else #import "YYAnimatedImageView.h" #endif NS_ASSUME_NONNULL_BEGIN /** An image to display sprite sheet animation. @discussion It is a fully compatible `UIImage` subclass. The animation can be played by YYAnimatedImageView. Sample Code: // 8 * 12 sprites in a single sheet image UIImage *spriteSheet = [UIImage imageNamed:@"sprite-sheet"]; NSMutableArray *contentRects = [NSMutableArray new]; NSMutableArray *durations = [NSMutableArray new]; for (int j = 0; j < 12; j++) { for (int i = 0; i < 8; i++) { CGRect rect; rect.size = CGSizeMake(img.size.width / 8, img.size.height / 12); rect.origin.x = img.size.width / 8 * i; rect.origin.y = img.size.height / 12 * j; [contentRects addObject:[NSValue valueWithCGRect:rect]]; [durations addObject:@(1 / 60.0)]; } } YYSpriteSheetImage *sprite; sprite = [[YYSpriteSheetImage alloc] initWithSpriteSheetImage:img contentRects:contentRects frameDurations:durations loopCount:0]; YYAnimatedImageView *imgView = [YYAnimatedImageView new]; imgView.size = CGSizeMake(img.size.width / 8, img.size.height / 12); imgView.image = sprite; @discussion It can also be used to display single frame in sprite sheet image. Sample Code: YYSpriteSheetImage *sheet = ...; UIImageView *imageView = ...; imageView.image = sheet; imageView.layer.contentsRect = [sheet contentsRectForCALayerAtIndex:6]; */ @interface YYSpriteSheetImage : UIImage <YYAnimatedImage> /** Creates and returns an image object. @param image The sprite sheet image (contains all frames). @param contentRects The sprite sheet image frame rects in the image coordinates. The rectangle should not outside the image's bounds. The objects in this array should be created with [NSValue valueWithCGRect:]. @param frameDurations The sprite sheet image frame's durations in seconds. The objects in this array should be NSNumber. @param loopCount Animation loop count, 0 means infinite looping. @return An image object, or nil if an error occurs. */ - (nullable instancetype)initWithSpriteSheetImage:(UIImage *)image contentRects:(NSArray<NSValue *> *)contentRects frameDurations:(NSArray<NSNumber *> *)frameDurations loopCount:(NSUInteger)loopCount; @property (nonatomic, readonly) NSArray<NSValue *> *contentRects; @property (nonatomic, readonly) NSArray<NSValue *> *frameDurations; @property (nonatomic, readonly) NSUInteger loopCount; /** Get the contents rect for CALayer. See "contentsRect" property in CALayer for more information. @param index Index of frame. @return Contents Rect. */ - (CGRect)contentsRectForCALayerAtIndex:(NSUInteger)index; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYSpriteSheetImage.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
757
```objective-c // // CALayer+YYWebImage.h // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYWebImageManager.h> #else #import "YYWebImageManager.h" #endif NS_ASSUME_NONNULL_BEGIN /** Web image methods for CALayer. It will set image to layer.contents. */ @interface CALayer (YYWebImage) #pragma mark - image /** Current image URL. @discussion Set a new value to this property will cancel the previous request operation and create a new request operation to fetch image. Set nil to clear the image and image URL. */ @property (nullable, nonatomic, strong) NSURL *imageURL; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param options The options to use when request the image. */ - (void)setImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder he image to be set initially, until the image request finishes. @param options The options to use when request the image. @param manager The manager to create image request operation. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options manager:(nullable YYWebImageManager *)manager progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Cancel the current image request. */ - (void)cancelCurrentImageRequest; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/CALayer+YYWebImage.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
855
```objective-c // // _YYWebImageSetter.m // YYKit <path_to_url // // Created by ibireme on 15/7/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "_YYWebImageSetter.h" #import "YYWebImageOperation.h" #import <libkern/OSAtomic.h> NSString *const _YYWebImageFadeAnimationKey = @"YYWebImageFade"; const NSTimeInterval _YYWebImageFadeTime = 0.2; const NSTimeInterval _YYWebImageProgressiveFadeTime = 0.4; @implementation _YYWebImageSetter { dispatch_semaphore_t _lock; NSURL *_imageURL; NSOperation *_operation; int32_t _sentinel; } - (instancetype)init { self = [super init]; _lock = dispatch_semaphore_create(1); return self; } - (NSURL *)imageURL { dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); NSURL *imageURL = _imageURL; dispatch_semaphore_signal(_lock); return imageURL; } - (void)dealloc { OSAtomicIncrement32(&_sentinel); [_operation cancel]; } - (int32_t)setOperationWithSentinel:(int32_t)sentinel url:(NSURL *)imageURL options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { if (sentinel != _sentinel) { if (completion) completion(nil, imageURL, YYWebImageFromNone, YYWebImageStageCancelled, nil); return _sentinel; } NSOperation *operation = [manager requestImageWithURL:imageURL options:options progress:progress transform:transform completion:completion]; if (!operation && completion) { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"YYWebImageOperation create failed." }; completion(nil, imageURL, YYWebImageFromNone, YYWebImageStageFinished, [NSError errorWithDomain:@"com.ibireme.yykit.webimage" code:-1 userInfo:userInfo]); } dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); if (sentinel == _sentinel) { if (_operation) [_operation cancel]; _operation = operation; sentinel = OSAtomicIncrement32(&_sentinel); } else { [operation cancel]; } dispatch_semaphore_signal(_lock); return sentinel; } - (int32_t)cancel { return [self cancelWithNewURL:nil]; } - (int32_t)cancelWithNewURL:(NSURL *)imageURL { int32_t sentinel; dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); if (_operation) { [_operation cancel]; _operation = nil; } _imageURL = imageURL; sentinel = OSAtomicIncrement32(&_sentinel); dispatch_semaphore_signal(_lock); return sentinel; } + (dispatch_queue_t)setterQueue { static dispatch_queue_t queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ queue = dispatch_queue_create("com.ibireme.yykit.webimage.setter", DISPATCH_QUEUE_SERIAL); dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); }); return queue; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/_YYWebImageSetter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
741
```objective-c // // YYImageCoder.h // YYKit <path_to_url // // Created by ibireme on 15/5/13. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** Image file type. */ typedef NS_ENUM(NSUInteger, YYImageType) { YYImageTypeUnknown = 0, ///< unknown YYImageTypeJPEG, ///< jpeg, jpg YYImageTypeJPEG2000, ///< jp2 YYImageTypeTIFF, ///< tiff, tif YYImageTypeBMP, ///< bmp YYImageTypeICO, ///< ico YYImageTypeICNS, ///< icns YYImageTypeGIF, ///< gif YYImageTypePNG, ///< png YYImageTypeWebP, ///< webp YYImageTypeOther, ///< other image format }; /** Dispose method specifies how the area used by the current frame is to be treated before rendering the next frame on the canvas. */ typedef NS_ENUM(NSUInteger, YYImageDisposeMethod) { /** No disposal is done on this frame before rendering the next; the contents of the canvas are left as is. */ YYImageDisposeNone = 0, /** The frame's region of the canvas is to be cleared to fully transparent black before rendering the next frame. */ YYImageDisposeBackground, /** The frame's region of the canvas is to be reverted to the previous contents before rendering the next frame. */ YYImageDisposePrevious, }; /** Blend operation specifies how transparent pixels of the current frame are blended with those of the previous canvas. */ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) { /** All color components of the frame, including alpha, overwrite the current contents of the frame's canvas region. */ YYImageBlendNone = 0, /** The frame should be composited onto the output buffer based on its alpha. */ YYImageBlendOver, }; /** An image frame object. */ @interface YYImageFrame : NSObject <NSCopying> @property (nonatomic) NSUInteger index; ///< Frame index (zero based) @property (nonatomic) NSUInteger width; ///< Frame width @property (nonatomic) NSUInteger height; ///< Frame height @property (nonatomic) NSUInteger offsetX; ///< Frame origin.x in canvas (left-bottom based) @property (nonatomic) NSUInteger offsetY; ///< Frame origin.y in canvas (left-bottom based) @property (nonatomic) NSTimeInterval duration; ///< Frame duration in seconds @property (nonatomic) YYImageDisposeMethod dispose; ///< Frame dispose method. @property (nonatomic) YYImageBlendOperation blend; ///< Frame blend operation. @property (nullable, nonatomic, strong) UIImage *image; ///< The image. + (instancetype)frameWithImage:(UIImage *)image; @end #pragma mark - Decoder /** An image decoder to decode image data. @discussion This class supports decoding animated WebP, APNG, GIF and system image format such as PNG, JPG, JP2, BMP, TIFF, PIC, ICNS and ICO. It can be used to decode complete image data, or to decode incremental image data during image download. This class is thread-safe. Example: // Decode single image: NSData *data = [NSData dataWithContentOfFile:@"/tmp/image.webp"]; YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:2.0]; UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image; // Decode image during download: NSMutableData *data = [NSMutableData new]; YYImageDecoder *decoder = [[YYImageDecoder alloc] initWithScale:2.0]; while(newDataArrived) { [data appendData:newData]; [decoder updateData:data final:NO]; if (decoder.frameCount > 0) { UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image; // progressive display... } } [decoder updateData:data final:YES]; UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image; // final display... */ @interface YYImageDecoder : NSObject @property (nullable, nonatomic, readonly) NSData *data; ///< Image data. @property (nonatomic, readonly) YYImageType type; ///< Image data type. @property (nonatomic, readonly) CGFloat scale; ///< Image scale. @property (nonatomic, readonly) NSUInteger frameCount; ///< Image frame count. @property (nonatomic, readonly) NSUInteger loopCount; ///< Image loop count, 0 means infinite. @property (nonatomic, readonly) NSUInteger width; ///< Image canvas width. @property (nonatomic, readonly) NSUInteger height; ///< Image canvas height. @property (nonatomic, readonly, getter=isFinalized) BOOL finalized; /** Creates an image decoder. @param scale Image's scale. @return An image decoder. */ - (instancetype)initWithScale:(CGFloat)scale NS_DESIGNATED_INITIALIZER; /** Updates the incremental image with new data. @discussion You can use this method to decode progressive/interlaced/baseline image when you do not have the complete image data. The `data` was retained by decoder, you should not modify the data in other thread during decoding. @param data The data to add to the image decoder. Each time you call this function, the 'data' parameter must contain all of the image file data accumulated so far. @param final A value that specifies whether the data is the final set. Pass YES if it is, NO otherwise. When the data is already finalized, you can not update the data anymore. @return Whether succeed. */ - (BOOL)updateData:(nullable NSData *)data final:(BOOL)final; /** Convenience method to create a decoder with specified data. @param data Image data. @param scale Image's scale. @return A new decoder, or nil if an error occurs. */ + (nullable instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale; /** Decodes and returns a frame from a specified index. @param index Frame image index (zero-based). @param decodeForDisplay Whether decode the image to memory bitmap for display. If NO, it will try to returns the original frame data without blend. @return A new frame with image, or nil if an error occurs. */ - (nullable YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay; /** Returns the frame duration from a specified index. @param index Frame image (zero-based). @return Duration in seconds. */ - (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index; /** Returns the frame's properties. See "CGImageProperties.h" in ImageIO.framework for more information. @param index Frame image index (zero-based). @return The ImageIO frame property. */ - (nullable NSDictionary *)framePropertiesAtIndex:(NSUInteger)index; /** Returns the image's properties. See "CGImageProperties.h" in ImageIO.framework for more information. */ - (nullable NSDictionary *)imageProperties; @end #pragma mark - Encoder /** An image encoder to encode image to data. @discussion It supports encoding single frame image with the type defined in YYImageType. It also supports encoding multi-frame image with GIF, APNG and WebP. Example: YYImageEncoder *jpegEncoder = [[YYImageEncoder alloc] initWithType:YYImageTypeJPEG]; jpegEncoder.quality = 0.9; [jpegEncoder addImage:image duration:0]; NSData jpegData = [jpegEncoder encode]; YYImageEncoder *gifEncoder = [[YYImageEncoder alloc] initWithType:YYImageTypeGIF]; gifEncoder.loopCount = 5; [gifEncoder addImage:image0 duration:0.1]; [gifEncoder addImage:image1 duration:0.15]; [gifEncoder addImage:image2 duration:0.2]; NSData gifData = [gifEncoder encode]; @warning It just pack the images together when encoding multi-frame image. If you want to reduce the image file size, try imagemagick/ffmpeg for GIF and WebP, and apngasm for APNG. */ @interface YYImageEncoder : NSObject @property (nonatomic, readonly) YYImageType type; ///< Image type. @property (nonatomic) NSUInteger loopCount; ///< Loop count, 0 means infinit, only available for GIF/APNG/WebP. @property (nonatomic) BOOL lossless; ///< Lossless, only available for WebP. @property (nonatomic) CGFloat quality; ///< Compress quality, 0.0~1.0, only available for JPG/JP2/WebP. - (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)new UNAVAILABLE_ATTRIBUTE; /** Create an image encoder with a specified type. @param type Image type. @return A new encoder, or nil if an error occurs. */ - (nullable instancetype)initWithType:(YYImageType)type NS_DESIGNATED_INITIALIZER; /** Add an image to encoder. @param image Image. @param duration Image duration for animation. Pass 0 to ignore this parameter. */ - (void)addImage:(UIImage *)image duration:(NSTimeInterval)duration; /** Add an image with image data to encoder. @param data Image data. @param duration Image duration for animation. Pass 0 to ignore this parameter. */ - (void)addImageWithData:(NSData *)data duration:(NSTimeInterval)duration; /** Add an image from a file path to encoder. @param image Image file path. @param duration Image duration for animation. Pass 0 to ignore this parameter. */ - (void)addImageWithFile:(NSString *)path duration:(NSTimeInterval)duration; /** Encodes the image and returns the image data. @return The image data, or nil if an error occurs. */ - (nullable NSData *)encode; /** Encodes the image to a file. @param path The file path (overwrite if exist). @return Whether succeed. */ - (BOOL)encodeToFile:(NSString *)path; /** Convenience method to encode single frame image. @param image The image. @param type The destination image type. @param quality Image quality, 0.0~1.0. @return The image data, or nil if an error occurs. */ + (nullable NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality; /** Convenience method to encode image from a decoder. @param decoder The image decoder. @param type The destination image type; @param quality Image quality, 0.0~1.0. @return The image data, or nil if an error occurs. */ + (nullable NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality; @end #pragma mark - UIImage @interface UIImage (YYImageCoder) /** Decompress this image to bitmap, so when the image is displayed on screen, the main thread won't be blocked by additional decode. If the image has already been decoded or unable to decode, it just returns itself. @return an image decoded, or just return itself if no needed. @see isDecodedForDisplay */ - (instancetype)imageByDecoded; /** Wherher the image can be display on screen without additional decoding. @warning It just a hint for your code, change it has no other effect. */ @property (nonatomic) BOOL isDecodedForDisplay; /** Saves this image to iOS Photos Album. @discussion This method attempts to save the original data to album if the image is created from an animated GIF/APNG, otherwise, it will save the image as JPEG or PNG (based on the alpha information). @param completionBlock The block invoked (in main thread) after the save operation completes. assetURL: An URL that identifies the saved image file. If the image is not saved, assetURL is nil. error: If the image is not saved, an error object that describes the reason for failure, otherwise nil. */ - (void)saveToAlbumWithCompletionBlock:(nullable void(^)(NSURL * _Nullable assetURL, NSError * _Nullable error))completionBlock; /** Return a 'best' data representation for this image. @discussion The convertion based on these rule: 1. If the image is created from an animated GIF/APNG/WebP, it returns the original data. 2. It returns PNG or JPEG(0.9) representation based on the alpha information. @return Image data, or nil if an error occurs. */ - (nullable NSData *)imageDataRepresentation; @end #pragma mark - Helper /// Detect a data's image type by reading the data's header 16 bytes (very fast). CG_EXTERN YYImageType YYImageDetectType(CFDataRef data); /// Convert YYImageType to UTI (such as kUTTypeJPEG). CG_EXTERN CFStringRef _Nullable YYImageTypeToUTType(YYImageType type); /// Convert UTI (such as kUTTypeJPEG) to YYImageType. CG_EXTERN YYImageType YYImageTypeFromUTType(CFStringRef uti); /// Get image type's file extension (such as @"jpg"). CG_EXTERN NSString *_Nullable YYImageTypeGetExtension(YYImageType type); /// Returns the shared DeviceRGB color space. CG_EXTERN CGColorSpaceRef YYCGColorSpaceGetDeviceRGB(); /// Returns the shared DeviceGray color space. CG_EXTERN CGColorSpaceRef YYCGColorSpaceGetDeviceGray(); /// Returns whether a color space is DeviceRGB. CG_EXTERN BOOL YYCGColorSpaceIsDeviceRGB(CGColorSpaceRef space); /// Returns whether a color space is DeviceGray. CG_EXTERN BOOL YYCGColorSpaceIsDeviceGray(CGColorSpaceRef space); /// Convert EXIF orientation value to UIImageOrientation. CG_EXTERN UIImageOrientation YYUIImageOrientationFromEXIFValue(NSInteger value); /// Convert UIImageOrientation to EXIF orientation value. CG_EXTERN NSInteger YYUIImageOrientationToEXIFValue(UIImageOrientation orientation); /** Create a decoded image. @discussion If the source image is created from a compressed image data (such as PNG or JPEG), you can use this method to decode the image. After decoded, you can access the decoded bytes with CGImageGetDataProvider() and CGDataProviderCopyData() without additional decode process. If the image has already decoded, this method just copy the decoded bytes to the new image. @param imageRef The source image. @param decodeForDisplay If YES, this method will decode the image and convert it to BGRA8888 (premultiplied) or BGRX8888 format for CALayer display. @return A decoded image, or NULL if an error occurs. */ CG_EXTERN CGImageRef _Nullable YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay); /** Create an image copy with an orientation. @param imageRef Source image @param orientation Image orientation which will applied to the image. @param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888). @return A new image, or NULL if an error occurs. */ CG_EXTERN CGImageRef _Nullable YYCGImageCreateCopyWithOrientation(CGImageRef imageRef, UIImageOrientation orientation, CGBitmapInfo destBitmapInfo); /** Create an image copy with CGAffineTransform. @param imageRef Source image. @param transform Transform applied to image (left-bottom based coordinate system). @param destSize Destination image size @param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888). @return A new image, or NULL if an error occurs. */ CG_EXTERN CGImageRef _Nullable YYCGImageCreateAffineTransformCopy(CGImageRef imageRef, CGAffineTransform transform, CGSize destSize, CGBitmapInfo destBitmapInfo); /** Encode an image to data with CGImageDestination. @param imageRef The image. @param type The image destination data type. @param quality The quality (0.0~1.0) @return A new image data, or nil if an error occurs. */ CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality); /** Whether WebP is available in YYImage. */ CG_EXTERN BOOL YYImageWebPAvailable(); /** Get a webp image frame count; @param webpData WebP data. @return Image frame count, or 0 if an error occurs. */ CG_EXTERN NSUInteger YYImageGetWebPFrameCount(CFDataRef webpData); /** Decode an image from WebP data, returns NULL if an error occurs. @param webpData The WebP data. @param decodeForDisplay If YES, this method will decode the image and convert it to BGRA8888 (premultiplied) format for CALayer display. @param useThreads YES to enable multi-thread decode. (speed up, but cost more CPU) @param bypassFiltering YES to skip the in-loop filtering. (speed up, but may lose some smooth) @param noFancyUpsampling YES to use faster pointwise upsampler. (speed down, and may lose some details). @return The decoded image, or NULL if an error occurs. */ CG_EXTERN CGImageRef _Nullable YYCGImageCreateWithWebPData(CFDataRef webpData, BOOL decodeForDisplay, BOOL useThreads, BOOL bypassFiltering, BOOL noFancyUpsampling); typedef NS_ENUM(NSUInteger, YYImagePreset) { YYImagePresetDefault = 0, ///< default preset. YYImagePresetPicture, ///< digital picture, like portrait, inner shot YYImagePresetPhoto, ///< outdoor photograph, with natural lighting YYImagePresetDrawing, ///< hand or line drawing, with high-contrast details YYImagePresetIcon, ///< small-sized colorful images YYImagePresetText ///< text-like }; /** Encode a CGImage to WebP data @param imageRef image @param lossless YES=lossless (similar to PNG), NO=lossy (similar to JPEG) @param quality 0.0~1.0 (0=smallest file, 1.0=biggest file) For lossless image, try the value near 1.0; for lossy, try the value near 0.8. @param compressLevel 0~6 (0=fast, 6=slower-better). Default is 4. @param preset Preset for different image type, default is YYImagePresetDefault. @return WebP data, or nil if an error occurs. */ CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedWebPData(CGImageRef imageRef, BOOL lossless, CGFloat quality, int compressLevel, YYImagePreset preset); NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/YYImageCoder.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
4,054
```objective-c // // CALayer+YYWebImage.m // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "CALayer+YYWebImage.h" #import "YYWebImageOperation.h" #import "_YYWebImageSetter.h" #import "YYKitMacro.h" #import <objc/runtime.h> YYSYNTH_DUMMY_CLASS(CALayer_YYWebImage) static int _YYWebImageSetterKey; @implementation CALayer (YYWebImage) - (NSURL *)imageURL { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); return setter.imageURL; } - (void)setImageURL:(NSURL *)imageURL { [self setImageWithURL:imageURL placeholder:nil options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder { [self setImageWithURL:imageURL placeholder:placeholder options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options { [self setImageWithURL:imageURL placeholder:nil options:options manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:nil transform:nil completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:progress transform:transform completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL]; manager = manager ? manager : [YYWebImageManager sharedManager]; _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); if (!setter) { setter = [_YYWebImageSetter new]; objc_setAssociatedObject(self, &_YYWebImageSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } int32_t sentinel = [setter cancelWithNewURL:imageURL]; dispatch_async_on_main_queue(^{ if ((options & YYWebImageOptionSetImageWithFadeAnimation) && !(options & YYWebImageOptionAvoidSetImage)) { [self removeAnimationForKey:_YYWebImageFadeAnimationKey]; } if (!imageURL) { if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.contents = (id)placeholder.CGImage; } return; } // get the image from memory as quickly as possible UIImage *imageFromMemory = nil; if (manager.cache && !(options & YYWebImageOptionUseNSURLCache) && !(options & YYWebImageOptionRefreshImageCache)) { imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory]; } if (imageFromMemory) { if (!(options & YYWebImageOptionAvoidSetImage)) { self.contents = (id)imageFromMemory.CGImage; } if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil); return; } if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.contents = (id)placeholder.CGImage; } __weak typeof(self) _self = self; dispatch_async([_YYWebImageSetter setterQueue], ^{ YYWebImageProgressBlock _progress = nil; if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) { dispatch_async(dispatch_get_main_queue(), ^{ progress(receivedSize, expectedSize); }); }; __block int32_t newSentinel = 0; __block __weak typeof(setter) weakSetter = nil; YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { __strong typeof(_self) self = _self; BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage); BOOL showFade = (options & YYWebImageOptionSetImageWithFadeAnimation); dispatch_async(dispatch_get_main_queue(), ^{ BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel; if (setImage && self && !sentinelChanged) { if (showFade) { CATransition *transition = [CATransition animation]; transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionFade; [self addAnimation:transition forKey:_YYWebImageFadeAnimationKey]; } self.contents = (id)image.CGImage; } if (completion) { if (sentinelChanged) { completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil); } else { completion(image, url, from, stage, error); } } }); }; newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion]; weakSetter = setter; }); }); } - (void)cancelCurrentImageRequest { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); if (setter) [setter cancel]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/CALayer+YYWebImage.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,472
```objective-c // // UIButton+YYWebImage.h // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYWebImageManager.h> #else #import "YYWebImageManager.h" #endif NS_ASSUME_NONNULL_BEGIN /** Web image methods for UIButton. */ @interface UIButton (YYWebImage) #pragma mark - image /** Current image URL for the specified state. @return The image URL, or nil. */ - (nullable NSURL *)imageURLForState:(UIControlState)state; /** Set the button's image with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. */ - (void)setImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder; /** Set the button's image with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param options The options to use when request the image. */ - (void)setImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state options:(YYWebImageOptions)options; /** Set the button's image with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options completion:(nullable YYWebImageCompletionBlock)completion; /** Set the button's image with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Set the button's image with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param manager The manager to create image request operation. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options manager:(nullable YYWebImageManager *)manager progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Cancel the current image request for a specified state. @param state The state that uses the specified image. */ - (void)cancelImageRequestForState:(UIControlState)state; #pragma mark - background image /** Current backgroundImage URL for the specified state. @return The image URL, or nil. */ - (nullable NSURL *)backgroundImageURLForState:(UIControlState)state; /** Set the button's backgroundImage with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. */ - (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder; /** Set the button's backgroundImage with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param options The options to use when request the image. */ - (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state options:(YYWebImageOptions)options; /** Set the button's backgroundImage with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param completion The block invoked (on main thread) when image request completed. */ - (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options completion:(nullable YYWebImageCompletionBlock)completion; /** Set the button's backgroundImage with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Set the button's backgroundImage with a specified URL for the specified state. @param imageURL The image url (remote or local file path). @param state The state that uses the specified image. @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param manager The manager to create image request operation. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setBackgroundImageWithURL:(nullable NSURL *)imageURL forState:(UIControlState)state placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options manager:(nullable YYWebImageManager *)manager progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Cancel the current backgroundImage request for a specified state. @param state The state that uses the specified image. */ - (void)cancelBackgroundImageRequestForState:(UIControlState)state; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/UIButton+YYWebImage.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,777
```objective-c // // UIButton+YYWebImage.m // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "UIButton+YYWebImage.h" #import "YYWebImageOperation.h" #import "_YYWebImageSetter.h" #import "YYKitMacro.h" #import <objc/runtime.h> YYSYNTH_DUMMY_CLASS(UIButton_YYWebImage) static inline NSNumber *UIControlStateSingle(UIControlState state) { if (state & UIControlStateHighlighted) return @(UIControlStateHighlighted); if (state & UIControlStateDisabled) return @(UIControlStateDisabled); if (state & UIControlStateSelected) return @(UIControlStateSelected); return @(UIControlStateNormal); } static inline NSArray *UIControlStateMulti(UIControlState state) { NSMutableArray *array = [NSMutableArray new]; if (state & UIControlStateHighlighted) [array addObject:@(UIControlStateHighlighted)]; if (state & UIControlStateDisabled) [array addObject:@(UIControlStateDisabled)]; if (state & UIControlStateSelected) [array addObject:@(UIControlStateSelected)]; if ((state & 0xFF) == 0) [array addObject:@(UIControlStateNormal)]; return array; } static int _YYWebImageSetterKey; static int _YYWebImageBackgroundSetterKey; @interface _YYWebImageSetterDicForButton : NSObject - (_YYWebImageSetter *)setterForState:(NSNumber *)state; - (_YYWebImageSetter *)lazySetterForState:(NSNumber *)state; @end @implementation _YYWebImageSetterDicForButton { NSMutableDictionary *_dic; dispatch_semaphore_t _lock; } - (instancetype)init { self = [super init]; _lock = dispatch_semaphore_create(1); _dic = [NSMutableDictionary new]; return self; } - (_YYWebImageSetter *)setterForState:(NSNumber *)state { dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); _YYWebImageSetter *setter = _dic[state]; dispatch_semaphore_signal(_lock); return setter; } - (_YYWebImageSetter *)lazySetterForState:(NSNumber *)state { dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); _YYWebImageSetter *setter = _dic[state]; if (!setter) { setter = [_YYWebImageSetter new]; _dic[state] = setter; } dispatch_semaphore_signal(_lock); return setter; } @end @implementation UIButton (YYWebImage) #pragma mark - image - (void)_setImageWithURL:(NSURL *)imageURL forSingleState:(NSNumber *)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL]; manager = manager ? manager : [YYWebImageManager sharedManager]; _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageSetterKey); if (!dic) { dic = [_YYWebImageSetterDicForButton new]; objc_setAssociatedObject(self, &_YYWebImageSetterKey, dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } _YYWebImageSetter *setter = [dic lazySetterForState:state]; int32_t sentinel = [setter cancelWithNewURL:imageURL]; dispatch_async_on_main_queue(^{ if (!imageURL) { if (!(options & YYWebImageOptionIgnorePlaceHolder)) { [self setImage:placeholder forState:state.integerValue]; } return; } // get the image from memory as quickly as possible UIImage *imageFromMemory = nil; if (manager.cache && !(options & YYWebImageOptionUseNSURLCache) && !(options & YYWebImageOptionRefreshImageCache)) { imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory]; } if (imageFromMemory) { if (!(options & YYWebImageOptionAvoidSetImage)) { [self setImage:imageFromMemory forState:state.integerValue]; } if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil); return; } if (!(options & YYWebImageOptionIgnorePlaceHolder)) { [self setImage:placeholder forState:state.integerValue]; } __weak typeof(self) _self = self; dispatch_async([_YYWebImageSetter setterQueue], ^{ YYWebImageProgressBlock _progress = nil; if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) { dispatch_async(dispatch_get_main_queue(), ^{ progress(receivedSize, expectedSize); }); }; __block int32_t newSentinel = 0; __block __weak typeof(setter) weakSetter = nil; YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { __strong typeof(_self) self = _self; BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage); dispatch_async(dispatch_get_main_queue(), ^{ BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel; if (setImage && self && !sentinelChanged) { [self setImage:image forState:state.integerValue]; } if (completion) { if (sentinelChanged) { completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil); } else { completion(image, url, from, stage, error); } } }); }; newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion]; weakSetter = setter; }); }); } - (void)_cancelImageRequestForSingleState:(NSNumber *)state { _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageSetterKey); _YYWebImageSetter *setter = [dic setterForState:state]; if (setter) [setter cancel]; } - (NSURL *)imageURLForState:(UIControlState)state { _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageSetterKey); _YYWebImageSetter *setter = [dic setterForState:UIControlStateSingle(state)]; return setter.imageURL; } - (void)setImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder { [self setImageWithURL:imageURL forState:state placeholder:placeholder options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL forState:(UIControlState)state options:(YYWebImageOptions)options { [self setImageWithURL:imageURL forState:state placeholder:nil options:options manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL forState:state placeholder:placeholder options:options manager:nil progress:nil transform:nil completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL forState:state placeholder:placeholder options:options manager:nil progress:progress transform:transform completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { for (NSNumber *num in UIControlStateMulti(state)) { [self _setImageWithURL:imageURL forSingleState:num placeholder:placeholder options:options manager:manager progress:progress transform:transform completion:completion]; } } - (void)cancelImageRequestForState:(UIControlState)state { for (NSNumber *num in UIControlStateMulti(state)) { [self _cancelImageRequestForSingleState:num]; } } #pragma mark - background image - (void)_setBackgroundImageWithURL:(NSURL *)imageURL forSingleState:(NSNumber *)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL]; manager = manager ? manager : [YYWebImageManager sharedManager]; _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageBackgroundSetterKey); if (!dic) { dic = [_YYWebImageSetterDicForButton new]; objc_setAssociatedObject(self, &_YYWebImageBackgroundSetterKey, dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } _YYWebImageSetter *setter = [dic lazySetterForState:state]; int32_t sentinel = [setter cancelWithNewURL:imageURL]; dispatch_async_on_main_queue(^{ if (!imageURL) { if (!(options & YYWebImageOptionIgnorePlaceHolder)) { [self setBackgroundImage:placeholder forState:state.integerValue]; } return; } // get the image from memory as quickly as possible UIImage *imageFromMemory = nil; if (manager.cache && !(options & YYWebImageOptionUseNSURLCache) && !(options & YYWebImageOptionRefreshImageCache)) { imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory]; } if (imageFromMemory) { if (!(options & YYWebImageOptionAvoidSetImage)) { [self setBackgroundImage:imageFromMemory forState:state.integerValue]; } if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil); return; } if (!(options & YYWebImageOptionIgnorePlaceHolder)) { [self setBackgroundImage:placeholder forState:state.integerValue]; } __weak typeof(self) _self = self; dispatch_async([_YYWebImageSetter setterQueue], ^{ YYWebImageProgressBlock _progress = nil; if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) { dispatch_async(dispatch_get_main_queue(), ^{ progress(receivedSize, expectedSize); }); }; __block int32_t newSentinel = 0; __block __weak typeof(setter) weakSetter = nil; YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { __strong typeof(_self) self = _self; BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage); dispatch_async(dispatch_get_main_queue(), ^{ BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel; if (setImage && self && !sentinelChanged) { [self setBackgroundImage:image forState:state.integerValue]; } if (completion) { if (sentinelChanged) { completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil); } else { completion(image, url, from, stage, error); } } }); }; newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion]; weakSetter = setter; }); }); } - (void)_cancelBackgroundImageRequestForSingleState:(NSNumber *)state { _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageBackgroundSetterKey); _YYWebImageSetter *setter = [dic setterForState:state]; if (setter) [setter cancel]; } - (NSURL *)backgroundImageURLForState:(UIControlState)state { _YYWebImageSetterDicForButton *dic = objc_getAssociatedObject(self, &_YYWebImageBackgroundSetterKey); _YYWebImageSetter *setter = [dic setterForState:UIControlStateSingle(state)]; return setter.imageURL; } - (void)setBackgroundImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder { [self setBackgroundImageWithURL:imageURL forState:state placeholder:placeholder options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setBackgroundImageWithURL:(NSURL *)imageURL forState:(UIControlState)state options:(YYWebImageOptions)options { [self setBackgroundImageWithURL:imageURL forState:state placeholder:nil options:options manager:nil progress:nil transform:nil completion:nil]; } - (void)setBackgroundImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options completion:(YYWebImageCompletionBlock)completion { [self setBackgroundImageWithURL:imageURL forState:state placeholder:placeholder options:options manager:nil progress:nil transform:nil completion:completion]; } - (void)setBackgroundImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { [self setBackgroundImageWithURL:imageURL forState:state placeholder:placeholder options:options manager:nil progress:progress transform:transform completion:completion]; } - (void)setBackgroundImageWithURL:(NSURL *)imageURL forState:(UIControlState)state placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { for (NSNumber *num in UIControlStateMulti(state)) { [self _setBackgroundImageWithURL:imageURL forSingleState:num placeholder:placeholder options:options manager:manager progress:progress transform:transform completion:completion]; } } - (void)cancelBackgroundImageRequestForState:(UIControlState)state { for (NSNumber *num in UIControlStateMulti(state)) { [self _cancelBackgroundImageRequestForSingleState:num]; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/UIButton+YYWebImage.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
3,491
```objective-c // // MKAnnotationView+YYWebImage.m // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "MKAnnotationView+YYWebImage.h" #import "YYWebImageOperation.h" #import "_YYWebImageSetter.h" #import "YYKitMacro.h" #import <objc/runtime.h> YYSYNTH_DUMMY_CLASS(MKAnnotationView_YYWebImage) static int _YYWebImageSetterKey; @implementation MKAnnotationView (YYWebImage) - (NSURL *)imageURL { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); return setter.imageURL; } - (void)setImageURL:(NSURL *)imageURL { [self setImageWithURL:imageURL placeholder:nil options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder { [self setImageWithURL:imageURL placeholder:placeholder options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options { [self setImageWithURL:imageURL placeholder:nil options:options manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:nil transform:nil completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:progress transform:transform completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL]; manager = manager ? manager : [YYWebImageManager sharedManager]; _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); if (!setter) { setter = [_YYWebImageSetter new]; objc_setAssociatedObject(self, &_YYWebImageSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } int32_t sentinel = [setter cancelWithNewURL:imageURL]; dispatch_async_on_main_queue(^{ if ((options & YYWebImageOptionSetImageWithFadeAnimation) && !(options & YYWebImageOptionAvoidSetImage)) { if (!self.highlighted) { [self.layer removeAnimationForKey:_YYWebImageFadeAnimationKey]; } } if (!imageURL) { if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.image = placeholder; } return; } // get the image from memory as quickly as possible UIImage *imageFromMemory = nil; if (manager.cache && !(options & YYWebImageOptionUseNSURLCache) && !(options & YYWebImageOptionRefreshImageCache)) { imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory]; } if (imageFromMemory) { if (!(options & YYWebImageOptionAvoidSetImage)) { self.image = imageFromMemory; } if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil); return; } if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.image = placeholder; } __weak typeof(self) _self = self; dispatch_async([_YYWebImageSetter setterQueue], ^{ YYWebImageProgressBlock _progress = nil; if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) { dispatch_async(dispatch_get_main_queue(), ^{ progress(receivedSize, expectedSize); }); }; __block int32_t newSentinel = 0; __block __weak typeof(setter) weakSetter = nil; YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { __strong typeof(_self) self = _self; BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage); BOOL showFade = ((options & YYWebImageOptionSetImageWithFadeAnimation) && !self.highlighted); dispatch_async(dispatch_get_main_queue(), ^{ BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel; if (setImage && self && !sentinelChanged) { if (showFade) { CATransition *transition = [CATransition animation]; transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionFade; [self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey]; } self.image = image; } if (completion) { if (sentinelChanged) { completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil); } else { completion(image, url, from, stage, error); } } }); }; newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion]; weakSetter = setter; }); }); } - (void)cancelCurrentImageRequest { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); if (setter) [setter cancel]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/MKAnnotationView+YYWebImage.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,471
```objective-c // // UIImageView+YYWebImage.h // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYWebImageManager.h> #else #import "YYWebImageManager.h" #endif NS_ASSUME_NONNULL_BEGIN /** Web image methods for UIImageView. */ @interface UIImageView (YYWebImage) #pragma mark - image /** Current image URL. @discussion Set a new value to this property will cancel the previous request operation and create a new request operation to fetch image. Set nil to clear the image and image URL. */ @property (nullable, nonatomic, strong) NSURL *imageURL; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param options The options to use when request the image. */ - (void)setImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder he image to be set initially, until the image request finishes. @param options The options to use when request the image. @param manager The manager to create image request operation. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options manager:(nullable YYWebImageManager *)manager progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Cancel the current image request. */ - (void)cancelCurrentImageRequest; #pragma mark - highlight image /** Current highlighted image URL. @discussion Set a new value to this property will cancel the previous request operation and create a new request operation to fetch image. Set nil to clear the highlighted image and image URL. */ @property (nullable, nonatomic, strong) NSURL *highlightedImageURL; /** Set the view's `highlightedImage` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. */ - (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder; /** Set the view's `highlightedImage` with a specified URL. @param imageURL The image url (remote or local file path). @param options The options to use when request the image. */ - (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options; /** Set the view's `highlightedImage` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param completion The block invoked (on main thread) when image request completed. */ - (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `highlightedImage` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `highlightedImage` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder he image to be set initially, until the image request finishes. @param options The options to use when request the image. @param manager The manager to create image request operation. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setHighlightedImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options manager:(nullable YYWebImageManager *)manager progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Cancel the current highlighed image request. */ - (void)cancelCurrentHighlightedImageRequest; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/UIImageView+YYWebImage.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,550
```objective-c // // _YYWebImageSetter.h // YYKit <path_to_url // // Created by ibireme on 15/7/15. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYWebImageManager.h> #else #import "YYWebImageManager.h" #endif NS_ASSUME_NONNULL_BEGIN extern NSString *const _YYWebImageFadeAnimationKey; extern const NSTimeInterval _YYWebImageFadeTime; extern const NSTimeInterval _YYWebImageProgressiveFadeTime; /** Private class used by web image categories. Typically, you should not use this class directly. */ @interface _YYWebImageSetter : NSObject /// Current image url. @property (nullable, nonatomic, readonly) NSURL *imageURL; /// Current sentinel. @property (nonatomic, readonly) int32_t sentinel; /// Create new operation for web image and return a sentinel value. - (int32_t)setOperationWithSentinel:(int32_t)sentinel url:(nullable NSURL *)imageURL options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /// Cancel and return a sentinel value. The imageURL will be set to nil. - (int32_t)cancel; /// Cancel and return a sentinel value. The imageURL will be set to new value. - (int32_t)cancelWithNewURL:(nullable NSURL *)imageURL; /// A queue to set operation. + (dispatch_queue_t)setterQueue; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/_YYWebImageSetter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
382
```objective-c // // MKAnnotationView+YYWebImage.h // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYWebImageManager.h> #else #import "YYWebImageManager.h" #endif NS_ASSUME_NONNULL_BEGIN /** Web image methods for MKAnnotationView. */ @interface MKAnnotationView (YYWebImage) /** Current image URL. @discussion Set a new value to this property will cancel the previous request operation and create a new request operation to fetch image. Set nil to clear the image and image URL. */ @property (nullable, nonatomic, strong) NSURL *imageURL; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param options The options to use when request the image. */ - (void)setImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder The image to be set initially, until the image request finishes. @param options The options to use when request the image. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Set the view's `image` with a specified URL. @param imageURL The image url (remote or local file path). @param placeholder he image to be set initially, until the image request finishes. @param options The options to use when request the image. @param manager The manager to create image request operation. @param progress The block invoked (on main thread) during image request. @param transform The block invoked (on background thread) to do additional image process. @param completion The block invoked (on main thread) when image request completed. */ - (void)setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder options:(YYWebImageOptions)options manager:(nullable YYWebImageManager *)manager progress:(nullable YYWebImageProgressBlock)progress transform:(nullable YYWebImageTransformBlock)transform completion:(nullable YYWebImageCompletionBlock)completion; /** Cancel the current image request. */ - (void)cancelCurrentImageRequest; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/MKAnnotationView+YYWebImage.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
843
```objective-c // // UIImageView+YYWebImage.m // YYKit <path_to_url // // Created by ibireme on 15/2/23. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "UIImageView+YYWebImage.h" #import "YYWebImageOperation.h" #import "_YYWebImageSetter.h" #import "YYKitMacro.h" #import <objc/runtime.h> YYSYNTH_DUMMY_CLASS(UIImageView_YYWebImage) static int _YYWebImageSetterKey; static int _YYWebImageHighlightedSetterKey; @implementation UIImageView (YYWebImage) #pragma mark - image - (NSURL *)imageURL { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); return setter.imageURL; } /* "setImageWithURL" is conflict to AFNetworking and SDWebImage...WTF! So.. We use "setImageURL:" instead. */ - (void)setImageURL:(NSURL *)imageURL { [self setImageWithURL:imageURL placeholder:nil options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder { [self setImageWithURL:imageURL placeholder:placeholder options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options { [self setImageWithURL:imageURL placeholder:nil options:options manager:nil progress:nil transform:nil completion:nil]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:nil transform:nil completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { [self setImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:progress transform:transform completion:completion]; } - (void)setImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL]; manager = manager ? manager : [YYWebImageManager sharedManager]; _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); if (!setter) { setter = [_YYWebImageSetter new]; objc_setAssociatedObject(self, &_YYWebImageSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } int32_t sentinel = [setter cancelWithNewURL:imageURL]; dispatch_async_on_main_queue(^{ if ((options & YYWebImageOptionSetImageWithFadeAnimation) && !(options & YYWebImageOptionAvoidSetImage)) { if (!self.highlighted) { [self.layer removeAnimationForKey:_YYWebImageFadeAnimationKey]; } } if (!imageURL) { if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.image = placeholder; } return; } // get the image from memory as quickly as possible UIImage *imageFromMemory = nil; if (manager.cache && !(options & YYWebImageOptionUseNSURLCache) && !(options & YYWebImageOptionRefreshImageCache)) { imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory]; } if (imageFromMemory) { if (!(options & YYWebImageOptionAvoidSetImage)) { self.image = imageFromMemory; } if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil); return; } if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.image = placeholder; } __weak typeof(self) _self = self; dispatch_async([_YYWebImageSetter setterQueue], ^{ YYWebImageProgressBlock _progress = nil; if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) { dispatch_async(dispatch_get_main_queue(), ^{ progress(receivedSize, expectedSize); }); }; __block int32_t newSentinel = 0; __block __weak typeof(setter) weakSetter = nil; YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { __strong typeof(_self) self = _self; BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage); dispatch_async(dispatch_get_main_queue(), ^{ BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel; if (setImage && self && !sentinelChanged) { BOOL showFade = ((options & YYWebImageOptionSetImageWithFadeAnimation) && !self.highlighted); if (showFade) { CATransition *transition = [CATransition animation]; transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionFade; [self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey]; } self.image = image; } if (completion) { if (sentinelChanged) { completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil); } else { completion(image, url, from, stage, error); } } }); }; newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion]; weakSetter = setter; }); }); } - (void)cancelCurrentImageRequest { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey); if (setter) [setter cancel]; } #pragma mark - highlighted image - (NSURL *)highlightedImageURL { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageHighlightedSetterKey); return setter.imageURL; } - (void)setHighlightedImageURL:(NSURL *)imageURL { [self setHighlightedImageWithURL:imageURL placeholder:nil options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setHighlightedImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder { [self setHighlightedImageWithURL:imageURL placeholder:placeholder options:kNilOptions manager:nil progress:nil transform:nil completion:nil]; } - (void)setHighlightedImageWithURL:(NSURL *)imageURL options:(YYWebImageOptions)options { [self setHighlightedImageWithURL:imageURL placeholder:nil options:options manager:nil progress:nil transform:nil completion:nil]; } - (void)setHighlightedImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options completion:(YYWebImageCompletionBlock)completion { [self setHighlightedImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:nil transform:nil completion:completion]; } - (void)setHighlightedImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { [self setHighlightedImageWithURL:imageURL placeholder:placeholder options:options manager:nil progress:progress transform:nil completion:completion]; } - (void)setHighlightedImageWithURL:(NSURL *)imageURL placeholder:(UIImage *)placeholder options:(YYWebImageOptions)options manager:(YYWebImageManager *)manager progress:(YYWebImageProgressBlock)progress transform:(YYWebImageTransformBlock)transform completion:(YYWebImageCompletionBlock)completion { if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL]; manager = manager ? manager : [YYWebImageManager sharedManager]; _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageHighlightedSetterKey); if (!setter) { setter = [_YYWebImageSetter new]; objc_setAssociatedObject(self, &_YYWebImageHighlightedSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } int32_t sentinel = [setter cancelWithNewURL:imageURL]; dispatch_async_on_main_queue(^{ if ((options & YYWebImageOptionSetImageWithFadeAnimation) && !(options & YYWebImageOptionAvoidSetImage)) { if (self.highlighted) { [self.layer removeAnimationForKey:_YYWebImageFadeAnimationKey]; } } if (!imageURL) { if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.highlightedImage = placeholder; } return; } // get the image from memory as quickly as possible UIImage *imageFromMemory = nil; if (manager.cache && !(options & YYWebImageOptionUseNSURLCache) && !(options & YYWebImageOptionRefreshImageCache)) { imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory]; } if (imageFromMemory) { if (!(options & YYWebImageOptionAvoidSetImage)) { self.highlightedImage = imageFromMemory; } if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil); return; } if (!(options & YYWebImageOptionIgnorePlaceHolder)) { self.highlightedImage = placeholder; } __weak typeof(self) _self = self; dispatch_async([_YYWebImageSetter setterQueue], ^{ YYWebImageProgressBlock _progress = nil; if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) { dispatch_async(dispatch_get_main_queue(), ^{ progress(receivedSize, expectedSize); }); }; __block int32_t newSentinel = 0; __block __weak typeof(setter) weakSetter = nil; YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { __strong typeof(_self) self = _self; BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage); BOOL showFade = ((options & YYWebImageOptionSetImageWithFadeAnimation) && self.highlighted); dispatch_async(dispatch_get_main_queue(), ^{ BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel; if (setImage && self && !sentinelChanged) { if (showFade) { CATransition *transition = [CATransition animation]; transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionFade; [self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey]; } self.highlightedImage = image; } if (completion) { if (sentinelChanged) { completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil); } else { completion(image, url, from, stage, error); } } }); }; newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion]; weakSetter = setter; }); }); } - (void)cancelCurrentHighlightedImageRequest { _YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageHighlightedSetterKey); if (setter) [setter cancel]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Image/Categories/UIImageView+YYWebImage.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,864
```objective-c // // YYClassInfo.h // YYKit <path_to_url // // Created by ibireme on 15/5/9. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> #import <objc/runtime.h> NS_ASSUME_NONNULL_BEGIN /** Type encoding's type. */ typedef NS_OPTIONS(NSUInteger, YYEncodingType) { YYEncodingTypeMask = 0xFF, ///< mask of type value YYEncodingTypeUnknown = 0, ///< unknown YYEncodingTypeVoid = 1, ///< void YYEncodingTypeBool = 2, ///< bool YYEncodingTypeInt8 = 3, ///< char / BOOL YYEncodingTypeUInt8 = 4, ///< unsigned char YYEncodingTypeInt16 = 5, ///< short YYEncodingTypeUInt16 = 6, ///< unsigned short YYEncodingTypeInt32 = 7, ///< int YYEncodingTypeUInt32 = 8, ///< unsigned int YYEncodingTypeInt64 = 9, ///< long long YYEncodingTypeUInt64 = 10, ///< unsigned long long YYEncodingTypeFloat = 11, ///< float YYEncodingTypeDouble = 12, ///< double YYEncodingTypeLongDouble = 13, ///< long double YYEncodingTypeObject = 14, ///< id YYEncodingTypeClass = 15, ///< Class YYEncodingTypeSEL = 16, ///< SEL YYEncodingTypeBlock = 17, ///< block YYEncodingTypePointer = 18, ///< void* YYEncodingTypeStruct = 19, ///< struct YYEncodingTypeUnion = 20, ///< union YYEncodingTypeCString = 21, ///< char* YYEncodingTypeCArray = 22, ///< char[10] (for example) YYEncodingTypeQualifierMask = 0xFF00, ///< mask of qualifier YYEncodingTypeQualifierConst = 1 << 8, ///< const YYEncodingTypeQualifierIn = 1 << 9, ///< in YYEncodingTypeQualifierInout = 1 << 10, ///< inout YYEncodingTypeQualifierOut = 1 << 11, ///< out YYEncodingTypeQualifierBycopy = 1 << 12, ///< bycopy YYEncodingTypeQualifierByref = 1 << 13, ///< byref YYEncodingTypeQualifierOneway = 1 << 14, ///< oneway YYEncodingTypePropertyMask = 0xFF0000, ///< mask of property YYEncodingTypePropertyReadonly = 1 << 16, ///< readonly YYEncodingTypePropertyCopy = 1 << 17, ///< copy YYEncodingTypePropertyRetain = 1 << 18, ///< retain YYEncodingTypePropertyNonatomic = 1 << 19, ///< nonatomic YYEncodingTypePropertyWeak = 1 << 20, ///< weak YYEncodingTypePropertyCustomGetter = 1 << 21, ///< getter= YYEncodingTypePropertyCustomSetter = 1 << 22, ///< setter= YYEncodingTypePropertyDynamic = 1 << 23, ///< @dynamic }; /** Get the type from a Type-Encoding string. @discussion See also: path_to_url path_to_url @param typeEncoding A Type-Encoding string. @return The encoding type. */ YYEncodingType YYEncodingGetType(const char *typeEncoding); /** Instance variable information. */ @interface YYClassIvarInfo : NSObject @property (nonatomic, assign, readonly) Ivar ivar; ///< ivar opaque struct @property (nonatomic, strong, readonly) NSString *name; ///< Ivar's name @property (nonatomic, assign, readonly) ptrdiff_t offset; ///< Ivar's offset @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< Ivar's type encoding @property (nonatomic, assign, readonly) YYEncodingType type; ///< Ivar's type /** Creates and returns an ivar info object. @param ivar ivar opaque struct @return A new object, or nil if an error occurs. */ - (instancetype)initWithIvar:(Ivar)ivar; @end /** Method information. */ @interface YYClassMethodInfo : NSObject @property (nonatomic, assign, readonly) Method method; ///< method opaque struct @property (nonatomic, strong, readonly) NSString *name; ///< method name @property (nonatomic, assign, readonly) SEL sel; ///< method's selector @property (nonatomic, assign, readonly) IMP imp; ///< method's implementation @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< method's parameter and return types @property (nonatomic, strong, readonly) NSString *returnTypeEncoding; ///< return value's type @property (nullable, nonatomic, strong, readonly) NSArray<NSString *> *argumentTypeEncodings; ///< array of arguments' type /** Creates and returns a method info object. @param method method opaque struct @return A new object, or nil if an error occurs. */ - (instancetype)initWithMethod:(Method)method; @end /** Property information. */ @interface YYClassPropertyInfo : NSObject @property (nonatomic, assign, readonly) objc_property_t property; ///< property's opaque struct @property (nonatomic, strong, readonly) NSString *name; ///< property's name @property (nonatomic, assign, readonly) YYEncodingType type; ///< property's type @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< property's encoding value @property (nonatomic, strong, readonly) NSString *ivarName; ///< property's ivar name @property (nullable, nonatomic, assign, readonly) Class cls; ///< may be nil @property (nullable, nonatomic, strong, readonly) NSArray<NSString *> *protocols; ///< may nil @property (nonatomic, assign, readonly) SEL getter; ///< getter (nonnull) @property (nonatomic, assign, readonly) SEL setter; ///< setter (nonnull) /** Creates and returns a property info object. @param property property opaque struct @return A new object, or nil if an error occurs. */ - (instancetype)initWithProperty:(objc_property_t)property; @end /** Class information for a class. */ @interface YYClassInfo : NSObject @property (nonatomic, assign, readonly) Class cls; ///< class object @property (nullable, nonatomic, assign, readonly) Class superCls; ///< super class object @property (nullable, nonatomic, assign, readonly) Class metaCls; ///< class's meta class object @property (nonatomic, readonly) BOOL isMeta; ///< whether this class is meta class @property (nonatomic, strong, readonly) NSString *name; ///< class name @property (nullable, nonatomic, strong, readonly) YYClassInfo *superClassInfo; ///< super class's class info @property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassIvarInfo *> *ivarInfos; ///< ivars @property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassMethodInfo *> *methodInfos; ///< methods @property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassPropertyInfo *> *propertyInfos; ///< properties /** If the class is changed (for example: you add a method to this class with 'class_addMethod()'), you should call this method to refresh the class info cache. After called this method, `needUpdate` will returns `YES`, and you should call 'classInfoWithClass' or 'classInfoWithClassName' to get the updated class info. */ - (void)setNeedUpdate; /** If this method returns `YES`, you should stop using this instance and call `classInfoWithClass` or `classInfoWithClassName` to get the updated class info. @return Whether this class info need update. */ - (BOOL)needUpdate; /** Get the class info of a specified Class. @discussion This method will cache the class info and super-class info at the first access to the Class. This method is thread-safe. @param cls A class. @return A class info, or nil if an error occurs. */ + (nullable instancetype)classInfoWithClass:(Class)cls; /** Get the class info of a specified Class. @discussion This method will cache the class info and super-class info at the first access to the Class. This method is thread-safe. @param className A class name. @return A class info, or nil if an error occurs. */ + (nullable instancetype)classInfoWithClassName:(NSString *)className; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Model/YYClassInfo.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,893
```objective-c // // YYClassInfo.m // YYKit <path_to_url // // Created by ibireme on 15/5/9. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYClassInfo.h" #import <objc/runtime.h> YYEncodingType YYEncodingGetType(const char *typeEncoding) { char *type = (char *)typeEncoding; if (!type) return YYEncodingTypeUnknown; size_t len = strlen(type); if (len == 0) return YYEncodingTypeUnknown; YYEncodingType qualifier = 0; bool prefix = true; while (prefix) { switch (*type) { case 'r': { qualifier |= YYEncodingTypeQualifierConst; type++; } break; case 'n': { qualifier |= YYEncodingTypeQualifierIn; type++; } break; case 'N': { qualifier |= YYEncodingTypeQualifierInout; type++; } break; case 'o': { qualifier |= YYEncodingTypeQualifierOut; type++; } break; case 'O': { qualifier |= YYEncodingTypeQualifierBycopy; type++; } break; case 'R': { qualifier |= YYEncodingTypeQualifierByref; type++; } break; case 'V': { qualifier |= YYEncodingTypeQualifierOneway; type++; } break; default: { prefix = false; } break; } } len = strlen(type); if (len == 0) return YYEncodingTypeUnknown | qualifier; switch (*type) { case 'v': return YYEncodingTypeVoid | qualifier; case 'B': return YYEncodingTypeBool | qualifier; case 'c': return YYEncodingTypeInt8 | qualifier; case 'C': return YYEncodingTypeUInt8 | qualifier; case 's': return YYEncodingTypeInt16 | qualifier; case 'S': return YYEncodingTypeUInt16 | qualifier; case 'i': return YYEncodingTypeInt32 | qualifier; case 'I': return YYEncodingTypeUInt32 | qualifier; case 'l': return YYEncodingTypeInt32 | qualifier; case 'L': return YYEncodingTypeUInt32 | qualifier; case 'q': return YYEncodingTypeInt64 | qualifier; case 'Q': return YYEncodingTypeUInt64 | qualifier; case 'f': return YYEncodingTypeFloat | qualifier; case 'd': return YYEncodingTypeDouble | qualifier; case 'D': return YYEncodingTypeLongDouble | qualifier; case '#': return YYEncodingTypeClass | qualifier; case ':': return YYEncodingTypeSEL | qualifier; case '*': return YYEncodingTypeCString | qualifier; case '^': return YYEncodingTypePointer | qualifier; case '[': return YYEncodingTypeCArray | qualifier; case '(': return YYEncodingTypeUnion | qualifier; case '{': return YYEncodingTypeStruct | qualifier; case '@': { if (len == 2 && *(type + 1) == '?') return YYEncodingTypeBlock | qualifier; else return YYEncodingTypeObject | qualifier; } default: return YYEncodingTypeUnknown | qualifier; } } @implementation YYClassIvarInfo - (instancetype)initWithIvar:(Ivar)ivar { if (!ivar) return nil; self = [super init]; _ivar = ivar; const char *name = ivar_getName(ivar); if (name) { _name = [NSString stringWithUTF8String:name]; } _offset = ivar_getOffset(ivar); const char *typeEncoding = ivar_getTypeEncoding(ivar); if (typeEncoding) { _typeEncoding = [NSString stringWithUTF8String:typeEncoding]; _type = YYEncodingGetType(typeEncoding); } return self; } @end @implementation YYClassMethodInfo - (instancetype)initWithMethod:(Method)method { if (!method) return nil; self = [super init]; _method = method; _sel = method_getName(method); _imp = method_getImplementation(method); const char *name = sel_getName(_sel); if (name) { _name = [NSString stringWithUTF8String:name]; } const char *typeEncoding = method_getTypeEncoding(method); if (typeEncoding) { _typeEncoding = [NSString stringWithUTF8String:typeEncoding]; } char *returnType = method_copyReturnType(method); if (returnType) { _returnTypeEncoding = [NSString stringWithUTF8String:returnType]; free(returnType); } unsigned int argumentCount = method_getNumberOfArguments(method); if (argumentCount > 0) { NSMutableArray *argumentTypes = [NSMutableArray new]; for (unsigned int i = 0; i < argumentCount; i++) { char *argumentType = method_copyArgumentType(method, i); NSString *type = argumentType ? [NSString stringWithUTF8String:argumentType] : nil; [argumentTypes addObject:type ? type : @""]; if (argumentType) free(argumentType); } _argumentTypeEncodings = argumentTypes; } return self; } @end @implementation YYClassPropertyInfo - (instancetype)initWithProperty:(objc_property_t)property { if (!property) return nil; self = [super init]; _property = property; const char *name = property_getName(property); if (name) { _name = [NSString stringWithUTF8String:name]; } YYEncodingType type = 0; unsigned int attrCount; objc_property_attribute_t *attrs = property_copyAttributeList(property, &attrCount); for (unsigned int i = 0; i < attrCount; i++) { switch (attrs[i].name[0]) { case 'T': { // Type encoding if (attrs[i].value) { _typeEncoding = [NSString stringWithUTF8String:attrs[i].value]; type = YYEncodingGetType(attrs[i].value); if ((type & YYEncodingTypeMask) == YYEncodingTypeObject && _typeEncoding.length) { NSScanner *scanner = [NSScanner scannerWithString:_typeEncoding]; if (![scanner scanString:@"@\"" intoString:NULL]) continue; NSString *clsName = nil; if ([scanner scanUpToCharactersFromSet: [NSCharacterSet characterSetWithCharactersInString:@"\"<"] intoString:&clsName]) { if (clsName.length) _cls = objc_getClass(clsName.UTF8String); } NSMutableArray *protocols = nil; while ([scanner scanString:@"<" intoString:NULL]) { NSString* protocol = nil; if ([scanner scanUpToString:@">" intoString: &protocol]) { if (protocol.length) { if (!protocols) protocols = [NSMutableArray new]; [protocols addObject:protocol]; } } [scanner scanString:@">" intoString:NULL]; } _protocols = protocols; } } } break; case 'V': { // Instance variable if (attrs[i].value) { _ivarName = [NSString stringWithUTF8String:attrs[i].value]; } } break; case 'R': { type |= YYEncodingTypePropertyReadonly; } break; case 'C': { type |= YYEncodingTypePropertyCopy; } break; case '&': { type |= YYEncodingTypePropertyRetain; } break; case 'N': { type |= YYEncodingTypePropertyNonatomic; } break; case 'D': { type |= YYEncodingTypePropertyDynamic; } break; case 'W': { type |= YYEncodingTypePropertyWeak; } break; case 'G': { type |= YYEncodingTypePropertyCustomGetter; if (attrs[i].value) { _getter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]); } } break; case 'S': { type |= YYEncodingTypePropertyCustomSetter; if (attrs[i].value) { _setter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]); } } // break; commented for code coverage in next line default: break; } } if (attrs) { free(attrs); attrs = NULL; } _type = type; if (_name.length) { if (!_getter) { _getter = NSSelectorFromString(_name); } if (!_setter) { _setter = NSSelectorFromString([NSString stringWithFormat:@"set%@%@:", [_name substringToIndex:1].uppercaseString, [_name substringFromIndex:1]]); } } return self; } @end @implementation YYClassInfo { BOOL _needUpdate; } - (instancetype)initWithClass:(Class)cls { if (!cls) return nil; self = [super init]; _cls = cls; _superCls = class_getSuperclass(cls); _isMeta = class_isMetaClass(cls); if (!_isMeta) { _metaCls = objc_getMetaClass(class_getName(cls)); } _name = NSStringFromClass(cls); [self _update]; _superClassInfo = [self.class classInfoWithClass:_superCls]; return self; } - (void)_update { _ivarInfos = nil; _methodInfos = nil; _propertyInfos = nil; Class cls = self.cls; unsigned int methodCount = 0; Method *methods = class_copyMethodList(cls, &methodCount); if (methods) { NSMutableDictionary *methodInfos = [NSMutableDictionary new]; _methodInfos = methodInfos; for (unsigned int i = 0; i < methodCount; i++) { YYClassMethodInfo *info = [[YYClassMethodInfo alloc] initWithMethod:methods[i]]; if (info.name) methodInfos[info.name] = info; } free(methods); } unsigned int propertyCount = 0; objc_property_t *properties = class_copyPropertyList(cls, &propertyCount); if (properties) { NSMutableDictionary *propertyInfos = [NSMutableDictionary new]; _propertyInfos = propertyInfos; for (unsigned int i = 0; i < propertyCount; i++) { YYClassPropertyInfo *info = [[YYClassPropertyInfo alloc] initWithProperty:properties[i]]; if (info.name) propertyInfos[info.name] = info; } free(properties); } unsigned int ivarCount = 0; Ivar *ivars = class_copyIvarList(cls, &ivarCount); if (ivars) { NSMutableDictionary *ivarInfos = [NSMutableDictionary new]; _ivarInfos = ivarInfos; for (unsigned int i = 0; i < ivarCount; i++) { YYClassIvarInfo *info = [[YYClassIvarInfo alloc] initWithIvar:ivars[i]]; if (info.name) ivarInfos[info.name] = info; } free(ivars); } if (!_ivarInfos) _ivarInfos = @{}; if (!_methodInfos) _methodInfos = @{}; if (!_propertyInfos) _propertyInfos = @{}; _needUpdate = NO; } - (void)setNeedUpdate { _needUpdate = YES; } - (BOOL)needUpdate { return _needUpdate; } + (instancetype)classInfoWithClass:(Class)cls { if (!cls) return nil; static CFMutableDictionaryRef classCache; static CFMutableDictionaryRef metaCache; static dispatch_once_t onceToken; static dispatch_semaphore_t lock; dispatch_once(&onceToken, ^{ classCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); metaCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); lock = dispatch_semaphore_create(1); }); dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); YYClassInfo *info = CFDictionaryGetValue(class_isMetaClass(cls) ? metaCache : classCache, (__bridge const void *)(cls)); if (info && info->_needUpdate) { [info _update]; } dispatch_semaphore_signal(lock); if (!info) { info = [[YYClassInfo alloc] initWithClass:cls]; if (info) { dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); CFDictionarySetValue(info.isMeta ? metaCache : classCache, (__bridge const void *)(cls), (__bridge const void *)(info)); dispatch_semaphore_signal(lock); } } return info; } + (instancetype)classInfoWithClassName:(NSString *)className { Class cls = NSClassFromString(className); return [self classInfoWithClass:cls]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Model/YYClassInfo.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,829
```objective-c // // NSObject+YYModel.h // YYKit <path_to_url // // Created by ibireme on 15/5/10. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** Provide some data-model method: * Convert json to any object, or convert any object to json. * Set object properties with a key-value dictionary (like KVC). * Implementations of `NSCoding`, `NSCopying`, `-hash` and `-isEqual:`. See `YYModel` protocol for custom methods. Sample Code: ********************** json convertor ********************* @interface YYAuthor : NSObject @property (nonatomic, strong) NSString *name; @property (nonatomic, assign) NSDate *birthday; @end @implementation YYAuthor @end @interface YYBook : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) NSUInteger pages; @property (nonatomic, strong) YYAuthor *author; @end @implementation YYBook @end int main() { // create model from json YYBook *book = [YYBook modelWithJSON:@"{\"name\": \"Harry Potter\", \"pages\": 256, \"author\": {\"name\": \"J.K.Rowling\", \"birthday\": \"1965-07-31\" }}"]; // convert model to json NSString *json = [book modelToJSONString]; // {"author":{"name":"J.K.Rowling","birthday":"1965-07-31T00:00:00+0000"},"name":"Harry Potter","pages":256} } ********************** Coding/Copying/hash/equal ********************* @interface YYShadow :NSObject <NSCoding, NSCopying> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) CGSize size; @end @implementation YYShadow - (void)encodeWithCoder:(NSCoder *)aCoder { [self modelEncodeWithCoder:aCoder]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self modelInitWithCoder:aDecoder]; } - (id)copyWithZone:(NSZone *)zone { return [self modelCopy]; } - (NSUInteger)hash { return [self modelHash]; } - (BOOL)isEqual:(id)object { return [self modelIsEqual:object]; } @end */ @interface NSObject (YYModel) /** Creates and returns a new instance of the receiver from a json. This method is thread-safe. @param json A json object in `NSDictionary`, `NSString` or `NSData`. @return A new instance created from the json, or nil if an error occurs. */ + (nullable instancetype)modelWithJSON:(id)json; /** Creates and returns a new instance of the receiver from a key-value dictionary. This method is thread-safe. @param dictionary A key-value dictionary mapped to the instance's properties. Any invalid key-value pair in dictionary will be ignored. @return A new instance created from the dictionary, or nil if an error occurs. @discussion The key in `dictionary` will mapped to the reciever's property name, and the value will set to the property. If the value's type does not match the property, this method will try to convert the value based on these rules: `NSString` or `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger... `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd". `NSString` -> NSURL. `NSValue` -> struct or union, such as CGRect, CGSize, ... `NSString` -> SEL, Class. */ + (nullable instancetype)modelWithDictionary:(NSDictionary *)dictionary; /** Set the receiver's properties with a json object. @discussion Any invalid data in json will be ignored. @param json A json object of `NSDictionary`, `NSString` or `NSData`, mapped to the receiver's properties. @return Whether succeed. */ - (BOOL)modelSetWithJSON:(id)json; /** Set the receiver's properties with a key-value dictionary. @param dic A key-value dictionary mapped to the receiver's properties. Any invalid key-value pair in dictionary will be ignored. @discussion The key in `dictionary` will mapped to the reciever's property name, and the value will set to the property. If the value's type doesn't match the property, this method will try to convert the value based on these rules: `NSString`, `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger... `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd". `NSString` -> NSURL. `NSValue` -> struct or union, such as CGRect, CGSize, ... `NSString` -> SEL, Class. @return Whether succeed. */ - (BOOL)modelSetWithDictionary:(NSDictionary *)dic; /** Generate a json object from the receiver's properties. @return A json object in `NSDictionary` or `NSArray`, or nil if an error occurs. See [NSJSONSerialization isValidJSONObject] for more information. @discussion Any of the invalid property is ignored. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it just convert the inner object to json object. */ - (nullable id)modelToJSONObject; /** Generate a json string's data from the receiver's properties. @return A json string's data, or nil if an error occurs. @discussion Any of the invalid property is ignored. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the inner object to json string. */ - (nullable NSData *)modelToJSONData; /** Generate a json string from the receiver's properties. @return A json string, or nil if an error occurs. @discussion Any of the invalid property is ignored. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the inner object to json string. */ - (nullable NSString *)modelToJSONString; /** Copy a instance with the receiver's properties. @return A copied instance, or nil if an error occurs. */ - (nullable id)modelCopy; /** Encode the receiver's properties to a coder. @param aCoder An archiver object. */ - (void)modelEncodeWithCoder:(NSCoder *)aCoder; /** Decode the receiver's properties from a decoder. @param aDecoder An archiver object. @return self */ - (id)modelInitWithCoder:(NSCoder *)aDecoder; /** Get a hash code with the receiver's properties. @return Hash code. */ - (NSUInteger)modelHash; /** Compares the receiver with another object for equality, based on properties. @param model Another object. @return `YES` if the reciever is equal to the object, otherwise `NO`. */ - (BOOL)modelIsEqual:(id)model; - (BOOL)modelIsEqualToModel:(id)model; /** Description method for debugging purposes based on properties. @return A string that describes the contents of the receiver. */ - (NSString *)modelDescription; @end /** Provide some data-model method for NSArray. */ @interface NSArray (YYModel) /** Creates and returns an array from a json-array. This method is thread-safe. @param cls The instance's class in array. @param json A json array of `NSArray`, `NSString` or `NSData`. Example: [{"name","Mary"},{name:"Joe"}] @return A array, or nil if an error occurs. */ + (nullable NSArray *)modelArrayWithClass:(Class)cls json:(id)json; @end /** Provide some data-model method for NSDictionary. */ @interface NSDictionary (YYModel) /** Creates and returns a dictionary from a json. This method is thread-safe. @param cls The value instance's class in dictionary. @param json A json dictionary of `NSDictionary`, `NSString` or `NSData`. Example: {"user1":{"name","Mary"}, "user2": {name:"Joe"}} @return A dictionary, or nil if an error occurs. */ + (nullable NSDictionary *)modelDictionaryWithClass:(Class)cls json:(id)json; @end /** If the default model transform does not fit to your model class, implement one or more method in this protocol to change the default key-value transform process. There's no need to add '<YYModel>' to your class header. */ @protocol YYModel <NSObject> @optional /** Custom property mapper. @discussion If the key in JSON/Dictionary does not match to the model's property name, implements this method and returns the additional mapper. Example: json: { "n":"Harry Pottery", "p": 256, "ext" : { "desc" : "A book written by J.K.Rowling." }, "ID" : 100010 } model: @interface YYBook : NSObject @property NSString *name; @property NSInteger page; @property NSString *desc; @property NSString *bookID; @end @implementation YYBook + (NSDictionary *)modelCustomPropertyMapper { return @{@"name" : @"n", @"page" : @"p", @"desc" : @"ext.desc", @"bookID": @[@"id", @"ID", @"book_id"]}; } @end @return A custom mapper for properties. */ + (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper; /** The generic class mapper for container properties. @discussion If the property is a container object, such as NSArray/NSSet/NSDictionary, implements this method and returns a property->class mapper, tells which kind of object will be add to the array/set/dictionary. Example: @class YYShadow, YYBorder, YYAttachment; @interface YYAttributes @property NSString *name; @property NSArray *shadows; @property NSSet *borders; @property NSDictionary *attachments; @end @implementation YYAttributes + (NSDictionary *)modelContainerPropertyGenericClass { return @{@"shadows" : [YYShadow class], @"borders" : YYBorder.class, @"attachments" : @"YYAttachment" }; } @end @return A class mapper. */ + (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass; /** If you need to create instances of different classes during json->object transform, use the method to choose custom class based on dictionary data. @discussion If the model implements this method, it will be called to determine resulting class during `+modelWithJSON:`, `+modelWithDictionary:`, conveting object of properties of parent objects (both singular and containers via `+modelContainerPropertyGenericClass`). Example: @class YYCircle, YYRectangle, YYLine; @implementation YYShape + (Class)modelCustomClassForDictionary:(NSDictionary*)dictionary { if (dictionary[@"radius"] != nil) { return [YYCircle class]; } else if (dictionary[@"width"] != nil) { return [YYRectangle class]; } else if (dictionary[@"y2"] != nil) { return [YYLine class]; } else { return [self class]; } } @end @param dictionary The json/kv dictionary. @return Class to create from this dictionary, `nil` to use current class. */ + (nullable Class)modelCustomClassForDictionary:(NSDictionary *)dictionary; /** All the properties in blacklist will be ignored in model transform process. Returns nil to ignore this feature. @return An array of property's name. */ + (nullable NSArray<NSString *> *)modelPropertyBlacklist; /** If a property is not in the whitelist, it will be ignored in model transform process. Returns nil to ignore this feature. @return An array of property's name. */ + (nullable NSArray<NSString *> *)modelPropertyWhitelist; /** This method's behavior is similar to `- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;`, but be called before the model transform. @discussion If the model implements this method, it will be called before `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`. If this method returns nil, the transform process will ignore this model. @param dic The json/kv dictionary. @return Returns the modified dictionary, or nil to ignore this model. */ - (NSDictionary *)modelCustomWillTransformFromDictionary:(NSDictionary *)dic; /** If the default json-to-model transform does not fit to your model object, implement this method to do additional process. You can also use this method to validate the model's properties. @discussion If the model implements this method, it will be called at the end of `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`. If this method returns NO, the transform process will ignore this model. @param dic The json/kv dictionary. @return Returns YES if the model is valid, or NO to ignore this model. */ - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic; /** If the default model-to-json transform does not fit to your model class, implement this method to do additional process. You can also use this method to validate the json dictionary. @discussion If the model implements this method, it will be called at the end of `-modelToJSONObject` and `-modelToJSONString`. If this method returns NO, the transform process will ignore this json dictionary. @param dic The json dictionary. @return Returns YES if the model is valid, or NO to ignore this model. */ - (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Model/NSObject+YYModel.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
3,081
```objective-c // // YYFPSLabel.h // YYKitExample // // Created by ibireme on 15/9/3. // #import <UIKit/UIKit.h> /** Show Screen FPS... The maximum fps in OSX/iOS Simulator is 60.00. The maximum fps on iPhone is 59.97. The maxmium fps on iPad is 60.0. */ @interface YYFPSLabel : UILabel @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/YYFPSLabel.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
91
```objective-c // // YYFPSLabel.m // YYKitExample // // Created by ibireme on 15/9/3. // #import "YYFPSLabel.h" #import "YYKit.h" #import "YYWeakProxy.h" #define kSize CGSizeMake(55, 20) @implementation YYFPSLabel { CADisplayLink *_link; NSUInteger _count; NSTimeInterval _lastTime; UIFont *_font; UIFont *_subFont; NSTimeInterval _llll; } - (instancetype)initWithFrame:(CGRect)frame { if (frame.size.width == 0 && frame.size.height == 0) { frame.size = kSize; } self = [super initWithFrame:frame]; self.layer.cornerRadius = 5; self.clipsToBounds = YES; self.textAlignment = NSTextAlignmentCenter; self.userInteractionEnabled = NO; self.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700]; _font = [UIFont fontWithName:@"Menlo" size:14]; if (_font) { _subFont = [UIFont fontWithName:@"Menlo" size:4]; } else { _font = [UIFont fontWithName:@"Courier" size:14]; _subFont = [UIFont fontWithName:@"Courier" size:4]; } _link = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(tick:)]; [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; return self; } - (void)dealloc { [_link invalidate]; } - (CGSize)sizeThatFits:(CGSize)size { return kSize; } - (void)tick:(CADisplayLink *)link { if (_lastTime == 0) { _lastTime = link.timestamp; return; } _count++; NSTimeInterval delta = link.timestamp - _lastTime; if (delta < 1) return; _lastTime = link.timestamp; float fps = _count / delta; _count = 0; CGFloat progress = fps / 60.0; UIColor *color = [UIColor colorWithHue:0.27 * (progress - 0.2) saturation:1 brightness:0.9 alpha:1]; NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d FPS",(int)round(fps)]]; [text setColor:color range:NSMakeRange(0, text.length - 3)]; [text setColor:[UIColor whiteColor] range:NSMakeRange(text.length - 3, 3)]; text.font = _font; [text setFont:_subFont range:NSMakeRange(text.length - 4, 1)]; self.attributedText = text; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/YYFPSLabel.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
579
```objective-c // // YYTextView.h // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextParser.h> #import <YYKit/YYTextLayout.h> #import <YYKit/YYTextAttribute.h> #else #import "YYTextParser.h" #import "YYTextLayout.h" #import "YYTextAttribute.h" #endif @class YYTextView; NS_ASSUME_NONNULL_BEGIN /** The YYTextViewDelegate protocol defines a set of optional methods you can use to receive editing-related messages for YYTextView objects. @discussion The API and behavior is similar to UITextViewDelegate, see UITextViewDelegate's documentation for more information. */ @protocol YYTextViewDelegate <NSObject, UIScrollViewDelegate> @optional - (BOOL)textViewShouldBeginEditing:(YYTextView *)textView; - (BOOL)textViewShouldEndEditing:(YYTextView *)textView; - (void)textViewDidBeginEditing:(YYTextView *)textView; - (void)textViewDidEndEditing:(YYTextView *)textView; - (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; - (void)textViewDidChange:(YYTextView *)textView; - (void)textViewDidChangeSelection:(YYTextView *)textView; - (BOOL)textView:(YYTextView *)textView shouldTapHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange; - (void)textView:(YYTextView *)textView didTapHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange rect:(CGRect)rect; - (BOOL)textView:(YYTextView *)textView shouldLongPressHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange; - (void)textView:(YYTextView *)textView didLongPressHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange rect:(CGRect)rect; @end #if !TARGET_INTERFACE_BUILDER /** The YYTextView class implements the behavior for a scrollable, multiline text region. @discussion The API and behavior is similar to UITextView, but provides more features: * It extends the CoreText attributes to support more text effects. * It allows to add UIImage, UIView and CALayer as text attachments. * It allows to add 'highlight' link to some range of text to allow user interact with. * It allows to add exclusion paths to control text container's shape. * It supports vertical form layout to display and edit CJK text. * It allows user to copy/paste image and attributed text from/to text view. * It allows to set an attributed text as placeholder. See NSAttributedString+YYText.h for more convenience methods to set the attributes. See YYTextAttribute.h and YYTextLayout.h for more information. */ @interface YYTextView : UIScrollView <UITextInput> #pragma mark - Accessing the Delegate ///============================================================================= /// @name Accessing the Delegate ///============================================================================= @property (nullable, nonatomic, weak) id<YYTextViewDelegate> delegate; #pragma mark - Configuring the Text Attributes ///============================================================================= /// @name Configuring the Text Attributes ///============================================================================= /** The text displayed by the text view. Set a new value to this property also replaces the text in `attributedText`. Get the value returns the plain text in `attributedText`. */ @property (null_resettable, nonatomic, copy) NSString *text; /** The font of the text. Default is 12-point system font. Set a new value to this property also causes the new font to be applied to the entire `attributedText`. Get the value returns the font at the head of `attributedText`. */ @property (nullable, nonatomic, strong) UIFont *font; /** The color of the text. Default is black. Set a new value to this property also causes the new color to be applied to the entire `attributedText`. Get the value returns the color at the head of `attributedText`. */ @property (nullable, nonatomic, strong) UIColor *textColor; /** The technique to use for aligning the text. Default is NSTextAlignmentNatural. Set a new value to this property also causes the new alignment to be applied to the entire `attributedText`. Get the value returns the alignment at the head of `attributedText`. */ @property (nonatomic) NSTextAlignment textAlignment; /** The text vertical aligmnent in container. Default is YYTextVerticalAlignmentTop. */ @property (nonatomic) YYTextVerticalAlignment textVerticalAlignment; /** The types of data converted to clickable URLs in the text view. Default is UIDataDetectorTypeNone. The tap or long press action should be handled by delegate. */ @property (nonatomic) UIDataDetectorTypes dataDetectorTypes; /** The attributes to apply to links at normal state. Default is light blue color. When a range of text is detected by the `dataDetectorTypes`, this value would be used to modify the original attributes in the range. */ @property (nullable, nonatomic, copy) NSDictionary<NSString *, id> *linkTextAttributes; /** The attributes to apply to links at highlight state. Default is a gray border. When a range of text is detected by the `dataDetectorTypes` and the range was touched by user, this value would be used to modify the original attributes in the range. */ @property (nullable, nonatomic, copy) NSDictionary<NSString *, id> *highlightTextAttributes; /** The attributes to apply to new text being entered by the user. When the text view's selection changes, this value is reset automatically. */ @property (nullable, nonatomic, copy) NSDictionary<NSString *, id> *typingAttributes; /** The styled text displayed by the text view. Set a new value to this property also replaces the value of the `text`, `font`, `textColor`, `textAlignment` and other properties in text view. @discussion It only support the attributes declared in CoreText and YYTextAttribute. See `NSAttributedString+YYText` for more convenience methods to set the attributes. */ @property (nullable, nonatomic, copy) NSAttributedString *attributedText; /** When `text` or `attributedText` is changed, the parser will be called to modify the text. It can be used to add code highlighting or emoticon replacement to text view. The default value is nil. See `YYTextParser` protocol for more information. */ @property (nullable, nonatomic, strong) id<YYTextParser> textParser; /** The current text layout in text view (readonly). It can be used to query the text layout information. */ @property (nullable, nonatomic, strong, readonly) YYTextLayout *textLayout; #pragma mark - Configuring the Placeholder ///============================================================================= /// @name Configuring the Placeholder ///============================================================================= /** The placeholder text displayed by the text view (when the text view is empty). Set a new value to this property also replaces the text in `placeholderAttributedText`. Get the value returns the plain text in `placeholderAttributedText`. */ @property (nullable, nonatomic, copy) NSString *placeholderText; /** The font of the placeholder text. Default is same as `font` property. Set a new value to this property also causes the new font to be applied to the entire `placeholderAttributedText`. Get the value returns the font at the head of `placeholderAttributedText`. */ @property (nullable, nonatomic, strong) UIFont *placeholderFont; /** The color of the placeholder text. Default is gray. Set a new value to this property also causes the new color to be applied to the entire `placeholderAttributedText`. Get the value returns the color at the head of `placeholderAttributedText`. */ @property (nullable, nonatomic, strong) UIColor *placeholderTextColor; /** The styled placeholder text displayed by the text view (when the text view is empty). Set a new value to this property also replaces the value of the `placeholderText`, `placeholderFont`, `placeholderTextColor`. @discussion It only support the attributes declared in CoreText and YYTextAttribute. See `NSAttributedString+YYText` for more convenience methods to set the attributes. */ @property (nullable, nonatomic, copy) NSAttributedString *placeholderAttributedText; #pragma mark - Configuring the Text Container ///============================================================================= /// @name Configuring the Text Container ///============================================================================= /** The inset of the text container's layout area within the text view's content area. */ @property (nonatomic) UIEdgeInsets textContainerInset; /** An array of UIBezierPath objects representing the exclusion paths inside the receiver's bounding rectangle. Default value is nil. */ @property (nullable, nonatomic, copy) NSArray<UIBezierPath *> *exclusionPaths; /** Whether the receiver's layout orientation is vertical form. Default is NO. It may used to edit/display CJK text. */ @property (nonatomic, getter=isVerticalForm) BOOL verticalForm; /** The text line position modifier used to modify the lines' position in layout. See `YYTextLinePositionModifier` protocol for more information. */ @property (nullable, nonatomic, copy) id<YYTextLinePositionModifier> linePositionModifier; /** The debug option to display CoreText layout result. The default value is [YYTextDebugOption sharedDebugOption]. */ @property (nullable, nonatomic, copy) YYTextDebugOption *debugOption; #pragma mark - Working with the Selection and Menu ///============================================================================= /// @name Working with the Selection and Menu ///============================================================================= /** Scrolls the receiver until the text in the specified range is visible. */ - (void)scrollRangeToVisible:(NSRange)range; /** The current selection range of the receiver. */ @property (nonatomic) NSRange selectedRange; /** A Boolean value indicating whether inserting text replaces the previous contents. The default value is NO. */ @property (nonatomic) BOOL clearsOnInsertion; /** A Boolean value indicating whether the receiver is selectable. Default is YES. When the value of this property is NO, user cannot select content or edit text. */ @property (nonatomic, getter=isSelectable) BOOL selectable; /** A Boolean value indicating whether the receiver is highlightable. Default is YES. When the value of this property is NO, user cannot interact with the highlight range of text. */ @property (nonatomic, getter=isHighlightable) BOOL highlightable; /** A Boolean value indicating whether the receiver is editable. Default is YES. When the value of this property is NO, user cannot edit text. */ @property (nonatomic, getter=isEditable) BOOL editable; /** A Boolean value indicating whether the receiver can paste image from pasteboard. Default is NO. When the value of this property is YES, user can paste image from pasteboard via "paste" menu. */ @property (nonatomic) BOOL allowsPasteImage; /** A Boolean value indicating whether the receiver can paste attributed text from pasteboard. Default is NO. When the value of this property is YES, user can paste attributed text from pasteboard via "paste" menu. */ @property (nonatomic) BOOL allowsPasteAttributedString; /** A Boolean value indicating whether the receiver can copy attributed text to pasteboard. Default is YES. When the value of this property is YES, user can copy attributed text (with attachment image) from text view to pasteboard via "copy" menu. */ @property (nonatomic) BOOL allowsCopyAttributedString; #pragma mark - Manage the undo and redo ///============================================================================= /// @name Manage the undo and redo ///============================================================================= /** A Boolean value indicating whether the receiver can undo and redo typing with shake gesture. The default value is YES. */ @property (nonatomic) BOOL allowsUndoAndRedo; /** The maximum undo/redo level. The default value is 20. */ @property (nonatomic) NSUInteger maximumUndoLevel; #pragma mark - Replacing the System Input Views ///============================================================================= /// @name Replacing the System Input Views ///============================================================================= /** The custom input view to display when the text view becomes the first responder. It can be used to replace system keyboard. @discussion If set the value while first responder, it will not take effect until 'reloadInputViews' is called. */ @property (nullable, nonatomic, readwrite, strong) __kindof UIView *inputView; /** The custom accessory view to display when the text view becomes the first responder. It can be used to add a toolbar at the top of keyboard. @discussion If set the value while first responder, it will not take effect until 'reloadInputViews' is called. */ @property (nullable, nonatomic, readwrite, strong) __kindof UIView *inputAccessoryView; /** If you use an custom accessory view without "inputAccessoryView" property, you may set the accessory view's height. It may used by auto scroll calculation. */ @property (nonatomic) CGFloat extraAccessoryViewHeight; @end #else // TARGET_INTERFACE_BUILDER IB_DESIGNABLE @interface YYTextView : UIScrollView <UITextInput> @property (null_resettable, nonatomic, copy) IBInspectable NSString *text; @property (nullable, nonatomic, strong) IBInspectable UIColor *textColor; @property (nullable, nonatomic, strong) IBInspectable NSString *fontName_; @property (nonatomic) IBInspectable CGFloat fontSize_; @property (nonatomic) IBInspectable BOOL fontIsBold_; @property (nonatomic) IBInspectable NSTextAlignment textAlignment; @property (nonatomic) IBInspectable YYTextVerticalAlignment textVerticalAlignment; @property (nullable, nonatomic, copy) IBInspectable NSString *placeholderText; @property (nullable, nonatomic, strong) IBInspectable UIColor *placeholderTextColor; @property (nullable, nonatomic, strong) IBInspectable NSString *placeholderFontName_; @property (nonatomic) IBInspectable CGFloat placeholderFontSize_; @property (nonatomic) IBInspectable BOOL placeholderFontIsBold_; @property (nonatomic, getter=isVerticalForm) IBInspectable BOOL verticalForm; @property (nonatomic) IBInspectable BOOL clearsOnInsertion; @property (nonatomic, getter=isSelectable) IBInspectable BOOL selectable; @property (nonatomic, getter=isHighlightable) IBInspectable BOOL highlightable; @property (nonatomic, getter=isEditable) IBInspectable BOOL editable; @property (nonatomic) IBInspectable BOOL allowsPasteImage; @property (nonatomic) IBInspectable BOOL allowsPasteAttributedString; @property (nonatomic) IBInspectable BOOL allowsCopyAttributedString; @property (nonatomic) IBInspectable BOOL allowsUndoAndRedo; @property (nonatomic) IBInspectable NSUInteger maximumUndoLevel; @property (nonatomic) IBInspectable CGFloat insetTop_; @property (nonatomic) IBInspectable CGFloat insetBottom_; @property (nonatomic) IBInspectable CGFloat insetLeft_; @property (nonatomic) IBInspectable CGFloat insetRight_; @property (nonatomic) IBInspectable BOOL debugEnabled_; @property (nullable, nonatomic, weak) id<YYTextViewDelegate> delegate; @property (nullable, nonatomic, strong) UIFont *font; @property (nonatomic) UIDataDetectorTypes dataDetectorTypes; @property (nullable, nonatomic, copy) NSDictionary *linkTextAttributes; @property (nullable, nonatomic, copy) NSDictionary *highlightTextAttributes; @property (nullable, nonatomic, copy) NSDictionary *typingAttributes; @property (nullable, nonatomic, copy) NSAttributedString *attributedText; @property (nullable, nonatomic, strong) id<YYTextParser> textParser; @property (nullable, nonatomic, strong, readonly) YYTextLayout *textLayout; @property (nullable, nonatomic, strong) UIFont *placeholderFont; @property (nullable, nonatomic, copy) NSAttributedString *placeholderAttributedText; @property (nonatomic) UIEdgeInsets textContainerInset; @property (nullable, nonatomic, copy) NSArray *exclusionPaths; @property (nullable, nonatomic, copy) id<YYTextLinePositionModifier> linePositionModifier; @property (nullable, nonatomic, copy) YYTextDebugOption *debugOption; - (void)scrollRangeToVisible:(NSRange)range; @property (nonatomic) NSRange selectedRange; @property (nullable, nonatomic, readwrite, strong) __kindof UIView *inputView; @property (nullable, nonatomic, readwrite, strong) __kindof UIView *inputAccessoryView; @property (nonatomic) CGFloat extraAccessoryViewHeight; @end #endif // !TARGET_INTERFACE_BUILDER // Notifications, see UITextView's documentation for more information. UIKIT_EXTERN NSString *const YYTextViewTextDidBeginEditingNotification; UIKIT_EXTERN NSString *const YYTextViewTextDidChangeNotification; UIKIT_EXTERN NSString *const YYTextViewTextDidEndEditingNotification; NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/YYTextView.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
3,372
```objective-c // // NSObject+YYModel.m // YYKit <path_to_url // // Created by ibireme on 15/5/10. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "NSObject+YYModel.h" #import "YYClassInfo.h" #import <objc/message.h> #define force_inline __inline__ __attribute__((always_inline)) /// Foundation Class Type typedef NS_ENUM (NSUInteger, YYEncodingNSType) { YYEncodingTypeNSUnknown = 0, YYEncodingTypeNSString, YYEncodingTypeNSMutableString, YYEncodingTypeNSValue, YYEncodingTypeNSNumber, YYEncodingTypeNSDecimalNumber, YYEncodingTypeNSData, YYEncodingTypeNSMutableData, YYEncodingTypeNSDate, YYEncodingTypeNSURL, YYEncodingTypeNSArray, YYEncodingTypeNSMutableArray, YYEncodingTypeNSDictionary, YYEncodingTypeNSMutableDictionary, YYEncodingTypeNSSet, YYEncodingTypeNSMutableSet, }; /// Get the Foundation class type from property info. static force_inline YYEncodingNSType YYClassGetNSType(Class cls) { if (!cls) return YYEncodingTypeNSUnknown; if ([cls isSubclassOfClass:[NSMutableString class]]) return YYEncodingTypeNSMutableString; if ([cls isSubclassOfClass:[NSString class]]) return YYEncodingTypeNSString; if ([cls isSubclassOfClass:[NSDecimalNumber class]]) return YYEncodingTypeNSDecimalNumber; if ([cls isSubclassOfClass:[NSNumber class]]) return YYEncodingTypeNSNumber; if ([cls isSubclassOfClass:[NSValue class]]) return YYEncodingTypeNSValue; if ([cls isSubclassOfClass:[NSMutableData class]]) return YYEncodingTypeNSMutableData; if ([cls isSubclassOfClass:[NSData class]]) return YYEncodingTypeNSData; if ([cls isSubclassOfClass:[NSDate class]]) return YYEncodingTypeNSDate; if ([cls isSubclassOfClass:[NSURL class]]) return YYEncodingTypeNSURL; if ([cls isSubclassOfClass:[NSMutableArray class]]) return YYEncodingTypeNSMutableArray; if ([cls isSubclassOfClass:[NSArray class]]) return YYEncodingTypeNSArray; if ([cls isSubclassOfClass:[NSMutableDictionary class]]) return YYEncodingTypeNSMutableDictionary; if ([cls isSubclassOfClass:[NSDictionary class]]) return YYEncodingTypeNSDictionary; if ([cls isSubclassOfClass:[NSMutableSet class]]) return YYEncodingTypeNSMutableSet; if ([cls isSubclassOfClass:[NSSet class]]) return YYEncodingTypeNSSet; return YYEncodingTypeNSUnknown; } /// Whether the type is c number. static force_inline BOOL YYEncodingTypeIsCNumber(YYEncodingType type) { switch (type & YYEncodingTypeMask) { case YYEncodingTypeBool: case YYEncodingTypeInt8: case YYEncodingTypeUInt8: case YYEncodingTypeInt16: case YYEncodingTypeUInt16: case YYEncodingTypeInt32: case YYEncodingTypeUInt32: case YYEncodingTypeInt64: case YYEncodingTypeUInt64: case YYEncodingTypeFloat: case YYEncodingTypeDouble: case YYEncodingTypeLongDouble: return YES; default: return NO; } } /// Parse a number value from 'id'. static force_inline NSNumber *YYNSNumberCreateFromID(__unsafe_unretained id value) { static NSCharacterSet *dot; static NSDictionary *dic; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ dot = [NSCharacterSet characterSetWithRange:NSMakeRange('.', 1)]; dic = @{@"TRUE" : @(YES), @"True" : @(YES), @"true" : @(YES), @"FALSE" : @(NO), @"False" : @(NO), @"false" : @(NO), @"YES" : @(YES), @"Yes" : @(YES), @"yes" : @(YES), @"NO" : @(NO), @"No" : @(NO), @"no" : @(NO), @"NIL" : (id)kCFNull, @"Nil" : (id)kCFNull, @"nil" : (id)kCFNull, @"NULL" : (id)kCFNull, @"Null" : (id)kCFNull, @"null" : (id)kCFNull, @"(NULL)" : (id)kCFNull, @"(Null)" : (id)kCFNull, @"(null)" : (id)kCFNull, @"<NULL>" : (id)kCFNull, @"<Null>" : (id)kCFNull, @"<null>" : (id)kCFNull}; }); if (!value || value == (id)kCFNull) return nil; if ([value isKindOfClass:[NSNumber class]]) return value; if ([value isKindOfClass:[NSString class]]) { NSNumber *num = dic[value]; if (num) { if (num == (id)kCFNull) return nil; return num; } if ([(NSString *)value rangeOfCharacterFromSet:dot].location != NSNotFound) { const char *cstring = ((NSString *)value).UTF8String; if (!cstring) return nil; double num = atof(cstring); if (isnan(num) || isinf(num)) return nil; return @(num); } else { const char *cstring = ((NSString *)value).UTF8String; if (!cstring) return nil; return @(atoll(cstring)); } } return nil; } /// Parse string to date. static force_inline NSDate *YYNSDateFromString(__unsafe_unretained NSString *string) { typedef NSDate* (^YYNSDateParseBlock)(NSString *string); #define kParserNum 34 static YYNSDateParseBlock blocks[kParserNum + 1] = {0}; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ { /* 2014-01-20 // Google */ NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter.dateFormat = @"yyyy-MM-dd"; blocks[10] = ^(NSString *string) { return [formatter dateFromString:string]; }; } { /* 2014-01-20 12:24:48 2014-01-20T12:24:48 // Google 2014-01-20 12:24:48.000 2014-01-20T12:24:48.000 */ NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init]; formatter1.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter1.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter1.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss"; NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init]; formatter2.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter2.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter2.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init]; formatter3.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter3.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter3.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS"; NSDateFormatter *formatter4 = [[NSDateFormatter alloc] init]; formatter4.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter4.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter4.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS"; blocks[19] = ^(NSString *string) { if ([string characterAtIndex:10] == 'T') { return [formatter1 dateFromString:string]; } else { return [formatter2 dateFromString:string]; } }; blocks[23] = ^(NSString *string) { if ([string characterAtIndex:10] == 'T') { return [formatter3 dateFromString:string]; } else { return [formatter4 dateFromString:string]; } }; } { /* 2014-01-20T12:24:48Z // Github, Apple 2014-01-20T12:24:48+0800 // Facebook 2014-01-20T12:24:48+12:00 // Google 2014-01-20T12:24:48.000Z 2014-01-20T12:24:48.000+0800 2014-01-20T12:24:48.000+12:00 */ NSDateFormatter *formatter = [NSDateFormatter new]; formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ"; NSDateFormatter *formatter2 = [NSDateFormatter new]; formatter2.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter2.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; blocks[20] = ^(NSString *string) { return [formatter dateFromString:string]; }; blocks[24] = ^(NSString *string) { return [formatter dateFromString:string]?: [formatter2 dateFromString:string]; }; blocks[25] = ^(NSString *string) { return [formatter dateFromString:string]; }; blocks[28] = ^(NSString *string) { return [formatter2 dateFromString:string]; }; blocks[29] = ^(NSString *string) { return [formatter2 dateFromString:string]; }; } { /* Fri Sep 04 00:12:21 +0800 2015 // Weibo, Twitter Fri Sep 04 00:12:21.000 +0800 2015 */ NSDateFormatter *formatter = [NSDateFormatter new]; formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy"; NSDateFormatter *formatter2 = [NSDateFormatter new]; formatter2.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter2.dateFormat = @"EEE MMM dd HH:mm:ss.SSS Z yyyy"; blocks[30] = ^(NSString *string) { return [formatter dateFromString:string]; }; blocks[34] = ^(NSString *string) { return [formatter2 dateFromString:string]; }; } }); if (!string) return nil; if (string.length > kParserNum) return nil; YYNSDateParseBlock parser = blocks[string.length]; if (!parser) return nil; return parser(string); #undef kParserNum } /// Get the 'NSBlock' class. static force_inline Class YYNSBlockClass() { static Class cls; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ void (^block)(void) = ^{}; cls = ((NSObject *)block).class; while (class_getSuperclass(cls) != [NSObject class]) { cls = class_getSuperclass(cls); } }); return cls; // current is "NSBlock" } /** Get the ISO date formatter. ISO8601 format example: 2010-07-09T16:13:30+12:00 2011-01-11T11:11:11+0000 2011-01-26T19:06:43Z length: 20/24/25 */ static force_inline NSDateFormatter *YYISODateFormatter() { static NSDateFormatter *formatter = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ formatter = [[NSDateFormatter alloc] init]; formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ"; }); return formatter; } /// Get the value with key paths from dictionary /// The dic should be NSDictionary, and the keyPath should not be nil. static force_inline id YYValueForKeyPath(__unsafe_unretained NSDictionary *dic, __unsafe_unretained NSArray *keyPaths) { id value = nil; for (NSUInteger i = 0, max = keyPaths.count; i < max; i++) { value = dic[keyPaths[i]]; if (i + 1 < max) { if ([value isKindOfClass:[NSDictionary class]]) { dic = value; } else { return nil; } } } return value; } /// Get the value with multi key (or key path) from dictionary /// The dic should be NSDictionary static force_inline id YYValueForMultiKeys(__unsafe_unretained NSDictionary *dic, __unsafe_unretained NSArray *multiKeys) { id value = nil; for (NSString *key in multiKeys) { if ([key isKindOfClass:[NSString class]]) { value = dic[key]; if (value) break; } else { value = YYValueForKeyPath(dic, (NSArray *)key); if (value) break; } } return value; } /// A property info in object model. @interface _YYModelPropertyMeta : NSObject { @package NSString *_name; ///< property's name YYEncodingType _type; ///< property's type YYEncodingNSType _nsType; ///< property's Foundation type BOOL _isCNumber; ///< is c number type Class _cls; ///< property's class, or nil Class _genericCls; ///< container's generic class, or nil if threr's no generic class SEL _getter; ///< getter, or nil if the instances cannot respond SEL _setter; ///< setter, or nil if the instances cannot respond BOOL _isKVCCompatible; ///< YES if it can access with key-value coding BOOL _isStructAvailableForKeyedArchiver; ///< YES if the struct can encoded with keyed archiver/unarchiver BOOL _hasCustomClassFromDictionary; ///< class/generic class implements +modelCustomClassForDictionary: /* property->key: _mappedToKey:key _mappedToKeyPath:nil _mappedToKeyArray:nil property->keyPath: _mappedToKey:keyPath _mappedToKeyPath:keyPath(array) _mappedToKeyArray:nil property->keys: _mappedToKey:keys[0] _mappedToKeyPath:nil/keyPath _mappedToKeyArray:keys(array) */ NSString *_mappedToKey; ///< the key mapped to NSArray *_mappedToKeyPath; ///< the key path mapped to (nil if the name is not key path) NSArray *_mappedToKeyArray; ///< the key(NSString) or keyPath(NSArray) array (nil if not mapped to multiple keys) YYClassPropertyInfo *_info; ///< property's info _YYModelPropertyMeta *_next; ///< next meta if there are multiple properties mapped to the same key. } @end @implementation _YYModelPropertyMeta + (instancetype)metaWithClassInfo:(YYClassInfo *)classInfo propertyInfo:(YYClassPropertyInfo *)propertyInfo generic:(Class)generic { // support pseudo generic class with protocol name if (!generic && propertyInfo.protocols) { for (NSString *protocol in propertyInfo.protocols) { Class cls = objc_getClass(protocol.UTF8String); if (cls) { generic = cls; break; } } } _YYModelPropertyMeta *meta = [self new]; meta->_name = propertyInfo.name; meta->_type = propertyInfo.type; meta->_info = propertyInfo; meta->_genericCls = generic; if ((meta->_type & YYEncodingTypeMask) == YYEncodingTypeObject) { meta->_nsType = YYClassGetNSType(propertyInfo.cls); } else { meta->_isCNumber = YYEncodingTypeIsCNumber(meta->_type); } if ((meta->_type & YYEncodingTypeMask) == YYEncodingTypeStruct) { /* It seems that NSKeyedUnarchiver cannot decode NSValue except these structs: */ static NSSet *types = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSMutableSet *set = [NSMutableSet new]; // 32 bit [set addObject:@"{CGSize=ff}"]; [set addObject:@"{CGPoint=ff}"]; [set addObject:@"{CGRect={CGPoint=ff}{CGSize=ff}}"]; [set addObject:@"{CGAffineTransform=ffffff}"]; [set addObject:@"{UIEdgeInsets=ffff}"]; [set addObject:@"{UIOffset=ff}"]; // 64 bit [set addObject:@"{CGSize=dd}"]; [set addObject:@"{CGPoint=dd}"]; [set addObject:@"{CGRect={CGPoint=dd}{CGSize=dd}}"]; [set addObject:@"{CGAffineTransform=dddddd}"]; [set addObject:@"{UIEdgeInsets=dddd}"]; [set addObject:@"{UIOffset=dd}"]; types = set; }); if ([types containsObject:propertyInfo.typeEncoding]) { meta->_isStructAvailableForKeyedArchiver = YES; } } meta->_cls = propertyInfo.cls; if (generic) { meta->_hasCustomClassFromDictionary = [generic respondsToSelector:@selector(modelCustomClassForDictionary:)]; } else if (meta->_cls && meta->_nsType == YYEncodingTypeNSUnknown) { meta->_hasCustomClassFromDictionary = [meta->_cls respondsToSelector:@selector(modelCustomClassForDictionary:)]; } if (propertyInfo.getter) { if ([classInfo.cls instancesRespondToSelector:propertyInfo.getter]) { meta->_getter = propertyInfo.getter; } } if (propertyInfo.setter) { if ([classInfo.cls instancesRespondToSelector:propertyInfo.setter]) { meta->_setter = propertyInfo.setter; } } if (meta->_getter && meta->_setter) { /* KVC invalid type: long double pointer (such as SEL/CoreFoundation object) */ switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: case YYEncodingTypeInt8: case YYEncodingTypeUInt8: case YYEncodingTypeInt16: case YYEncodingTypeUInt16: case YYEncodingTypeInt32: case YYEncodingTypeUInt32: case YYEncodingTypeInt64: case YYEncodingTypeUInt64: case YYEncodingTypeFloat: case YYEncodingTypeDouble: case YYEncodingTypeObject: case YYEncodingTypeClass: case YYEncodingTypeBlock: case YYEncodingTypeStruct: case YYEncodingTypeUnion: { meta->_isKVCCompatible = YES; } break; default: break; } } return meta; } @end /// A class info in object model. @interface _YYModelMeta : NSObject { @package YYClassInfo *_classInfo; /// Key:mapped key and key path, Value:_YYModelPropertyMeta. NSDictionary *_mapper; /// Array<_YYModelPropertyMeta>, all property meta of this model. NSArray *_allPropertyMetas; /// Array<_YYModelPropertyMeta>, property meta which is mapped to a key path. NSArray *_keyPathPropertyMetas; /// Array<_YYModelPropertyMeta>, property meta which is mapped to multi keys. NSArray *_multiKeysPropertyMetas; /// The number of mapped key (and key path), same to _mapper.count. NSUInteger _keyMappedCount; /// Model class type. YYEncodingNSType _nsType; BOOL _hasCustomWillTransformFromDictionary; BOOL _hasCustomTransformFromDictionary; BOOL _hasCustomTransformToDictionary; BOOL _hasCustomClassFromDictionary; } @end @implementation _YYModelMeta - (instancetype)initWithClass:(Class)cls { YYClassInfo *classInfo = [YYClassInfo classInfoWithClass:cls]; if (!classInfo) return nil; self = [super init]; // Get black list NSSet *blacklist = nil; if ([cls respondsToSelector:@selector(modelPropertyBlacklist)]) { NSArray *properties = [(id<YYModel>)cls modelPropertyBlacklist]; if (properties) { blacklist = [NSSet setWithArray:properties]; } } // Get white list NSSet *whitelist = nil; if ([cls respondsToSelector:@selector(modelPropertyWhitelist)]) { NSArray *properties = [(id<YYModel>)cls modelPropertyWhitelist]; if (properties) { whitelist = [NSSet setWithArray:properties]; } } // Get container property's generic class NSDictionary *genericMapper = nil; if ([cls respondsToSelector:@selector(modelContainerPropertyGenericClass)]) { genericMapper = [(id<YYModel>)cls modelContainerPropertyGenericClass]; if (genericMapper) { NSMutableDictionary *tmp = [NSMutableDictionary new]; [genericMapper enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (![key isKindOfClass:[NSString class]]) return; Class meta = object_getClass(obj); if (!meta) return; if (class_isMetaClass(meta)) { tmp[key] = obj; } else if ([obj isKindOfClass:[NSString class]]) { Class cls = NSClassFromString(obj); if (cls) { tmp[key] = cls; } } }]; genericMapper = tmp; } } // Create all property metas. NSMutableDictionary *allPropertyMetas = [NSMutableDictionary new]; YYClassInfo *curClassInfo = classInfo; while (curClassInfo && curClassInfo.superCls != nil) { // recursive parse super class, but ignore root class (NSObject/NSProxy) for (YYClassPropertyInfo *propertyInfo in curClassInfo.propertyInfos.allValues) { if (!propertyInfo.name) continue; if (blacklist && [blacklist containsObject:propertyInfo.name]) continue; if (whitelist && ![whitelist containsObject:propertyInfo.name]) continue; _YYModelPropertyMeta *meta = [_YYModelPropertyMeta metaWithClassInfo:classInfo propertyInfo:propertyInfo generic:genericMapper[propertyInfo.name]]; if (!meta || !meta->_name) continue; if (!meta->_getter || !meta->_setter) continue; if (allPropertyMetas[meta->_name]) continue; allPropertyMetas[meta->_name] = meta; } curClassInfo = curClassInfo.superClassInfo; } if (allPropertyMetas.count) _allPropertyMetas = allPropertyMetas.allValues.copy; // create mapper NSMutableDictionary *mapper = [NSMutableDictionary new]; NSMutableArray *keyPathPropertyMetas = [NSMutableArray new]; NSMutableArray *multiKeysPropertyMetas = [NSMutableArray new]; if ([cls respondsToSelector:@selector(modelCustomPropertyMapper)]) { NSDictionary *customMapper = [(id <YYModel>)cls modelCustomPropertyMapper]; [customMapper enumerateKeysAndObjectsUsingBlock:^(NSString *propertyName, NSString *mappedToKey, BOOL *stop) { _YYModelPropertyMeta *propertyMeta = allPropertyMetas[propertyName]; if (!propertyMeta) return; [allPropertyMetas removeObjectForKey:propertyName]; if ([mappedToKey isKindOfClass:[NSString class]]) { if (mappedToKey.length == 0) return; propertyMeta->_mappedToKey = mappedToKey; NSArray *keyPath = [mappedToKey componentsSeparatedByString:@"."]; for (NSString *onePath in keyPath) { if (onePath.length == 0) { NSMutableArray *tmp = keyPath.mutableCopy; [tmp removeObject:@""]; keyPath = tmp; break; } } if (keyPath.count > 1) { propertyMeta->_mappedToKeyPath = keyPath; [keyPathPropertyMetas addObject:propertyMeta]; } propertyMeta->_next = mapper[mappedToKey] ?: nil; mapper[mappedToKey] = propertyMeta; } else if ([mappedToKey isKindOfClass:[NSArray class]]) { NSMutableArray *mappedToKeyArray = [NSMutableArray new]; for (NSString *oneKey in ((NSArray *)mappedToKey)) { if (![oneKey isKindOfClass:[NSString class]]) continue; if (oneKey.length == 0) continue; NSArray *keyPath = [oneKey componentsSeparatedByString:@"."]; if (keyPath.count > 1) { [mappedToKeyArray addObject:keyPath]; } else { [mappedToKeyArray addObject:oneKey]; } if (!propertyMeta->_mappedToKey) { propertyMeta->_mappedToKey = oneKey; propertyMeta->_mappedToKeyPath = keyPath.count > 1 ? keyPath : nil; } } if (!propertyMeta->_mappedToKey) return; propertyMeta->_mappedToKeyArray = mappedToKeyArray; [multiKeysPropertyMetas addObject:propertyMeta]; propertyMeta->_next = mapper[mappedToKey] ?: nil; mapper[mappedToKey] = propertyMeta; } }]; } [allPropertyMetas enumerateKeysAndObjectsUsingBlock:^(NSString *name, _YYModelPropertyMeta *propertyMeta, BOOL *stop) { propertyMeta->_mappedToKey = name; propertyMeta->_next = mapper[name] ?: nil; mapper[name] = propertyMeta; }]; if (mapper.count) _mapper = mapper; if (keyPathPropertyMetas) _keyPathPropertyMetas = keyPathPropertyMetas; if (multiKeysPropertyMetas) _multiKeysPropertyMetas = multiKeysPropertyMetas; _classInfo = classInfo; _keyMappedCount = _allPropertyMetas.count; _nsType = YYClassGetNSType(cls); _hasCustomWillTransformFromDictionary = ([cls instancesRespondToSelector:@selector(modelCustomWillTransformFromDictionary:)]); _hasCustomTransformFromDictionary = ([cls instancesRespondToSelector:@selector(modelCustomTransformFromDictionary:)]); _hasCustomTransformToDictionary = ([cls instancesRespondToSelector:@selector(modelCustomTransformToDictionary:)]); _hasCustomClassFromDictionary = ([cls respondsToSelector:@selector(modelCustomClassForDictionary:)]); return self; } /// Returns the cached model class meta + (instancetype)metaWithClass:(Class)cls { if (!cls) return nil; static CFMutableDictionaryRef cache; static dispatch_once_t onceToken; static dispatch_semaphore_t lock; dispatch_once(&onceToken, ^{ cache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); lock = dispatch_semaphore_create(1); }); dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); _YYModelMeta *meta = CFDictionaryGetValue(cache, (__bridge const void *)(cls)); dispatch_semaphore_signal(lock); if (!meta || meta->_classInfo.needUpdate) { meta = [[_YYModelMeta alloc] initWithClass:cls]; if (meta) { dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); CFDictionarySetValue(cache, (__bridge const void *)(cls), (__bridge const void *)(meta)); dispatch_semaphore_signal(lock); } } return meta; } @end /** Get number from property. @discussion Caller should hold strong reference to the parameters before this function returns. @param model Should not be nil. @param meta Should not be nil, meta.isCNumber should be YES, meta.getter should not be nil. @return A number object, or nil if failed. */ static force_inline NSNumber *ModelCreateNumberFromProperty(__unsafe_unretained id model, __unsafe_unretained _YYModelPropertyMeta *meta) { switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: { return @(((bool (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt8: { return @(((int8_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt8: { return @(((uint8_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt16: { return @(((int16_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt16: { return @(((uint16_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt32: { return @(((int32_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt32: { return @(((uint32_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt64: { return @(((int64_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt64: { return @(((uint64_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeFloat: { float num = ((float (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); if (isnan(num) || isinf(num)) return nil; return @(num); } case YYEncodingTypeDouble: { double num = ((double (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); if (isnan(num) || isinf(num)) return nil; return @(num); } case YYEncodingTypeLongDouble: { double num = ((long double (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); if (isnan(num) || isinf(num)) return nil; return @(num); } default: return nil; } } /** Set number to property. @discussion Caller should hold strong reference to the parameters before this function returns. @param model Should not be nil. @param num Can be nil. @param meta Should not be nil, meta.isCNumber should be YES, meta.setter should not be nil. */ static force_inline void ModelSetNumberToProperty(__unsafe_unretained id model, __unsafe_unretained NSNumber *num, __unsafe_unretained _YYModelPropertyMeta *meta) { switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: { ((void (*)(id, SEL, bool))(void *) objc_msgSend)((id)model, meta->_setter, num.boolValue); } break; case YYEncodingTypeInt8: { ((void (*)(id, SEL, int8_t))(void *) objc_msgSend)((id)model, meta->_setter, (int8_t)num.charValue); } break; case YYEncodingTypeUInt8: { ((void (*)(id, SEL, uint8_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint8_t)num.unsignedCharValue); } break; case YYEncodingTypeInt16: { ((void (*)(id, SEL, int16_t))(void *) objc_msgSend)((id)model, meta->_setter, (int16_t)num.shortValue); } break; case YYEncodingTypeUInt16: { ((void (*)(id, SEL, uint16_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint16_t)num.unsignedShortValue); } break; case YYEncodingTypeInt32: { ((void (*)(id, SEL, int32_t))(void *) objc_msgSend)((id)model, meta->_setter, (int32_t)num.intValue); } case YYEncodingTypeUInt32: { ((void (*)(id, SEL, uint32_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint32_t)num.unsignedIntValue); } break; case YYEncodingTypeInt64: { if ([num isKindOfClass:[NSDecimalNumber class]]) { ((void (*)(id, SEL, int64_t))(void *) objc_msgSend)((id)model, meta->_setter, (int64_t)num.stringValue.longLongValue); } else { ((void (*)(id, SEL, uint64_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint64_t)num.longLongValue); } } break; case YYEncodingTypeUInt64: { if ([num isKindOfClass:[NSDecimalNumber class]]) { ((void (*)(id, SEL, int64_t))(void *) objc_msgSend)((id)model, meta->_setter, (int64_t)num.stringValue.longLongValue); } else { ((void (*)(id, SEL, uint64_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint64_t)num.unsignedLongLongValue); } } break; case YYEncodingTypeFloat: { float f = num.floatValue; if (isnan(f) || isinf(f)) f = 0; ((void (*)(id, SEL, float))(void *) objc_msgSend)((id)model, meta->_setter, f); } break; case YYEncodingTypeDouble: { double d = num.doubleValue; if (isnan(d) || isinf(d)) d = 0; ((void (*)(id, SEL, double))(void *) objc_msgSend)((id)model, meta->_setter, d); } break; case YYEncodingTypeLongDouble: { long double d = num.doubleValue; if (isnan(d) || isinf(d)) d = 0; ((void (*)(id, SEL, long double))(void *) objc_msgSend)((id)model, meta->_setter, (long double)d); } // break; commented for code coverage in next line default: break; } } /** Set value to model with a property meta. @discussion Caller should hold strong reference to the parameters before this function returns. @param model Should not be nil. @param value Should not be nil, but can be NSNull. @param meta Should not be nil, and meta->_setter should not be nil. */ static void ModelSetValueForProperty(__unsafe_unretained id model, __unsafe_unretained id value, __unsafe_unretained _YYModelPropertyMeta *meta) { if (meta->_isCNumber) { NSNumber *num = YYNSNumberCreateFromID(value); ModelSetNumberToProperty(model, num, meta); if (num) [num class]; // hold the number } else if (meta->_nsType) { if (value == (id)kCFNull) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)nil); } else { switch (meta->_nsType) { case YYEncodingTypeNSString: case YYEncodingTypeNSMutableString: { if ([value isKindOfClass:[NSString class]]) { if (meta->_nsType == YYEncodingTypeNSString) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSString *)value).mutableCopy); } } else if ([value isKindOfClass:[NSNumber class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (meta->_nsType == YYEncodingTypeNSString) ? ((NSNumber *)value).stringValue : ((NSNumber *)value).stringValue.mutableCopy); } else if ([value isKindOfClass:[NSData class]]) { NSMutableString *string = [[NSMutableString alloc] initWithData:value encoding:NSUTF8StringEncoding]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, string); } else if ([value isKindOfClass:[NSURL class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (meta->_nsType == YYEncodingTypeNSString) ? ((NSURL *)value).absoluteString : ((NSURL *)value).absoluteString.mutableCopy); } else if ([value isKindOfClass:[NSAttributedString class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (meta->_nsType == YYEncodingTypeNSString) ? ((NSAttributedString *)value).string : ((NSAttributedString *)value).string.mutableCopy); } } break; case YYEncodingTypeNSValue: case YYEncodingTypeNSNumber: case YYEncodingTypeNSDecimalNumber: { if (meta->_nsType == YYEncodingTypeNSNumber) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, YYNSNumberCreateFromID(value)); } else if (meta->_nsType == YYEncodingTypeNSDecimalNumber) { if ([value isKindOfClass:[NSDecimalNumber class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else if ([value isKindOfClass:[NSNumber class]]) { NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithDecimal:[((NSNumber *)value) decimalValue]]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, decNum); } else if ([value isKindOfClass:[NSString class]]) { NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithString:value]; NSDecimal dec = decNum.decimalValue; if (dec._length == 0 && dec._isNegative) { decNum = nil; // NaN } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, decNum); } } else { // YYEncodingTypeNSValue if ([value isKindOfClass:[NSValue class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } } } break; case YYEncodingTypeNSData: case YYEncodingTypeNSMutableData: { if ([value isKindOfClass:[NSData class]]) { if (meta->_nsType == YYEncodingTypeNSData) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { NSMutableData *data = ((NSData *)value).mutableCopy; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, data); } } else if ([value isKindOfClass:[NSString class]]) { NSData *data = [(NSString *)value dataUsingEncoding:NSUTF8StringEncoding]; if (meta->_nsType == YYEncodingTypeNSMutableData) { data = ((NSData *)data).mutableCopy; } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, data); } } break; case YYEncodingTypeNSDate: { if ([value isKindOfClass:[NSDate class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else if ([value isKindOfClass:[NSString class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, YYNSDateFromString(value)); } } break; case YYEncodingTypeNSURL: { if ([value isKindOfClass:[NSURL class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else if ([value isKindOfClass:[NSString class]]) { NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet]; NSString *str = [value stringByTrimmingCharactersInSet:set]; if (str.length == 0) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, nil); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, [[NSURL alloc] initWithString:str]); } } } break; case YYEncodingTypeNSArray: case YYEncodingTypeNSMutableArray: { if (meta->_genericCls) { NSArray *valueArr = nil; if ([value isKindOfClass:[NSArray class]]) valueArr = value; else if ([value isKindOfClass:[NSSet class]]) valueArr = ((NSSet *)value).allObjects; if (valueArr) { NSMutableArray *objectArr = [NSMutableArray new]; for (id one in valueArr) { if ([one isKindOfClass:meta->_genericCls]) { [objectArr addObject:one]; } else if ([one isKindOfClass:[NSDictionary class]]) { Class cls = meta->_genericCls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:one]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } NSObject *newOne = [cls new]; [newOne modelSetWithDictionary:one]; if (newOne) [objectArr addObject:newOne]; } } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, objectArr); } } else { if ([value isKindOfClass:[NSArray class]]) { if (meta->_nsType == YYEncodingTypeNSArray) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSArray *)value).mutableCopy); } } else if ([value isKindOfClass:[NSSet class]]) { if (meta->_nsType == YYEncodingTypeNSArray) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSSet *)value).allObjects); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSSet *)value).allObjects.mutableCopy); } } } } break; case YYEncodingTypeNSDictionary: case YYEncodingTypeNSMutableDictionary: { if ([value isKindOfClass:[NSDictionary class]]) { if (meta->_genericCls) { NSMutableDictionary *dic = [NSMutableDictionary new]; [((NSDictionary *)value) enumerateKeysAndObjectsUsingBlock:^(NSString *oneKey, id oneValue, BOOL *stop) { if ([oneValue isKindOfClass:[NSDictionary class]]) { Class cls = meta->_genericCls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:oneValue]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } NSObject *newOne = [cls new]; [newOne modelSetWithDictionary:(id)oneValue]; if (newOne) dic[oneKey] = newOne; } }]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, dic); } else { if (meta->_nsType == YYEncodingTypeNSDictionary) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSDictionary *)value).mutableCopy); } } } } break; case YYEncodingTypeNSSet: case YYEncodingTypeNSMutableSet: { NSSet *valueSet = nil; if ([value isKindOfClass:[NSArray class]]) valueSet = [NSMutableSet setWithArray:value]; else if ([value isKindOfClass:[NSSet class]]) valueSet = ((NSSet *)value); if (meta->_genericCls) { NSMutableSet *set = [NSMutableSet new]; for (id one in valueSet) { if ([one isKindOfClass:meta->_genericCls]) { [set addObject:one]; } else if ([one isKindOfClass:[NSDictionary class]]) { Class cls = meta->_genericCls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:one]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } NSObject *newOne = [cls new]; [newOne modelSetWithDictionary:one]; if (newOne) [set addObject:newOne]; } } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, set); } else { if (meta->_nsType == YYEncodingTypeNSSet) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, valueSet); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSSet *)valueSet).mutableCopy); } } } // break; commented for code coverage in next line default: break; } } } else { BOOL isNull = (value == (id)kCFNull); switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { if (isNull) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)nil); } else if ([value isKindOfClass:meta->_cls] || !meta->_cls) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)value); } else if ([value isKindOfClass:[NSDictionary class]]) { NSObject *one = nil; if (meta->_getter) { one = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); } if (one) { [one modelSetWithDictionary:value]; } else { Class cls = meta->_cls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:value]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } one = [cls new]; [one modelSetWithDictionary:value]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)one); } } } break; case YYEncodingTypeClass: { if (isNull) { ((void (*)(id, SEL, Class))(void *) objc_msgSend)((id)model, meta->_setter, (Class)NULL); } else { Class cls = nil; if ([value isKindOfClass:[NSString class]]) { cls = NSClassFromString(value); if (cls) { ((void (*)(id, SEL, Class))(void *) objc_msgSend)((id)model, meta->_setter, (Class)cls); } } else { cls = object_getClass(value); if (cls) { if (class_isMetaClass(cls)) { ((void (*)(id, SEL, Class))(void *) objc_msgSend)((id)model, meta->_setter, (Class)value); } } } } } break; case YYEncodingTypeSEL: { if (isNull) { ((void (*)(id, SEL, SEL))(void *) objc_msgSend)((id)model, meta->_setter, (SEL)NULL); } else if ([value isKindOfClass:[NSString class]]) { SEL sel = NSSelectorFromString(value); if (sel) ((void (*)(id, SEL, SEL))(void *) objc_msgSend)((id)model, meta->_setter, (SEL)sel); } } break; case YYEncodingTypeBlock: { if (isNull) { ((void (*)(id, SEL, void (^)()))(void *) objc_msgSend)((id)model, meta->_setter, (void (^)())NULL); } else if ([value isKindOfClass:YYNSBlockClass()]) { ((void (*)(id, SEL, void (^)()))(void *) objc_msgSend)((id)model, meta->_setter, (void (^)())value); } } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: case YYEncodingTypeCArray: { if ([value isKindOfClass:[NSValue class]]) { const char *valueType = ((NSValue *)value).objCType; const char *metaType = meta->_info.typeEncoding.UTF8String; if (valueType && metaType && strcmp(valueType, metaType) == 0) { [model setValue:value forKey:meta->_name]; } } } break; case YYEncodingTypePointer: case YYEncodingTypeCString: { if (isNull) { ((void (*)(id, SEL, void *))(void *) objc_msgSend)((id)model, meta->_setter, (void *)NULL); } else if ([value isKindOfClass:[NSValue class]]) { NSValue *nsValue = value; if (nsValue.objCType && strcmp(nsValue.objCType, "^v") == 0) { ((void (*)(id, SEL, void *))(void *) objc_msgSend)((id)model, meta->_setter, nsValue.pointerValue); } } } // break; commented for code coverage in next line default: break; } } } typedef struct { void *modelMeta; ///< _YYModelMeta void *model; ///< id (self) void *dictionary; ///< NSDictionary (json) } ModelSetContext; /** Apply function for dictionary, to set the key-value pair to model. @param _key should not be nil, NSString. @param _value should not be nil. @param _context _context.modelMeta and _context.model should not be nil. */ static void ModelSetWithDictionaryFunction(const void *_key, const void *_value, void *_context) { ModelSetContext *context = _context; __unsafe_unretained _YYModelMeta *meta = (__bridge _YYModelMeta *)(context->modelMeta); __unsafe_unretained _YYModelPropertyMeta *propertyMeta = [meta->_mapper objectForKey:(__bridge id)(_key)]; __unsafe_unretained id model = (__bridge id)(context->model); while (propertyMeta) { if (propertyMeta->_setter) { ModelSetValueForProperty(model, (__bridge __unsafe_unretained id)_value, propertyMeta); } propertyMeta = propertyMeta->_next; }; } /** Apply function for model property meta, to set dictionary to model. @param _propertyMeta should not be nil, _YYModelPropertyMeta. @param _context _context.model and _context.dictionary should not be nil. */ static void ModelSetWithPropertyMetaArrayFunction(const void *_propertyMeta, void *_context) { ModelSetContext *context = _context; __unsafe_unretained NSDictionary *dictionary = (__bridge NSDictionary *)(context->dictionary); __unsafe_unretained _YYModelPropertyMeta *propertyMeta = (__bridge _YYModelPropertyMeta *)(_propertyMeta); if (!propertyMeta->_setter) return; id value = nil; if (propertyMeta->_mappedToKeyArray) { value = YYValueForMultiKeys(dictionary, propertyMeta->_mappedToKeyArray); } else if (propertyMeta->_mappedToKeyPath) { value = YYValueForKeyPath(dictionary, propertyMeta->_mappedToKeyPath); } else { value = [dictionary objectForKey:propertyMeta->_mappedToKey]; } if (value) { __unsafe_unretained id model = (__bridge id)(context->model); ModelSetValueForProperty(model, value, propertyMeta); } } /** Returns a valid JSON object (NSArray/NSDictionary/NSString/NSNumber/NSNull), or nil if an error occurs. @param model Model, can be nil. @return JSON object, nil if an error occurs. */ static id ModelToJSONObjectRecursive(NSObject *model) { if (!model || model == (id)kCFNull) return model; if ([model isKindOfClass:[NSString class]]) return model; if ([model isKindOfClass:[NSNumber class]]) return model; if ([model isKindOfClass:[NSDictionary class]]) { if ([NSJSONSerialization isValidJSONObject:model]) return model; NSMutableDictionary *newDic = [NSMutableDictionary new]; [((NSDictionary *)model) enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) { NSString *stringKey = [key isKindOfClass:[NSString class]] ? key : key.description; if (!stringKey) return; id jsonObj = ModelToJSONObjectRecursive(obj); if (!jsonObj) jsonObj = (id)kCFNull; newDic[stringKey] = jsonObj; }]; return newDic; } if ([model isKindOfClass:[NSSet class]]) { NSArray *array = ((NSSet *)model).allObjects; if ([NSJSONSerialization isValidJSONObject:array]) return array; NSMutableArray *newArray = [NSMutableArray new]; for (id obj in array) { if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) { [newArray addObject:obj]; } else { id jsonObj = ModelToJSONObjectRecursive(obj); if (jsonObj && jsonObj != (id)kCFNull) [newArray addObject:jsonObj]; } } return newArray; } if ([model isKindOfClass:[NSArray class]]) { if ([NSJSONSerialization isValidJSONObject:model]) return model; NSMutableArray *newArray = [NSMutableArray new]; for (id obj in (NSArray *)model) { if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) { [newArray addObject:obj]; } else { id jsonObj = ModelToJSONObjectRecursive(obj); if (jsonObj && jsonObj != (id)kCFNull) [newArray addObject:jsonObj]; } } return newArray; } if ([model isKindOfClass:[NSURL class]]) return ((NSURL *)model).absoluteString; if ([model isKindOfClass:[NSAttributedString class]]) return ((NSAttributedString *)model).string; if ([model isKindOfClass:[NSDate class]]) return [YYISODateFormatter() stringFromDate:(id)model]; if ([model isKindOfClass:[NSData class]]) return nil; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:[model class]]; if (!modelMeta || modelMeta->_keyMappedCount == 0) return nil; NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity:64]; __unsafe_unretained NSMutableDictionary *dic = result; // avoid retain and release in block [modelMeta->_mapper enumerateKeysAndObjectsUsingBlock:^(NSString *propertyMappedKey, _YYModelPropertyMeta *propertyMeta, BOOL *stop) { if (!propertyMeta->_getter) return; id value = nil; if (propertyMeta->_isCNumber) { value = ModelCreateNumberFromProperty(model, propertyMeta); } else if (propertyMeta->_nsType) { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = ModelToJSONObjectRecursive(v); } else { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = ModelToJSONObjectRecursive(v); if (value == (id)kCFNull) value = nil; } break; case YYEncodingTypeClass: { Class v = ((Class (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = v ? NSStringFromClass(v) : nil; } break; case YYEncodingTypeSEL: { SEL v = ((SEL (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = v ? NSStringFromSelector(v) : nil; } break; default: break; } } if (!value) return; if (propertyMeta->_mappedToKeyPath) { NSMutableDictionary *superDic = dic; NSMutableDictionary *subDic = nil; for (NSUInteger i = 0, max = propertyMeta->_mappedToKeyPath.count; i < max; i++) { NSString *key = propertyMeta->_mappedToKeyPath[i]; if (i + 1 == max) { // end if (!superDic[key]) superDic[key] = value; break; } subDic = superDic[key]; if (subDic) { if ([subDic isKindOfClass:[NSDictionary class]]) { subDic = subDic.mutableCopy; superDic[key] = subDic; } else { break; } } else { subDic = [NSMutableDictionary new]; superDic[key] = subDic; } superDic = subDic; subDic = nil; } } else { if (!dic[propertyMeta->_mappedToKey]) { dic[propertyMeta->_mappedToKey] = value; } } }]; if (modelMeta->_hasCustomTransformToDictionary) { BOOL suc = [((id<YYModel>)model) modelCustomTransformToDictionary:dic]; if (!suc) return nil; } return result; } /// Add indent to string (exclude first line) static NSMutableString *ModelDescriptionAddIndent(NSMutableString *desc, NSUInteger indent) { for (NSUInteger i = 0, max = desc.length; i < max; i++) { unichar c = [desc characterAtIndex:i]; if (c == '\n') { for (NSUInteger j = 0; j < indent; j++) { [desc insertString:@" " atIndex:i + 1]; } i += indent * 4; max += indent * 4; } } return desc; } /// Generaate a description string static NSString *ModelDescription(NSObject *model) { static const int kDescMaxLength = 100; if (!model) return @"<nil>"; if (model == (id)kCFNull) return @"<null>"; if (![model isKindOfClass:[NSObject class]]) return [NSString stringWithFormat:@"%@",model]; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:model.class]; switch (modelMeta->_nsType) { case YYEncodingTypeNSString: case YYEncodingTypeNSMutableString: { return [NSString stringWithFormat:@"\"%@\"",model]; } case YYEncodingTypeNSValue: case YYEncodingTypeNSData: case YYEncodingTypeNSMutableData: { NSString *tmp = model.description; if (tmp.length > kDescMaxLength) { tmp = [tmp substringToIndex:kDescMaxLength]; tmp = [tmp stringByAppendingString:@"..."]; } return tmp; } case YYEncodingTypeNSNumber: case YYEncodingTypeNSDecimalNumber: case YYEncodingTypeNSDate: case YYEncodingTypeNSURL: { return [NSString stringWithFormat:@"%@",model]; } case YYEncodingTypeNSSet: case YYEncodingTypeNSMutableSet: { model = ((NSSet *)model).allObjects; } // no break case YYEncodingTypeNSArray: case YYEncodingTypeNSMutableArray: { NSArray *array = (id)model; NSMutableString *desc = [NSMutableString new]; if (array.count == 0) { return [desc stringByAppendingString:@"[]"]; } else { [desc appendFormat:@"[\n"]; for (NSUInteger i = 0, max = array.count; i < max; i++) { NSObject *obj = array[i]; [desc appendString:@" "]; [desc appendString:ModelDescriptionAddIndent(ModelDescription(obj).mutableCopy, 1)]; [desc appendString:(i + 1 == max) ? @"\n" : @";\n"]; } [desc appendString:@"]"]; return desc; } } case YYEncodingTypeNSDictionary: case YYEncodingTypeNSMutableDictionary: { NSDictionary *dic = (id)model; NSMutableString *desc = [NSMutableString new]; if (dic.count == 0) { return [desc stringByAppendingString:@"{}"]; } else { NSArray *keys = dic.allKeys; [desc appendFormat:@"{\n"]; for (NSUInteger i = 0, max = keys.count; i < max; i++) { NSString *key = keys[i]; NSObject *value = dic[key]; [desc appendString:@" "]; [desc appendFormat:@"%@ = %@",key, ModelDescriptionAddIndent(ModelDescription(value).mutableCopy, 1)]; [desc appendString:(i + 1 == max) ? @"\n" : @";\n"]; } [desc appendString:@"}"]; } return desc; } default: { NSMutableString *desc = [NSMutableString new]; [desc appendFormat:@"<%@: %p>", model.class, model]; if (modelMeta->_allPropertyMetas.count == 0) return desc; // sort property names NSArray *properties = [modelMeta->_allPropertyMetas sortedArrayUsingComparator:^NSComparisonResult(_YYModelPropertyMeta *p1, _YYModelPropertyMeta *p2) { return [p1->_name compare:p2->_name]; }]; [desc appendFormat:@" {\n"]; for (NSUInteger i = 0, max = properties.count; i < max; i++) { _YYModelPropertyMeta *property = properties[i]; NSString *propertyDesc; if (property->_isCNumber) { NSNumber *num = ModelCreateNumberFromProperty(model, property); propertyDesc = num.stringValue; } else { switch (property->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = ModelDescription(v); if (!propertyDesc) propertyDesc = @"<nil>"; } break; case YYEncodingTypeClass: { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = ((NSObject *)v).description; if (!propertyDesc) propertyDesc = @"<nil>"; } break; case YYEncodingTypeSEL: { SEL sel = ((SEL (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); if (sel) propertyDesc = NSStringFromSelector(sel); else propertyDesc = @"<NULL>"; } break; case YYEncodingTypeBlock: { id block = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = block ? ((NSObject *)block).description : @"<nil>"; } break; case YYEncodingTypeCArray: case YYEncodingTypeCString: case YYEncodingTypePointer: { void *pointer = ((void* (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = [NSString stringWithFormat:@"%p",pointer]; } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { NSValue *value = [model valueForKey:property->_name]; propertyDesc = value ? value.description : @"{unknown}"; } break; default: propertyDesc = @"<unknown>"; } } propertyDesc = ModelDescriptionAddIndent(propertyDesc.mutableCopy, 1); [desc appendFormat:@" %@ = %@",property->_name, propertyDesc]; [desc appendString:(i + 1 == max) ? @"\n" : @";\n"]; } [desc appendFormat:@"}"]; return desc; } } } @implementation NSObject (YYModel) + (NSDictionary *)_yy_dictionaryWithJSON:(id)json { if (!json || json == (id)kCFNull) return nil; NSDictionary *dic = nil; NSData *jsonData = nil; if ([json isKindOfClass:[NSDictionary class]]) { dic = json; } else if ([json isKindOfClass:[NSString class]]) { jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding]; } else if ([json isKindOfClass:[NSData class]]) { jsonData = json; } if (jsonData) { dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL]; if (![dic isKindOfClass:[NSDictionary class]]) dic = nil; } return dic; } + (instancetype)modelWithJSON:(id)json { NSDictionary *dic = [self _yy_dictionaryWithJSON:json]; return [self modelWithDictionary:dic]; } + (instancetype)modelWithDictionary:(NSDictionary *)dictionary { if (!dictionary || dictionary == (id)kCFNull) return nil; if (![dictionary isKindOfClass:[NSDictionary class]]) return nil; Class cls = [self class]; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:cls]; if (modelMeta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:dictionary] ?: cls; } NSObject *one = [cls new]; if ([one modelSetWithDictionary:dictionary]) return one; return nil; } - (BOOL)modelSetWithJSON:(id)json { NSDictionary *dic = [NSObject _yy_dictionaryWithJSON:json]; return [self modelSetWithDictionary:dic]; } - (BOOL)modelSetWithDictionary:(NSDictionary *)dic { if (!dic || dic == (id)kCFNull) return NO; if (![dic isKindOfClass:[NSDictionary class]]) return NO; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:object_getClass(self)]; if (modelMeta->_keyMappedCount == 0) return NO; if (modelMeta->_hasCustomWillTransformFromDictionary) { dic = [((id<YYModel>)self) modelCustomWillTransformFromDictionary:dic]; if (![dic isKindOfClass:[NSDictionary class]]) return NO; } ModelSetContext context = {0}; context.modelMeta = (__bridge void *)(modelMeta); context.model = (__bridge void *)(self); context.dictionary = (__bridge void *)(dic); if (modelMeta->_keyMappedCount >= CFDictionaryGetCount((CFDictionaryRef)dic)) { CFDictionaryApplyFunction((CFDictionaryRef)dic, ModelSetWithDictionaryFunction, &context); if (modelMeta->_keyPathPropertyMetas) { CFArrayApplyFunction((CFArrayRef)modelMeta->_keyPathPropertyMetas, CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta->_keyPathPropertyMetas)), ModelSetWithPropertyMetaArrayFunction, &context); } if (modelMeta->_multiKeysPropertyMetas) { CFArrayApplyFunction((CFArrayRef)modelMeta->_multiKeysPropertyMetas, CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta->_multiKeysPropertyMetas)), ModelSetWithPropertyMetaArrayFunction, &context); } } else { CFArrayApplyFunction((CFArrayRef)modelMeta->_allPropertyMetas, CFRangeMake(0, modelMeta->_keyMappedCount), ModelSetWithPropertyMetaArrayFunction, &context); } if (modelMeta->_hasCustomTransformFromDictionary) { return [((id<YYModel>)self) modelCustomTransformFromDictionary:dic]; } return YES; } - (id)modelToJSONObject { /* Apple said: The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All dictionary keys are instances of NSString. Numbers are not NaN or infinity. */ id jsonObject = ModelToJSONObjectRecursive(self); if ([jsonObject isKindOfClass:[NSArray class]]) return jsonObject; if ([jsonObject isKindOfClass:[NSDictionary class]]) return jsonObject; return nil; } - (NSData *)modelToJSONData { id jsonObject = [self modelToJSONObject]; if (!jsonObject) return nil; return [NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:NULL]; } - (NSString *)modelToJSONString { NSData *jsonData = [self modelToJSONData]; if (jsonData.length == 0) return nil; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } - (id)modelCopy{ if (self == (id)kCFNull) return self; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return [self copy]; NSObject *one = [self.class new]; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_getter || !propertyMeta->_setter) continue; if (propertyMeta->_isCNumber) { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: { bool num = ((bool (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, bool))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt8: case YYEncodingTypeUInt8: { uint8_t num = ((bool (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint8_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt16: case YYEncodingTypeUInt16: { uint16_t num = ((uint16_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint16_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt32: case YYEncodingTypeUInt32: { uint32_t num = ((uint32_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint32_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt64: case YYEncodingTypeUInt64: { uint64_t num = ((uint64_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint64_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeFloat: { float num = ((float (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, float))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeDouble: { double num = ((double (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, double))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeLongDouble: { long double num = ((long double (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, long double))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } // break; commented for code coverage in next line default: break; } } else { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: case YYEncodingTypeClass: case YYEncodingTypeBlock: { id value = ((id (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)one, propertyMeta->_setter, value); } break; case YYEncodingTypeSEL: case YYEncodingTypePointer: case YYEncodingTypeCString: { size_t value = ((size_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, size_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, value); } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { @try { NSValue *value = [self valueForKey:NSStringFromSelector(propertyMeta->_getter)]; if (value) { [one setValue:value forKey:propertyMeta->_name]; } } @catch (NSException *exception) {} } // break; commented for code coverage in next line default: break; } } } return one; } - (void)modelEncodeWithCoder:(NSCoder *)aCoder { if (!aCoder) return; if (self == (id)kCFNull) { [((id<NSCoding>)self)encodeWithCoder:aCoder]; return; } _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) { [((id<NSCoding>)self)encodeWithCoder:aCoder]; return; } for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_getter) return; if (propertyMeta->_isCNumber) { NSNumber *value = ModelCreateNumberFromProperty(self, propertyMeta); if (value) [aCoder encodeObject:value forKey:propertyMeta->_name]; } else { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { id value = ((id (*)(id, SEL))(void *)objc_msgSend)((id)self, propertyMeta->_getter); if (value && (propertyMeta->_nsType || [value respondsToSelector:@selector(encodeWithCoder:)])) { if ([value isKindOfClass:[NSValue class]]) { if ([value isKindOfClass:[NSNumber class]]) { [aCoder encodeObject:value forKey:propertyMeta->_name]; } } else { [aCoder encodeObject:value forKey:propertyMeta->_name]; } } } break; case YYEncodingTypeSEL: { SEL value = ((SEL (*)(id, SEL))(void *)objc_msgSend)((id)self, propertyMeta->_getter); if (value) { NSString *str = NSStringFromSelector(value); [aCoder encodeObject:str forKey:propertyMeta->_name]; } } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { if (propertyMeta->_isKVCCompatible && propertyMeta->_isStructAvailableForKeyedArchiver) { @try { NSValue *value = [self valueForKey:NSStringFromSelector(propertyMeta->_getter)]; [aCoder encodeObject:value forKey:propertyMeta->_name]; } @catch (NSException *exception) {} } } break; default: break; } } } } - (id)modelInitWithCoder:(NSCoder *)aDecoder { if (!aDecoder) return self; if (self == (id)kCFNull) return self; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return self; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_setter) continue; if (propertyMeta->_isCNumber) { NSNumber *value = [aDecoder decodeObjectForKey:propertyMeta->_name]; if ([value isKindOfClass:[NSNumber class]]) { ModelSetNumberToProperty(self, value, propertyMeta); [value class]; } } else { YYEncodingType type = propertyMeta->_type & YYEncodingTypeMask; switch (type) { case YYEncodingTypeObject: { id value = [aDecoder decodeObjectForKey:propertyMeta->_name]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)self, propertyMeta->_setter, value); } break; case YYEncodingTypeSEL: { NSString *str = [aDecoder decodeObjectForKey:propertyMeta->_name]; if ([str isKindOfClass:[NSString class]]) { SEL sel = NSSelectorFromString(str); ((void (*)(id, SEL, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_setter, sel); } } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { if (propertyMeta->_isKVCCompatible) { @try { NSValue *value = [aDecoder decodeObjectForKey:propertyMeta->_name]; if (value) [self setValue:value forKey:propertyMeta->_name]; } @catch (NSException *exception) {} } } break; default: break; } } } return self; } - (NSUInteger)modelHash { if (self == (id)kCFNull) return [self hash]; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return [self hash]; NSUInteger value = 0; NSUInteger count = 0; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_isKVCCompatible) continue; value ^= [[self valueForKey:NSStringFromSelector(propertyMeta->_getter)] hash]; count++; } if (count == 0) value = (long)((__bridge void *)self); return value; } - (BOOL)modelIsEqual:(id)model { if (self == model) return YES; if (![model isMemberOfClass:self.class]) return NO; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return [self isEqual:model]; if ([self hash] != [model hash]) return NO; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_isKVCCompatible) continue; id this = [self valueForKey:NSStringFromSelector(propertyMeta->_getter)]; id that = [model valueForKey:NSStringFromSelector(propertyMeta->_getter)]; if (this == that) continue; if (this == nil || that == nil) return NO; if (![this isEqual:that]) return NO; } return YES; } - (BOOL)modelIsEqualToModel:(id)model { if (self == model) return YES; if (![model isMemberOfClass:self.class]) return NO; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return [self isEqual:model]; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_isKVCCompatible) continue; NSString *propertyMetaGetter = NSStringFromSelector(propertyMeta->_getter); if ([propertyMetaGetter isEqualToString:@"classId"] || [propertyMetaGetter isEqualToString:@"className"] || [propertyMetaGetter isEqualToString:@"inviterInfoModel"] || [propertyMetaGetter isEqualToString:@"groupName"]) continue; id this = [self valueForKey:propertyMetaGetter]; id that = [model valueForKey:propertyMetaGetter]; if (this == that) continue; if (this == nil || that == nil) return NO; if (![this isEqual:that]) return NO; } return YES; } - (NSString *)modelDescription { return ModelDescription(self); } @end @implementation NSArray (YYModel) + (NSArray *)modelArrayWithClass:(Class)cls json:(id)json { if (!json) return nil; NSArray *arr = nil; NSData *jsonData = nil; if ([json isKindOfClass:[NSArray class]]) { arr = json; } else if ([json isKindOfClass:[NSString class]]) { jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding]; } else if ([json isKindOfClass:[NSData class]]) { jsonData = json; } if (jsonData) { arr = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL]; if (![arr isKindOfClass:[NSArray class]]) arr = nil; } return [self modelArrayWithClass:cls array:arr]; } + (NSArray *)modelArrayWithClass:(Class)cls array:(NSArray *)arr { if (!cls || !arr) return nil; NSMutableArray *result = [NSMutableArray new]; for (NSDictionary *dic in arr) { if (![dic isKindOfClass:[NSDictionary class]]) continue; NSObject *obj = [cls modelWithDictionary:dic]; if (obj) [result addObject:obj]; } return result; } @end @implementation NSDictionary (YYModel) + (NSDictionary *)modelDictionaryWithClass:(Class)cls json:(id)json { if (!json) return nil; NSDictionary *dic = nil; NSData *jsonData = nil; if ([json isKindOfClass:[NSDictionary class]]) { dic = json; } else if ([json isKindOfClass:[NSString class]]) { jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding]; } else if ([json isKindOfClass:[NSData class]]) { jsonData = json; } if (jsonData) { dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL]; if (![dic isKindOfClass:[NSDictionary class]]) dic = nil; } return [self modelDictionaryWithClass:cls dictionary:dic]; } + (NSDictionary *)modelDictionaryWithClass:(Class)cls dictionary:(NSDictionary *)dic { if (!cls || !dic) return nil; NSMutableDictionary *result = [NSMutableDictionary new]; for (NSString *key in dic.allKeys) { if (![key isKindOfClass:[NSString class]]) continue; NSObject *obj = [cls modelWithDictionary:dic[key]]; if (obj) result[key] = obj; } return result; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Model/NSObject+YYModel.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
18,117
```objective-c // // YYLabel.m // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYLabel.h" #import "YYAsyncLayer.h" #import "YYWeakProxy.h" #import "YYCGUtilities.h" #import "NSAttributedString+YYText.h" #if __has_include("YYDispatchQueuePool.h") #import "YYDispatchQueuePool.h" #endif #ifdef YYDispatchQueuePool_h static dispatch_queue_t YYLabelGetReleaseQueue() { return YYDispatchQueueGetForQOS(NSQualityOfServiceUtility); } #else static dispatch_queue_t YYLabelGetReleaseQueue() { return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0); } #endif #define kLongPressMinimumDuration 0.5 // Time in seconds the fingers must be held down for long press gesture. #define kLongPressAllowableMovement 9.0 // Maximum movement in points allowed before the long press fails. #define kHighlightFadeDuration 0.15 // Time in seconds for highlight fadeout animation. #define kAsyncFadeDuration 0.08 // Time in seconds for async display fadeout animation. @interface YYLabel() <YYTextDebugTarget, YYAsyncLayerDelegate> { NSMutableAttributedString *_innerText; ///< nonnull YYTextLayout *_innerLayout; YYTextContainer *_innerContainer; ///< nonnull NSMutableArray *_attachmentViews; NSMutableArray *_attachmentLayers; NSRange _highlightRange; ///< current highlight range YYTextHighlight *_highlight; ///< highlight attribute in `_highlightRange` YYTextLayout *_highlightLayout; ///< when _state.showingHighlight=YES, this layout should be displayed YYTextLayout *_shrinkInnerLayout; YYTextLayout *_shrinkHighlightLayout; NSTimer *_longPressTimer; CGPoint _touchBeganPoint; struct { unsigned int layoutNeedUpdate : 1; unsigned int showingHighlight : 1; unsigned int trackingTouch : 1; unsigned int swallowTouch : 1; unsigned int touchMoved : 1; unsigned int hasTapAction : 1; unsigned int hasLongPressAction : 1; unsigned int contentsNeedFade : 1; } _state; } @end @implementation YYLabel #pragma mark - Private - (void)_updateIfNeeded { if (_state.layoutNeedUpdate) { _state.layoutNeedUpdate = NO; [self _updateLayout]; [self.layer setNeedsDisplay]; } } - (void)_updateLayout { _innerLayout = [YYTextLayout layoutWithContainer:_innerContainer text:_innerText]; _shrinkInnerLayout = [YYLabel _shrinkLayoutWithLayout:_innerLayout]; } - (void)_setLayoutNeedUpdate { _state.layoutNeedUpdate = YES; [self _clearInnerLayout]; [self _setLayoutNeedRedraw]; } - (void)_setLayoutNeedRedraw { [self.layer setNeedsDisplay]; } - (void)_clearInnerLayout { if (!_innerLayout) return; YYTextLayout *layout = _innerLayout; _innerLayout = nil; _shrinkInnerLayout = nil; dispatch_async(YYLabelGetReleaseQueue(), ^{ NSAttributedString *text = [layout text]; // capture to block and release in background if (layout.attachments.count) { dispatch_async(dispatch_get_main_queue(), ^{ [text length]; // capture to block and release in main thread (maybe there's UIView/CALayer attachments). }); } }); } - (YYTextLayout *)_innerLayout { return _shrinkInnerLayout ? _shrinkInnerLayout : _innerLayout; } - (YYTextLayout *)_highlightLayout { return _shrinkHighlightLayout ? _shrinkHighlightLayout : _highlightLayout; } + (YYTextLayout *)_shrinkLayoutWithLayout:(YYTextLayout *)layout { if (layout.text.length && layout.lines.count == 0) { YYTextContainer *container = layout.container.copy; container.maximumNumberOfRows = 1; CGSize containerSize = container.size; if (!container.verticalForm) { containerSize.height = YYTextContainerMaxSize.height; } else { containerSize.width = YYTextContainerMaxSize.width; } container.size = containerSize; return [YYTextLayout layoutWithContainer:container text:layout.text]; } else { return nil; } } - (void)_startLongPressTimer { [_longPressTimer invalidate]; _longPressTimer = [NSTimer timerWithTimeInterval:kLongPressMinimumDuration target:[YYWeakProxy proxyWithTarget:self] selector:@selector(_trackDidLongPress) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:_longPressTimer forMode:NSRunLoopCommonModes]; } - (void)_endLongPressTimer { [_longPressTimer invalidate]; _longPressTimer = nil; } - (void)_trackDidLongPress { [self _endLongPressTimer]; if (_state.hasLongPressAction && _textLongPressAction) { NSRange range = NSMakeRange(NSNotFound, 0); CGRect rect = CGRectNull; CGPoint point = [self _convertPointToLayout:_touchBeganPoint]; YYTextRange *textRange = [self._innerLayout textRangeAtPoint:point]; CGRect textRect = [self._innerLayout rectForRange:textRange]; textRect = [self _convertRectFromLayout:textRect]; if (textRange) { range = textRange.asRange; rect = textRect; } _textLongPressAction(self, _innerText, range, rect); } if (_highlight) { YYTextAction longPressAction = _highlight.longPressAction ? _highlight.longPressAction : _highlightLongPressAction; if (longPressAction) { YYTextPosition *start = [YYTextPosition positionWithOffset:_highlightRange.location]; YYTextPosition *end = [YYTextPosition positionWithOffset:_highlightRange.location + _highlightRange.length affinity:YYTextAffinityBackward]; YYTextRange *range = [YYTextRange rangeWithStart:start end:end]; CGRect rect = [self._innerLayout rectForRange:range]; rect = [self _convertRectFromLayout:rect]; longPressAction(self, _innerText, _highlightRange, rect); [self _removeHighlightAnimated:YES]; _state.trackingTouch = NO; } } } - (YYTextHighlight *)_getHighlightAtPoint:(CGPoint)point range:(NSRangePointer)range { if (!self._innerLayout.containsHighlight) return nil; point = [self _convertPointToLayout:point]; YYTextRange *textRange = [self._innerLayout textRangeAtPoint:point]; if (!textRange) return nil; NSUInteger startIndex = textRange.start.offset; if (startIndex == _innerText.length) { if (startIndex > 0) { startIndex--; } } NSRange highlightRange = {0}; YYTextHighlight *highlight = [_innerText attribute:YYTextHighlightAttributeName atIndex:startIndex longestEffectiveRange:&highlightRange inRange:NSMakeRange(0, _innerText.length)]; if (!highlight) return nil; if (range) *range = highlightRange; return highlight; } - (void)_showHighlightAnimated:(BOOL)animated { if (!_highlight) return; if (!_highlightLayout) { NSMutableAttributedString *hiText = _innerText.mutableCopy; NSDictionary *newAttrs = _highlight.attributes; [newAttrs enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) { [hiText setAttribute:key value:value range:_highlightRange]; }]; _highlightLayout = [YYTextLayout layoutWithContainer:_innerContainer text:hiText]; _shrinkHighlightLayout = [YYLabel _shrinkLayoutWithLayout:_highlightLayout]; if (!_highlightLayout) _highlight = nil; } if (_highlightLayout && !_state.showingHighlight) { _state.showingHighlight = YES; _state.contentsNeedFade = animated; [self _setLayoutNeedRedraw]; } } - (void)_hideHighlightAnimated:(BOOL)animated { if (_state.showingHighlight) { _state.showingHighlight = NO; _state.contentsNeedFade = animated; [self _setLayoutNeedRedraw]; } } - (void)_removeHighlightAnimated:(BOOL)animated { [self _hideHighlightAnimated:animated]; _highlight = nil; _highlightLayout = nil; _shrinkHighlightLayout = nil; } - (void)_endTouch { [self _endLongPressTimer]; [self _removeHighlightAnimated:YES]; _state.trackingTouch = NO; } - (CGPoint)_convertPointToLayout:(CGPoint)point { CGSize boundingSize = self._innerLayout.textBoundingSize; if (self._innerLayout.container.isVerticalForm) { CGFloat w = self._innerLayout.textBoundingSize.width; if (w < self.bounds.size.width) w = self.bounds.size.width; point.x += self._innerLayout.container.size.width - w; if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.x += (self.bounds.size.width - boundingSize.width) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.x += (self.bounds.size.width - boundingSize.width); } return point; } else { if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.y -= (self.bounds.size.height - boundingSize.height) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.y -= (self.bounds.size.height - boundingSize.height); } return point; } } - (CGPoint)_convertPointFromLayout:(CGPoint)point { CGSize boundingSize = self._innerLayout.textBoundingSize; if (self._innerLayout.container.isVerticalForm) { CGFloat w = self._innerLayout.textBoundingSize.width; if (w < self.bounds.size.width) w = self.bounds.size.width; point.x -= self._innerLayout.container.size.width - w; if (boundingSize.width < self.bounds.size.width) { if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.x -= (self.bounds.size.width - boundingSize.width) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.x -= (self.bounds.size.width - boundingSize.width); } } return point; } else { if (boundingSize.height < self.bounds.size.height) { if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.y += (self.bounds.size.height - boundingSize.height) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.y += (self.bounds.size.height - boundingSize.height); } } return point; } } - (CGRect)_convertRectToLayout:(CGRect)rect { rect.origin = [self _convertPointToLayout:rect.origin]; return rect; } - (CGRect)_convertRectFromLayout:(CGRect)rect { rect.origin = [self _convertPointFromLayout:rect.origin]; return rect; } - (UIFont *)_defaultFont { return [UIFont systemFontOfSize:17]; } - (NSShadow *)_shadowFromProperties { if (!_shadowColor || _shadowBlurRadius < 0) return nil; NSShadow *shadow = [NSShadow new]; shadow.shadowColor = _shadowColor; #if !TARGET_INTERFACE_BUILDER shadow.shadowOffset = _shadowOffset; #else shadow.shadowOffset = CGSizeMake(_shadowOffset.x, _shadowOffset.y); #endif shadow.shadowBlurRadius = _shadowBlurRadius; return shadow; } - (void)_updateOuterLineBreakMode { if (_innerContainer.truncationType) { switch (_innerContainer.truncationType) { case YYTextTruncationTypeStart: { _lineBreakMode = NSLineBreakByTruncatingHead; } break; case YYTextTruncationTypeEnd: { _lineBreakMode = NSLineBreakByTruncatingTail; } break; case YYTextTruncationTypeMiddle: { _lineBreakMode = NSLineBreakByTruncatingMiddle; } break; default:break; } } else { _lineBreakMode = _innerText.lineBreakMode; } } - (void)_updateOuterTextProperties { _text = [_innerText plainTextForRange:NSMakeRange(0, _innerText.length)]; _font = _innerText.font; if (!_font) _font = [self _defaultFont]; _textColor = _innerText.color; if (!_textColor) _textColor = [UIColor blackColor]; _textAlignment = _innerText.alignment; _lineBreakMode = _innerText.lineBreakMode; NSShadow *shadow = _innerText.shadow; _shadowColor = shadow.shadowColor; #if !TARGET_INTERFACE_BUILDER _shadowOffset = shadow.shadowOffset; #else _shadowOffset = CGPointMake(shadow.shadowOffset.width, shadow.shadowOffset.height); #endif _shadowBlurRadius = shadow.shadowBlurRadius; _attributedText = _innerText; [self _updateOuterLineBreakMode]; } - (void)_updateOuterContainerProperties { _truncationToken = _innerContainer.truncationToken; _numberOfLines = _innerContainer.maximumNumberOfRows; _textContainerPath = _innerContainer.path; _exclusionPaths = _innerContainer.exclusionPaths; _textContainerInset = _innerContainer.insets; _verticalForm = _innerContainer.verticalForm; _linePositionModifier = _innerContainer.linePositionModifier; [self _updateOuterLineBreakMode]; } - (void)_clearContents { CGImageRef image = (__bridge_retained CGImageRef)(self.layer.contents); self.layer.contents = nil; if (image) { dispatch_async(YYLabelGetReleaseQueue(), ^{ CFRelease(image); }); } } - (void)_initLabel { ((YYAsyncLayer *)self.layer).displaysAsynchronously = NO; self.layer.contentsScale = [UIScreen mainScreen].scale; self.contentMode = UIViewContentModeRedraw; _attachmentViews = [NSMutableArray new]; _attachmentLayers = [NSMutableArray new]; _debugOption = [YYTextDebugOption sharedDebugOption]; [YYTextDebugOption addDebugTarget:self]; _font = [self _defaultFont]; _textColor = [UIColor blackColor]; _textVerticalAlignment = YYTextVerticalAlignmentCenter; _numberOfLines = 1; _textAlignment = NSTextAlignmentNatural; _lineBreakMode = NSLineBreakByTruncatingTail; _innerText = [NSMutableAttributedString new]; _innerContainer = [YYTextContainer new]; _innerContainer.truncationType = YYTextTruncationTypeEnd; _innerContainer.maximumNumberOfRows = _numberOfLines; _clearContentsBeforeAsynchronouslyDisplay = YES; _fadeOnAsynchronouslyDisplay = YES; _fadeOnHighlight = YES; self.isAccessibilityElement = YES; } #pragma mark - Override - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:CGRectZero]; if (!self) return nil; self.backgroundColor = [UIColor clearColor]; self.opaque = NO; [self _initLabel]; self.frame = frame; return self; } - (void)dealloc { [YYTextDebugOption removeDebugTarget:self]; [_longPressTimer invalidate]; } + (Class)layerClass { return [YYAsyncLayer class]; } - (void)setFrame:(CGRect)frame { CGSize oldSize = self.bounds.size; [super setFrame:frame]; CGSize newSize = self.bounds.size; if (!CGSizeEqualToSize(oldSize, newSize)) { _innerContainer.size = self.bounds.size; if (!_ignoreCommonProperties) { _state.layoutNeedUpdate = YES; } if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedRedraw]; } } - (void)setBounds:(CGRect)bounds { CGSize oldSize = self.bounds.size; [super setBounds:bounds]; CGSize newSize = self.bounds.size; if (!CGSizeEqualToSize(oldSize, newSize)) { _innerContainer.size = self.bounds.size; if (!_ignoreCommonProperties) { _state.layoutNeedUpdate = YES; } if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedRedraw]; } } - (CGSize)sizeThatFits:(CGSize)size { if (_ignoreCommonProperties) { return _innerLayout.textBoundingSize; } if (!_verticalForm && size.width <= 0) size.width = YYTextContainerMaxSize.width; if (_verticalForm && size.height <= 0) size.height = YYTextContainerMaxSize.height; if ((!_verticalForm && size.width == self.bounds.size.width) || (_verticalForm && size.height == self.bounds.size.height)) { [self _updateIfNeeded]; YYTextLayout *layout = self._innerLayout; BOOL contains = NO; if (layout.container.maximumNumberOfRows == 0) { if (layout.truncatedLine == nil) { contains = YES; } } else { if (layout.rowCount <= layout.container.maximumNumberOfRows) { contains = YES; } } if (contains) { return layout.textBoundingSize; } } if (!_verticalForm) { size.height = YYTextContainerMaxSize.height; } else { size.width = YYTextContainerMaxSize.width; } YYTextContainer *container = [_innerContainer copy]; container.size = size; YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:_innerText]; return layout.textBoundingSize; } - (NSString *)accessibilityLabel { return [_innerLayout.text plainTextForRange:_innerLayout.text.rangeOfAll]; } #pragma mark - NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder { [super encodeWithCoder:aCoder]; [aCoder encodeObject:_attributedText forKey:@"attributedText"]; [aCoder encodeObject:_innerContainer forKey:@"innerContainer"]; } - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; [self _initLabel]; YYTextContainer *innerContainer = [aDecoder decodeObjectForKey:@"innerContainer"]; if (innerContainer) { _innerContainer = innerContainer; } else { _innerContainer.size = self.bounds.size; } [self _updateOuterContainerProperties]; self.attributedText = [aDecoder decodeObjectForKey:@"attributedText"]; [self _setLayoutNeedUpdate]; return self; } #pragma mark - Touches - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self _updateIfNeeded]; UITouch *touch = touches.anyObject; CGPoint point = [touch locationInView:self]; _highlight = [self _getHighlightAtPoint:point range:&_highlightRange]; _highlightLayout = nil; _shrinkHighlightLayout = nil; _state.hasTapAction = _textTapAction != nil; _state.hasLongPressAction = _textLongPressAction != nil; if (_highlight || _textTapAction || _textLongPressAction) { _touchBeganPoint = point; _state.trackingTouch = YES; _state.swallowTouch = YES; _state.touchMoved = NO; [self _startLongPressTimer]; if (_highlight) [self _showHighlightAnimated:NO]; } else { _state.trackingTouch = NO; _state.swallowTouch = NO; _state.touchMoved = NO; } if (!_state.swallowTouch) { [super touchesBegan:touches withEvent:event]; } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [self _updateIfNeeded]; UITouch *touch = touches.anyObject; CGPoint point = [touch locationInView:self]; if (_state.trackingTouch) { if (!_state.touchMoved) { CGFloat moveH = point.x - _touchBeganPoint.x; CGFloat moveV = point.y - _touchBeganPoint.y; if (fabs(moveH) > fabs(moveV)) { if (fabs(moveH) > kLongPressAllowableMovement) _state.touchMoved = YES; } else { if (fabs(moveV) > kLongPressAllowableMovement) _state.touchMoved = YES; } if (_state.touchMoved) { [self _endLongPressTimer]; } } if (_state.touchMoved && _highlight) { YYTextHighlight *highlight = [self _getHighlightAtPoint:point range:NULL]; if (highlight == _highlight) { [self _showHighlightAnimated:_fadeOnHighlight]; } else { [self _hideHighlightAnimated:_fadeOnHighlight]; } } } if (!_state.swallowTouch) { [super touchesMoved:touches withEvent:event]; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = touches.anyObject; CGPoint point = [touch locationInView:self]; if (_state.trackingTouch) { [self _endLongPressTimer]; if (!_state.touchMoved && _textTapAction) { NSRange range = NSMakeRange(NSNotFound, 0); CGRect rect = CGRectNull; CGPoint point = [self _convertPointToLayout:_touchBeganPoint]; YYTextRange *textRange = [self._innerLayout textRangeAtPoint:point]; CGRect textRect = [self._innerLayout rectForRange:textRange]; textRect = [self _convertRectFromLayout:textRect]; if (textRange) { range = textRange.asRange; rect = textRect; } _textTapAction(self, _innerText, range, rect); } if (_highlight) { if (!_state.touchMoved || [self _getHighlightAtPoint:point range:NULL] == _highlight) { YYTextAction tapAction = _highlight.tapAction ? _highlight.tapAction : _highlightTapAction; if (tapAction) { YYTextPosition *start = [YYTextPosition positionWithOffset:_highlightRange.location]; YYTextPosition *end = [YYTextPosition positionWithOffset:_highlightRange.location + _highlightRange.length affinity:YYTextAffinityBackward]; YYTextRange *range = [YYTextRange rangeWithStart:start end:end]; CGRect rect = [self._innerLayout rectForRange:range]; rect = [self _convertRectFromLayout:rect]; tapAction(self, _innerText, _highlightRange, rect); } } [self _removeHighlightAnimated:_fadeOnHighlight]; } } if (!_state.swallowTouch) { [super touchesEnded:touches withEvent:event]; } } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [self _endTouch]; if (!_state.swallowTouch) [super touchesCancelled:touches withEvent:event]; } #pragma mark - Properties - (void)setText:(NSString *)text { if (_text == text || [_text isEqualToString:text]) return; _text = text.copy; BOOL needAddAttributes = _innerText.length == 0 && text.length > 0; [_innerText replaceCharactersInRange:NSMakeRange(0, _innerText.length) withString:text ? text : @""]; [_innerText removeDiscontinuousAttributesInRange:NSMakeRange(0, _innerText.length)]; if (needAddAttributes) { _innerText.font = _font; _innerText.color = _textColor; _innerText.shadow = [self _shadowFromProperties]; _innerText.alignment = _textAlignment; switch (_lineBreakMode) { case NSLineBreakByWordWrapping: case NSLineBreakByCharWrapping: case NSLineBreakByClipping: { _innerText.lineBreakMode = _lineBreakMode; } break; case NSLineBreakByTruncatingHead: case NSLineBreakByTruncatingTail: case NSLineBreakByTruncatingMiddle: { _innerText.lineBreakMode = NSLineBreakByWordWrapping; } break; default: break; } } if ([_textParser parseText:_innerText selectedRange:NULL]) { [self _updateOuterTextProperties]; } if (!_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setFont:(UIFont *)font { if (!font) { font = [self _defaultFont]; } if (_font == font || [_font isEqual:font]) return; _font = font; _innerText.font = _font; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setTextColor:(UIColor *)textColor { if (!textColor) { textColor = [UIColor blackColor]; } if (_textColor == textColor || [_textColor isEqual:textColor]) return; _textColor = textColor; _innerText.color = textColor; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; } } - (void)setShadowColor:(UIColor *)shadowColor { if (_shadowColor == shadowColor || [_shadowColor isEqual:shadowColor]) return; _shadowColor = shadowColor; _innerText.shadow = [self _shadowFromProperties]; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; } } #if !TARGET_INTERFACE_BUILDER - (void)setShadowOffset:(CGSize)shadowOffset { if (CGSizeEqualToSize(_shadowOffset, shadowOffset)) return; _shadowOffset = shadowOffset; _innerText.shadow = [self _shadowFromProperties]; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; } } #else - (void)setShadowOffset:(CGPoint)shadowOffset { if (CGPointEqualToPoint(_shadowOffset, shadowOffset)) return; _shadowOffset = shadowOffset; _innerText.shadow = [self _shadowFromProperties]; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; } } #endif - (void)setShadowBlurRadius:(CGFloat)shadowBlurRadius { if (_shadowBlurRadius == shadowBlurRadius) return; _shadowBlurRadius = shadowBlurRadius; _innerText.shadow = [self _shadowFromProperties]; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; } } - (void)setTextAlignment:(NSTextAlignment)textAlignment { if (_textAlignment == textAlignment) return; _textAlignment = textAlignment; _innerText.alignment = textAlignment; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode { if (_lineBreakMode == lineBreakMode) return; _lineBreakMode = lineBreakMode; _innerText.lineBreakMode = lineBreakMode; // allow multi-line break switch (lineBreakMode) { case NSLineBreakByWordWrapping: case NSLineBreakByCharWrapping: case NSLineBreakByClipping: { _innerContainer.truncationType = YYTextTruncationTypeNone; _innerText.lineBreakMode = lineBreakMode; } break; case NSLineBreakByTruncatingHead:{ _innerContainer.truncationType = YYTextTruncationTypeStart; _innerText.lineBreakMode = NSLineBreakByWordWrapping; } break; case NSLineBreakByTruncatingTail:{ _innerContainer.truncationType = YYTextTruncationTypeEnd; _innerText.lineBreakMode = NSLineBreakByWordWrapping; } break; case NSLineBreakByTruncatingMiddle: { _innerContainer.truncationType = YYTextTruncationTypeMiddle; _innerText.lineBreakMode = NSLineBreakByWordWrapping; } break; default: break; } if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setTextVerticalAlignment:(YYTextVerticalAlignment)textVerticalAlignment { if (_textVerticalAlignment == textVerticalAlignment) return; _textVerticalAlignment = textVerticalAlignment; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setTruncationToken:(NSAttributedString *)truncationToken { if (_truncationToken == truncationToken || [_truncationToken isEqual:truncationToken]) return; _truncationToken = truncationToken.copy; _innerContainer.truncationToken = truncationToken; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setNumberOfLines:(NSUInteger)numberOfLines { if (_numberOfLines == numberOfLines) return; _numberOfLines = numberOfLines; _innerContainer.maximumNumberOfRows = numberOfLines; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setAttributedText:(NSAttributedString *)attributedText { if (attributedText.length > 0) { _innerText = attributedText.mutableCopy; switch (_lineBreakMode) { case NSLineBreakByWordWrapping: case NSLineBreakByCharWrapping: case NSLineBreakByClipping: { _innerText.lineBreakMode = _lineBreakMode; } break; case NSLineBreakByTruncatingHead: case NSLineBreakByTruncatingTail: case NSLineBreakByTruncatingMiddle: { _innerText.lineBreakMode = NSLineBreakByWordWrapping; } break; default: break; } } else { _innerText = [NSMutableAttributedString new]; } [_textParser parseText:_innerText selectedRange:NULL]; if (!_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _updateOuterTextProperties]; [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setTextContainerPath:(UIBezierPath *)textContainerPath { if (_textContainerPath == textContainerPath || [_textContainerPath isEqual:textContainerPath]) return; _textContainerPath = textContainerPath.copy; _innerContainer.path = textContainerPath; if (!_textContainerPath) { _innerContainer.size = self.bounds.size; _innerContainer.insets = _textContainerInset; } if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setExclusionPaths:(NSArray *)exclusionPaths { if (_exclusionPaths == exclusionPaths || [_exclusionPaths isEqual:exclusionPaths]) return; _exclusionPaths = exclusionPaths.copy; _innerContainer.exclusionPaths = exclusionPaths; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setTextContainerInset:(UIEdgeInsets)textContainerInset { if (UIEdgeInsetsEqualToEdgeInsets(_textContainerInset, textContainerInset)) return; _textContainerInset = textContainerInset; _innerContainer.insets = textContainerInset; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setVerticalForm:(BOOL)verticalForm { if (_verticalForm == verticalForm) return; _verticalForm = verticalForm; _innerContainer.verticalForm = verticalForm; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setLinePositionModifier:(id<YYTextLinePositionModifier>)linePositionModifier { if (_linePositionModifier == linePositionModifier) return; _linePositionModifier = linePositionModifier; _innerContainer.linePositionModifier = linePositionModifier; if (_innerText.length && !_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } - (void)setTextParser:(id<YYTextParser>)textParser { if (_textParser == textParser || [_textParser isEqual:textParser]) return; _textParser = textParser; if ([_textParser parseText:_innerText selectedRange:NULL]) { [self _updateOuterTextProperties]; if (!_ignoreCommonProperties) { if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } [self _setLayoutNeedUpdate]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } } } - (void)setTextLayout:(YYTextLayout *)textLayout { _innerLayout = textLayout; _shrinkInnerLayout = nil; if (_ignoreCommonProperties) { _innerText = (NSMutableAttributedString *)textLayout.text; _innerContainer = textLayout.container.copy; } else { _innerText = textLayout.text.mutableCopy; if (!_innerText) { _innerText = [NSMutableAttributedString new]; } [self _updateOuterTextProperties]; _innerContainer = textLayout.container.copy; if (!_innerContainer) { _innerContainer = [YYTextContainer new]; _innerContainer.size = self.bounds.size; _innerContainer.insets = self.textContainerInset; } [self _updateOuterContainerProperties]; } if (_displaysAsynchronously && _clearContentsBeforeAsynchronouslyDisplay) { [self _clearContents]; } _state.layoutNeedUpdate = NO; [self _setLayoutNeedRedraw]; [self _endTouch]; [self invalidateIntrinsicContentSize]; } - (YYTextLayout *)textLayout { [self _updateIfNeeded]; return _innerLayout; } - (void)setDisplaysAsynchronously:(BOOL)displaysAsynchronously { _displaysAsynchronously = displaysAsynchronously; ((YYAsyncLayer *)self.layer).displaysAsynchronously = displaysAsynchronously; } #pragma mark - AutoLayout - (void)setPreferredMaxLayoutWidth:(CGFloat)preferredMaxLayoutWidth { if (_preferredMaxLayoutWidth == preferredMaxLayoutWidth) return; _preferredMaxLayoutWidth = preferredMaxLayoutWidth; [self invalidateIntrinsicContentSize]; } - (CGSize)intrinsicContentSize { if (_preferredMaxLayoutWidth == 0) { YYTextContainer *container = [_innerContainer copy]; container.size = YYTextContainerMaxSize; YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:_innerText]; return layout.textBoundingSize; } CGSize containerSize = _innerContainer.size; if (!_verticalForm) { containerSize.height = YYTextContainerMaxSize.height; containerSize.width = _preferredMaxLayoutWidth; if (containerSize.width == 0) containerSize.width = self.bounds.size.width; } else { containerSize.width = YYTextContainerMaxSize.width; containerSize.height = _preferredMaxLayoutWidth; if (containerSize.height == 0) containerSize.height = self.bounds.size.height; } YYTextContainer *container = [_innerContainer copy]; container.size = containerSize; YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:_innerText]; return layout.textBoundingSize; } #pragma mark - YYTextDebugTarget - (void)setDebugOption:(YYTextDebugOption *)debugOption { BOOL needDraw = _debugOption.needDrawDebug; _debugOption = debugOption.copy; if (_debugOption.needDrawDebug != needDraw) { [self _setLayoutNeedRedraw]; } } #pragma mark - YYAsyncLayerDelegate - (YYAsyncLayerDisplayTask *)newAsyncDisplayTask { // capture current context BOOL contentsNeedFade = _state.contentsNeedFade; NSAttributedString *text = _innerText; YYTextContainer *container = _innerContainer; YYTextVerticalAlignment verticalAlignment = _textVerticalAlignment; YYTextDebugOption *debug = _debugOption; NSMutableArray *attachmentViews = _attachmentViews; NSMutableArray *attachmentLayers = _attachmentLayers; BOOL layoutNeedUpdate = _state.layoutNeedUpdate; BOOL fadeForAsync = _displaysAsynchronously && _fadeOnAsynchronouslyDisplay; __block YYTextLayout *layout = (_state.showingHighlight && _highlightLayout) ? self._highlightLayout : self._innerLayout; __block YYTextLayout *shrinkLayout = nil; __block BOOL layoutUpdated = NO; if (layoutNeedUpdate) { text = text.copy; container = container.copy; } // create display task YYAsyncLayerDisplayTask *task = [YYAsyncLayerDisplayTask new]; task.willDisplay = ^(CALayer *layer) { [layer removeAnimationForKey:@"contents"]; // If the attachment is not in new layout, or we don't know the new layout currently, // the attachment should be removed. for (UIView *view in attachmentViews) { if (layoutNeedUpdate || ![layout.attachmentContentsSet containsObject:view]) { if (view.superview == self) { [view removeFromSuperview]; } } } for (CALayer *layer in attachmentLayers) { if (layoutNeedUpdate || ![layout.attachmentContentsSet containsObject:layer]) { if (layer.superlayer == self.layer) { [layer removeFromSuperlayer]; } } } [attachmentViews removeAllObjects]; [attachmentLayers removeAllObjects]; }; task.display = ^(CGContextRef context, CGSize size, BOOL (^isCancelled)(void)) { if (isCancelled()) return; if (text.length == 0) return; YYTextLayout *drawLayout = layout; if (layoutNeedUpdate) { layout = [YYTextLayout layoutWithContainer:container text:text]; shrinkLayout = [YYLabel _shrinkLayoutWithLayout:layout]; if (isCancelled()) return; layoutUpdated = YES; drawLayout = shrinkLayout ? shrinkLayout : layout; } CGSize boundingSize = drawLayout.textBoundingSize; CGPoint point = CGPointZero; if (verticalAlignment == YYTextVerticalAlignmentCenter) { if (drawLayout.container.isVerticalForm) { point.x = -(size.width - boundingSize.width) * 0.5; } else { point.y = (size.height - boundingSize.height) * 0.5; } } else if (verticalAlignment == YYTextVerticalAlignmentBottom) { if (drawLayout.container.isVerticalForm) { point.x = -(size.width - boundingSize.width); } else { point.y = (size.height - boundingSize.height); } } point = CGPointPixelRound(point); [drawLayout drawInContext:context size:size point:point view:nil layer:nil debug:debug cancel:isCancelled]; }; task.didDisplay = ^(CALayer *layer, BOOL finished) { YYTextLayout *drawLayout = layout; if (layoutUpdated && shrinkLayout) { drawLayout = shrinkLayout; } if (!finished) { // If the display task is cancelled, we should clear the attachments. for (YYTextAttachment *a in drawLayout.attachments) { if ([a.content isKindOfClass:[UIView class]]) { if (((UIView *)a.content).superview == layer.delegate) { [((UIView *)a.content) removeFromSuperview]; } } else if ([a.content isKindOfClass:[CALayer class]]) { if (((CALayer *)a.content).superlayer == layer) { [((CALayer *)a.content) removeFromSuperlayer]; } } } return; } [layer removeAnimationForKey:@"contents"]; __strong YYLabel *view = (YYLabel *)layer.delegate; if (!view) return; if (view->_state.layoutNeedUpdate && layoutUpdated) { view->_innerLayout = layout; view->_shrinkInnerLayout = shrinkLayout; view->_state.layoutNeedUpdate = NO; } CGSize size = layer.bounds.size; CGSize boundingSize = drawLayout.textBoundingSize; CGPoint point = CGPointZero; if (verticalAlignment == YYTextVerticalAlignmentCenter) { if (drawLayout.container.isVerticalForm) { point.x = -(size.width - boundingSize.width) * 0.5; } else { point.y = (size.height - boundingSize.height) * 0.5; } } else if (verticalAlignment == YYTextVerticalAlignmentBottom) { if (drawLayout.container.isVerticalForm) { point.x = -(size.width - boundingSize.width); } else { point.y = (size.height - boundingSize.height); } } point = CGPointPixelRound(point); [drawLayout drawInContext:nil size:size point:point view:view layer:layer debug:nil cancel:NULL]; for (YYTextAttachment *a in drawLayout.attachments) { if ([a.content isKindOfClass:[UIView class]]) [attachmentViews addObject:a.content]; else if ([a.content isKindOfClass:[CALayer class]]) [attachmentLayers addObject:a.content]; } if (contentsNeedFade) { CATransition *transition = [CATransition animation]; transition.duration = kHighlightFadeDuration; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; transition.type = kCATransitionFade; [layer addAnimation:transition forKey:@"contents"]; } else if (fadeForAsync) { CATransition *transition = [CATransition animation]; transition.duration = kAsyncFadeDuration; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; transition.type = kCATransitionFade; [layer addAnimation:transition forKey:@"contents"]; } }; return task; } @end @interface YYLabel(IBInspectableProperties) @end @implementation YYLabel (IBInspectableProperties) - (BOOL)fontIsBold_:(UIFont *)font { if (![font respondsToSelector:@selector(fontDescriptor)]) return NO; return (font.fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold) > 0; } - (UIFont *)boldFont_:(UIFont *)font { if (![font respondsToSelector:@selector(fontDescriptor)]) return font; return [UIFont fontWithDescriptor:[font.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:font.pointSize]; } - (UIFont *)normalFont_:(UIFont *)font { if (![font respondsToSelector:@selector(fontDescriptor)]) return font; return [UIFont fontWithDescriptor:[font.fontDescriptor fontDescriptorWithSymbolicTraits:0] size:font.pointSize]; } - (void)setFontName_:(NSString *)fontName { if (!fontName) return; UIFont *font = self.font; if ((fontName.length == 0 || [fontName.lowercaseString isEqualToString:@"system"]) && ![self fontIsBold_:font]) { font = [UIFont systemFontOfSize:font.pointSize]; } else if ([fontName.lowercaseString isEqualToString:@"system bold"]) { font = [UIFont boldSystemFontOfSize:font.pointSize]; } else { if ([self fontIsBold_:font] && ![fontName.lowercaseString containsString:@"bold"]) { font = [UIFont fontWithName:fontName size:font.pointSize]; font = [self boldFont_:font]; } else { font = [UIFont fontWithName:fontName size:font.pointSize]; } } if (font) self.font = font; } - (void)setFontSize_:(CGFloat)fontSize { if (fontSize <= 0) return; UIFont *font = self.font; font = [font fontWithSize:fontSize]; if (font) self.font = font; } - (void)setFontIsBold_:(BOOL)fontBold { UIFont *font = self.font; if ([self fontIsBold_:font] == fontBold) return; if (fontBold) { font = [self boldFont_:font]; } else { font = [self normalFont_:font]; } if (font) self.font = font; } - (void)setInsetTop_:(CGFloat)textInsetTop { UIEdgeInsets insets = self.textContainerInset; insets.top = textInsetTop; self.textContainerInset = insets; } - (void)setInsetBottom_:(CGFloat)textInsetBottom { UIEdgeInsets insets = self.textContainerInset; insets.bottom = textInsetBottom; self.textContainerInset = insets; } - (void)setInsetLeft_:(CGFloat)textInsetLeft { UIEdgeInsets insets = self.textContainerInset; insets.left = textInsetLeft; self.textContainerInset = insets; } - (void)setInsetRight_:(CGFloat)textInsetRight { UIEdgeInsets insets = self.textContainerInset; insets.right = textInsetRight; self.textContainerInset = insets; } - (void)setDebugEnabled_:(BOOL)enabled { if (!enabled) { self.debugOption = nil; } else { YYTextDebugOption *debugOption = [YYTextDebugOption new]; debugOption.baselineColor = [UIColor redColor]; debugOption.CTFrameBorderColor = [UIColor redColor]; debugOption.CTLineFillColor = [UIColor colorWithRed:0.000 green:0.463 blue:1.000 alpha:0.180]; debugOption.CGGlyphBorderColor = [UIColor colorWithRed:1.000 green:0.524 blue:0.000 alpha:0.200]; self.debugOption = debugOption; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/YYLabel.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
10,634
```objective-c // // YYLabel.h // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextParser.h> #import <YYKit/YYTextLayout.h> #import <YYKit/YYTextAttribute.h> #else #import "YYTextParser.h" #import "YYTextLayout.h" #import "YYTextAttribute.h" #endif NS_ASSUME_NONNULL_BEGIN #if !TARGET_INTERFACE_BUILDER /** The YYLabel class implements a read-only text view. @discussion The API and behavior is similar to UILabel, but provides more features: * It supports asynchronous layout and rendering (to avoid blocking UI thread). * It extends the CoreText attributes to support more text effects. * It allows to add UIImage, UIView and CALayer as text attachments. * It allows to add 'highlight' link to some range of text to allow user interact with. * It allows to add container path and exclusion paths to control text container's shape. * It supports vertical form layout to display CJK text. See NSAttributedString+YYText.h for more convenience methods to set the attributes. See YYTextAttribute.h and YYTextLayout.h for more information. */ @interface YYLabel : UIView <NSCoding> #pragma mark - Accessing the Text Attributes ///============================================================================= /// @name Accessing the Text Attributes ///============================================================================= /** The text displayed by the label. Default is nil. Set a new value to this property also replaces the text in `attributedText`. Get the value returns the plain text in `attributedText`. */ @property (nullable, nonatomic, copy) NSString *text; /** The font of the text. Default is 17-point system font. Set a new value to this property also causes the new font to be applied to the entire `attributedText`. Get the value returns the font at the head of `attributedText`. */ @property (null_resettable, nonatomic, strong) UIFont *font; /** The color of the text. Default is black. Set a new value to this property also causes the new color to be applied to the entire `attributedText`. Get the value returns the color at the head of `attributedText`. */ @property (null_resettable, nonatomic, strong) UIColor *textColor; /** The shadow color of the text. Default is nil. Set a new value to this property also causes the shadow color to be applied to the entire `attributedText`. Get the value returns the shadow color at the head of `attributedText`. */ @property (nullable, nonatomic, strong) UIColor *shadowColor; /** The shadow offset of the text. Default is CGSizeZero. Set a new value to this property also causes the shadow offset to be applied to the entire `attributedText`. Get the value returns the shadow offset at the head of `attributedText`. */ @property (nonatomic) CGSize shadowOffset; /** The shadow blur of the text. Default is 0. Set a new value to this property also causes the shadow blur to be applied to the entire `attributedText`. Get the value returns the shadow blur at the head of `attributedText`. */ @property (nonatomic) CGFloat shadowBlurRadius; /** The technique to use for aligning the text. Default is NSTextAlignmentNatural. Set a new value to this property also causes the new alignment to be applied to the entire `attributedText`. Get the value returns the alignment at the head of `attributedText`. */ @property (nonatomic) NSTextAlignment textAlignment; /** The text vertical aligmnent in container. Default is YYTextVerticalAlignmentCenter. */ @property (nonatomic) YYTextVerticalAlignment textVerticalAlignment; /** The styled text displayed by the label. Set a new value to this property also replaces the value of the `text`, `font`, `textColor`, `textAlignment` and other properties in label. @discussion It only support the attributes declared in CoreText and YYTextAttribute. See `NSAttributedString+YYText` for more convenience methods to set the attributes. */ @property (nullable, nonatomic, copy) NSAttributedString *attributedText; /** The technique to use for wrapping and truncating the label's text. Default is NSLineBreakByTruncatingTail. */ @property (nonatomic) NSLineBreakMode lineBreakMode; /** The truncation token string used when text is truncated. Default is nil. When the value is nil, the label use "" as default truncation token. */ @property (nullable, nonatomic, copy) NSAttributedString *truncationToken; /** The maximum number of lines to use for rendering text. Default value is 1. 0 means no limit. */ @property (nonatomic) NSUInteger numberOfLines; /** When `text` or `attributedText` is changed, the parser will be called to modify the text. It can be used to add code highlighting or emoticon replacement to text view. The default value is nil. See `YYTextParser` protocol for more information. */ @property (nullable, nonatomic, strong) id<YYTextParser> textParser; /** The current text layout in text view. It can be used to query the text layout information. Set a new value to this property also replaces most properties in this label, such as `text`, `color`, `attributedText`, `lineBreakMode`, `textContainerPath`, `exclusionPaths` and so on. */ @property (nullable, nonatomic, strong) YYTextLayout *textLayout; #pragma mark - Configuring the Text Container ///============================================================================= /// @name Configuring the Text Container ///============================================================================= /** A UIBezierPath object that specifies the shape of the text frame. Default value is nil. */ @property (nullable, nonatomic, copy) UIBezierPath *textContainerPath; /** An array of UIBezierPath objects representing the exclusion paths inside the receiver's bounding rectangle. Default value is nil. */ @property (nullable, nonatomic, copy) NSArray<UIBezierPath *> *exclusionPaths; /** The inset of the text container's layout area within the text view's content area. Default value is UIEdgeInsetsZero. */ @property (nonatomic) UIEdgeInsets textContainerInset; /** Whether the receiver's layout orientation is vertical form. Default is NO. It may used to display CJK text. */ @property (nonatomic, getter=isVerticalForm) BOOL verticalForm; /** The text line position modifier used to modify the lines' position in layout. Default value is nil. See `YYTextLinePositionModifier` protocol for more information. */ @property (nullable, nonatomic, copy) id<YYTextLinePositionModifier> linePositionModifier; /** The debug option to display CoreText layout result. The default value is [YYTextDebugOption sharedDebugOption]. */ @property (nullable, nonatomic, copy) YYTextDebugOption *debugOption; #pragma mark - Getting the Layout Constraints ///============================================================================= /// @name Getting the Layout Constraints ///============================================================================= /** The preferred maximum width (in points) for a multiline label. @discussion This property affects the size of the label when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text is flowed to one or more new lines, thereby increasing the height of the label. If the text is vertical form, this value will match to text height. */ @property (nonatomic) CGFloat preferredMaxLayoutWidth; #pragma mark - Interacting with Text Data ///============================================================================= /// @name Interacting with Text Data ///============================================================================= /** When user tap the label, this action will be called (similar to tap gesture). The default value is nil. */ @property (nullable, nonatomic, copy) YYTextAction textTapAction; /** When user long press the label, this action will be called (similar to long press gesture). The default value is nil. */ @property (nullable, nonatomic, copy) YYTextAction textLongPressAction; /** When user tap the highlight range of text, this action will be called. The default value is nil. */ @property (nullable, nonatomic, copy) YYTextAction highlightTapAction; /** When user long press the highlight range of text, this action will be called. The default value is nil. */ @property (nullable, nonatomic, copy) YYTextAction highlightLongPressAction; #pragma mark - Configuring the Display Mode ///============================================================================= /// @name Configuring the Display Mode ///============================================================================= /** A Boolean value indicating whether the layout and rendering codes are running asynchronously on background threads. The default value is `NO`. */ @property (nonatomic) BOOL displaysAsynchronously; /** If the value is YES, and the layer is rendered asynchronously, then it will set label.layer.contents to nil before display. The default value is `YES`. @discussion When the asynchronously display is enabled, the layer's content will be updated after the background render process finished. If the render process can not finished in a vsync time (1/60 second), the old content will be still kept for display. You may manually clear the content by set the layer.contents to nil after you update the label's properties, or you can just set this property to YES. */ @property (nonatomic) BOOL clearContentsBeforeAsynchronouslyDisplay; /** If the value is YES, and the layer is rendered asynchronously, then it will add a fade animation on layer when the contents of layer changed. The default value is `YES`. */ @property (nonatomic) BOOL fadeOnAsynchronouslyDisplay; /** If the value is YES, then it will add a fade animation on layer when some range of text become highlighted. The default value is `YES`. */ @property (nonatomic) BOOL fadeOnHighlight; /** Ignore common properties (such as text, font, textColor, attributedText...) and only use "textLayout" to display content. The default value is `NO`. @discussion If you control the label content only through "textLayout", then you may set this value to YES for higher performance. */ @property (nonatomic) BOOL ignoreCommonProperties; /* Tips: 1. If you only need a UILabel alternative to display rich text and receive link touch event, you do not need to adjust the display mode properties. 2. If you have performance issues, you may enable the asynchronous display mode by setting the `displaysAsynchronously` to YES. 3. If you want to get the highest performance, you should do text layout with `YYTextLayout` class in background thread. Here's an example: YYLabel *label = [YYLabel new]; label.displaysAsynchronously = YES; label.ignoreCommonProperties = YES; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Create attributed string. NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Some Text"]; text.font = [UIFont systemFontOfSize:16]; text.color = [UIColor grayColor]; [text setColor:[UIColor redColor] range:NSMakeRange(0, 4)]; // Create text container YYTextContainer *container = [YYTextContainer new]; container.size = CGSizeMake(100, CGFLOAT_MAX); container.maximumNumberOfRows = 0; // Generate a text layout. YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text]; dispatch_async(dispatch_get_main_queue(), ^{ label.size = layout.textBoundingSize; label.textLayout = layout; }); }); */ @end #else // TARGET_INTERFACE_BUILDER IB_DESIGNABLE @interface YYLabel : UIView <NSCoding> @property (nullable, nonatomic, copy) IBInspectable NSString *text; @property (null_resettable, nonatomic, strong) IBInspectable UIColor *textColor; @property (nullable, nonatomic, strong) IBInspectable NSString *fontName_; @property (nonatomic) IBInspectable CGFloat fontSize_; @property (nonatomic) IBInspectable BOOL fontIsBold_; @property (nonatomic) IBInspectable NSUInteger numberOfLines; @property (nonatomic) IBInspectable NSInteger lineBreakMode; @property (nonatomic) IBInspectable CGFloat preferredMaxLayoutWidth; @property (nonatomic, getter=isVerticalForm) IBInspectable BOOL verticalForm; @property (nonatomic) IBInspectable NSInteger textAlignment; @property (nonatomic) IBInspectable NSInteger textVerticalAlignment; @property (nullable, nonatomic, strong) IBInspectable UIColor *shadowColor; @property (nonatomic) IBInspectable CGPoint shadowOffset; @property (nonatomic) IBInspectable CGFloat shadowBlurRadius; @property (nullable, nonatomic, copy) IBInspectable NSAttributedString *attributedText; @property (nonatomic) IBInspectable CGFloat insetTop_; @property (nonatomic) IBInspectable CGFloat insetBottom_; @property (nonatomic) IBInspectable CGFloat insetLeft_; @property (nonatomic) IBInspectable CGFloat insetRight_; @property (nonatomic) IBInspectable BOOL debugEnabled_; @property (null_resettable, nonatomic, strong) UIFont *font; @property (nullable, nonatomic, copy) NSAttributedString *truncationToken; @property (nullable, nonatomic, strong) id<YYTextParser> textParser; @property (nullable, nonatomic, strong) YYTextLayout *textLayout; @property (nullable, nonatomic, copy) UIBezierPath *textContainerPath; @property (nullable, nonatomic, copy) NSArray<UIBezierPath *> *exclusionPaths; @property (nonatomic) UIEdgeInsets textContainerInset; @property (nullable, nonatomic, copy) id<YYTextLinePositionModifier> linePositionModifier; @property (nonnull, nonatomic, copy) YYTextDebugOption *debugOption; @property (nullable, nonatomic, copy) YYTextAction textTapAction; @property (nullable, nonatomic, copy) YYTextAction textLongPressAction; @property (nullable, nonatomic, copy) YYTextAction highlightTapAction; @property (nullable, nonatomic, copy) YYTextAction highlightLongPressAction; @property (nonatomic) BOOL displaysAsynchronously; @property (nonatomic) BOOL clearContentsBeforeAsynchronouslyDisplay; @property (nonatomic) BOOL fadeOnAsynchronouslyDisplay; @property (nonatomic) BOOL fadeOnHighlight; @property (nonatomic) BOOL ignoreCommonProperties; @end #endif // !TARGET_INTERFACE_BUILDER NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/YYLabel.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,964
```objective-c // // YYTextRubyAnnotation.m // YYKit <path_to_url // // Created by ibireme on 15/4/24. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextRubyAnnotation.h" @implementation YYTextRubyAnnotation - (instancetype)init { self = super.init; self.alignment = kCTRubyAlignmentAuto; self.overhang = kCTRubyOverhangAuto; self.sizeFactor = 0.5; return self; } + (instancetype)rubyWithCTRubyRef:(CTRubyAnnotationRef)ctRuby { if (!ctRuby) return nil; YYTextRubyAnnotation *one = [self new]; one.alignment = CTRubyAnnotationGetAlignment(ctRuby); one.overhang = CTRubyAnnotationGetOverhang(ctRuby); one.sizeFactor = CTRubyAnnotationGetSizeFactor(ctRuby); one.textBefore = (__bridge NSString *)(CTRubyAnnotationGetTextForPosition(ctRuby, kCTRubyPositionBefore)); one.textAfter = (__bridge NSString *)(CTRubyAnnotationGetTextForPosition(ctRuby, kCTRubyPositionAfter)); one.textInterCharacter = (__bridge NSString *)(CTRubyAnnotationGetTextForPosition(ctRuby, kCTRubyPositionInterCharacter)); one.textInline = (__bridge NSString *)(CTRubyAnnotationGetTextForPosition(ctRuby, kCTRubyPositionInline)); return one; } - (CTRubyAnnotationRef)CTRubyAnnotation CF_RETURNS_RETAINED { if (((long)CTRubyAnnotationCreate + 1) == 1) return NULL; // system not support CFStringRef text[kCTRubyPositionCount]; text[kCTRubyPositionBefore] = (__bridge CFStringRef)(_textBefore); text[kCTRubyPositionAfter] = (__bridge CFStringRef)(_textAfter); text[kCTRubyPositionInterCharacter] = (__bridge CFStringRef)(_textInterCharacter); text[kCTRubyPositionInline] = (__bridge CFStringRef)(_textInline); CTRubyAnnotationRef ruby = CTRubyAnnotationCreate(_alignment, _overhang, _sizeFactor, text); return ruby; } - (id)copyWithZone:(NSZone *)zone { YYTextRubyAnnotation *one = [self.class new]; one.alignment = _alignment; one.overhang = _overhang; one.sizeFactor = _sizeFactor; one.textBefore = _textBefore; one.textAfter = _textAfter; one.textInterCharacter = _textInterCharacter; one.textInline = _textInline; return one; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:@(_alignment) forKey:@"alignment"]; [aCoder encodeObject:@(_overhang) forKey:@"overhang"]; [aCoder encodeObject:@(_sizeFactor) forKey:@"sizeFactor"]; [aCoder encodeObject:_textBefore forKey:@"textBefore"]; [aCoder encodeObject:_textAfter forKey:@"textAfter"]; [aCoder encodeObject:_textInterCharacter forKey:@"textInterCharacter"]; [aCoder encodeObject:_textInline forKey:@"textInline"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [self init]; _alignment = ((NSNumber *)[aDecoder decodeObjectForKey:@"alignment"]).intValue; _overhang = ((NSNumber *)[aDecoder decodeObjectForKey:@"overhang"]).intValue; _sizeFactor = ((NSNumber *)[aDecoder decodeObjectForKey:@"sizeFactor"]).intValue; _textBefore = [aDecoder decodeObjectForKey:@"textBefore"]; _textAfter = [aDecoder decodeObjectForKey:@"textAfter"]; _textInterCharacter = [aDecoder decodeObjectForKey:@"textInterCharacter"]; _textInline = [aDecoder decodeObjectForKey:@"textInline"]; return self; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextRubyAnnotation.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
824
```objective-c // // YYTextView.m // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextView.h" #import "YYKitMacro.h" #import "YYTextInput.h" #import "YYTextContainerView.h" #import "YYTextSelectionView.h" #import "YYTextMagnifier.h" #import "YYTextEffectWindow.h" #import "YYTextKeyboardManager.h" #import "YYTextUtilities.h" #import "YYCGUtilities.h" #import "YYTransaction.h" #import "YYWeakProxy.h" #import "UIView+YYAdd.h" #import "NSAttributedString+YYText.h" #import "UIPasteboard+YYText.h" #import "UIDevice+YYAdd.h" #import "UIApplication+YYAdd.h" #import "YYImage.h" #define kDefaultUndoLevelMax 20 // Default maximum undo level #define kAutoScrollMinimumDuration 0.1 // Time in seconds to tick auto-scroll. #define kLongPressMinimumDuration 0.5 // Time in seconds the fingers must be held down for long press gesture. #define kLongPressAllowableMovement 10.0 // Maximum movement in points allowed before the long press fails. #define kMagnifierRangedTrackFix -6.0 // Magnifier ranged offset fix. #define kMagnifierRangedPopoverOffset 4.0 // Magnifier ranged popover offset. #define kMagnifierRangedCaptureOffset -6.0 // Magnifier ranged capture center offset. #define kHighlightFadeDuration 0.15 // Time in seconds for highlight fadeout animation. #define kDefaultInset UIEdgeInsetsMake(6, 4, 6, 4) #define kDefaultVerticalInset UIEdgeInsetsMake(4, 6, 4, 6) NSString *const YYTextViewTextDidBeginEditingNotification = @"YYTextViewTextDidBeginEditing"; NSString *const YYTextViewTextDidChangeNotification = @"YYTextViewTextDidChange"; NSString *const YYTextViewTextDidEndEditingNotification = @"YYTextViewTextDidEndEditing"; typedef NS_ENUM (NSUInteger, YYTextGrabberDirection) { kStart = 1, kEnd = 2, }; typedef NS_ENUM(NSUInteger, YYTextMoveDirection) { kLeft = 1, kTop = 2, kRight = 3, kBottom = 4, }; /// An object that captures the state of the text view. Used for undo and redo. @interface _YYTextViewUndoObject : NSObject @property (nonatomic, strong) NSAttributedString *text; @property (nonatomic, assign) NSRange selectedRange; @end @implementation _YYTextViewUndoObject + (instancetype)objectWithText:(NSAttributedString *)text range:(NSRange)range { _YYTextViewUndoObject *obj = [self new]; obj.text = text ? text : [NSAttributedString new]; obj.selectedRange = range; return obj; } @end @interface YYTextView () <UIScrollViewDelegate, UIAlertViewDelegate, YYTextDebugTarget, YYTextKeyboardObserver> { YYTextRange *_selectedTextRange; /// nonnull YYTextRange *_markedTextRange; __weak id<YYTextViewDelegate> _outerDelegate; UIImageView *_placeHolderView; NSMutableAttributedString *_innerText; ///< nonnull, inner attributed text NSMutableAttributedString *_delectedText; ///< detected text for display YYTextContainer *_innerContainer; ///< nonnull, inner text container YYTextLayout *_innerLayout; ///< inner text layout, the text in this layout is longer than `_innerText` by appending '\n' YYTextContainerView *_containerView; ///< nonnull YYTextSelectionView *_selectionView; ///< nonnull YYTextMagnifier *_magnifierCaret; ///< nonnull YYTextMagnifier *_magnifierRanged; ///< nonnull NSMutableAttributedString *_typingAttributesHolder; ///< nonnull, typing attributes NSDataDetector *_dataDetector; CGFloat _magnifierRangedOffset; NSRange _highlightRange; ///< current highlight range YYTextHighlight *_highlight; ///< highlight attribute in `_highlightRange` YYTextLayout *_highlightLayout; ///< when _state.showingHighlight=YES, this layout should be displayed YYTextRange *_trackingRange; ///< the range in _innerLayout, may out of _innerText. BOOL _insetModifiedByKeyboard; ///< text is covered by keyboard, and the contentInset is modified UIEdgeInsets _originalContentInset; ///< the original contentInset before modified UIEdgeInsets _originalScrollIndicatorInsets; ///< the original scrollIndicatorInsets before modified NSTimer *_longPressTimer; NSTimer *_autoScrollTimer; CGFloat _autoScrollOffset; ///< current auto scroll offset which shoud add to scroll view NSInteger _autoScrollAcceleration; ///< an acceleration coefficient for auto scroll NSTimer *_selectionDotFixTimer; ///< fix the selection dot in window if the view is moved by parents CGPoint _previousOriginInWindow; CGPoint _touchBeganPoint; CGPoint _trackingPoint; NSTimeInterval _touchBeganTime; NSTimeInterval _trackingTime; NSMutableArray *_undoStack; NSMutableArray *_redoStack; NSRange _lastTypeRange; struct { unsigned int trackingGrabber : 2; ///< YYTextGrabberDirection, current tracking grabber unsigned int trackingCaret : 1; ///< track the caret unsigned int trackingPreSelect : 1; ///< track pre-select unsigned int trackingTouch : 1; ///< is in touch phase unsigned int swallowTouch : 1; ///< don't forward event to next responder unsigned int touchMoved : 3; ///< YYTextMoveDirection, move direction after touch began unsigned int selectedWithoutEdit : 1; ///< show selected range but not first responder unsigned int deleteConfirm : 1; ///< delete a binding text range unsigned int ignoreFirstResponder : 1; ///< ignore become first responder temporary unsigned int ignoreTouchBegan : 1; ///< ignore begin tracking touch temporary unsigned int showingMagnifierCaret : 1; unsigned int showingMagnifierRanged : 1; unsigned int showingMenu : 1; unsigned int showingHighlight : 1; unsigned int typingAttributesOnce : 1; ///< apply the typing attributes once unsigned int clearsOnInsertionOnce : 1; ///< select all once when become first responder unsigned int autoScrollTicked : 1; ///< auto scroll did tick scroll at this timer period unsigned int firstShowDot : 1; ///< the selection grabber dot has displayed at least once unsigned int needUpdate : 1; ///< the layout or selection view is 'dirty' and need update unsigned int placeholderNeedUpdate : 1; ///< the placeholder need update it's contents unsigned int insideUndoBlock : 1; unsigned int firstResponderBeforeUndoAlert : 1; } _state; } @end @implementation YYTextView #pragma mark - @protocol UITextInputTraits @synthesize autocapitalizationType = _autocapitalizationType; @synthesize autocorrectionType = _autocorrectionType; @synthesize spellCheckingType = _spellCheckingType; @synthesize keyboardType = _keyboardType; @synthesize keyboardAppearance = _keyboardAppearance; @synthesize returnKeyType = _returnKeyType; @synthesize enablesReturnKeyAutomatically = _enablesReturnKeyAutomatically; @synthesize secureTextEntry = _secureTextEntry; #pragma mark - @protocol UITextInput @synthesize selectedTextRange = _selectedTextRange; //copy nonnull (YYTextRange*) @synthesize markedTextRange = _markedTextRange; //readonly (YYTextRange*) @synthesize markedTextStyle = _markedTextStyle; //copy @synthesize inputDelegate = _inputDelegate; //assign @synthesize tokenizer = _tokenizer; //readonly #pragma mark - @protocol UITextInput optional @synthesize selectionAffinity = _selectionAffinity; #pragma mark - Private /// Update layout and selection before runloop sleep/end. - (void)_commitUpdate { #if !TARGET_INTERFACE_BUILDER _state.needUpdate = YES; [[YYTransaction transactionWithTarget:self selector:@selector(_updateIfNeeded)] commit]; #else [self _update]; #endif } /// Update layout and selection view if needed. - (void)_updateIfNeeded { if (_state.needUpdate) { [self _update]; } } /// Update layout and selection view immediately. - (void)_update { _state.needUpdate = NO; [self _updateLayout]; [self _updateSelectionView]; } /// Update layout immediately. - (void)_updateLayout { NSMutableAttributedString *text = _innerText.mutableCopy; _placeHolderView.hidden = text.length > 0; if ([self _detectText:text]) { _delectedText = text; } else { _delectedText = nil; } [text replaceCharactersInRange:NSMakeRange(text.length, 0) withString:@"\r"]; // add for nextline caret [text removeDiscontinuousAttributesInRange:NSMakeRange(_innerText.length, 1)]; [text removeAttribute:YYTextBorderAttributeName range:NSMakeRange(_innerText.length, 1)]; [text removeAttribute:YYTextBackgroundBorderAttributeName range:NSMakeRange(_innerText.length, 1)]; if (_innerText.length == 0) { [text setAttributes:_typingAttributesHolder.attributes]; // add for empty text caret } if (_selectedTextRange.end.offset == _innerText.length) { [_typingAttributesHolder.attributes enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) { [text setAttribute:key value:value range:NSMakeRange(_innerText.length, 1)]; }]; } [self willChangeValueForKey:@"textLayout"]; _innerLayout = [YYTextLayout layoutWithContainer:_innerContainer text:text]; [self didChangeValueForKey:@"textLayout"]; CGSize size = [_innerLayout textBoundingSize]; CGSize visibleSize = [self _getVisibleSize]; if (_innerContainer.isVerticalForm) { size.height = visibleSize.height; if (size.width < visibleSize.width) size.width = visibleSize.width; } else { size.width = visibleSize.width; } [_containerView setLayout:_innerLayout withFadeDuration:0]; _containerView.frame = (CGRect){.size = size}; _state.showingHighlight = NO; self.contentSize = size; } /// Update selection view immediately. /// This method should be called after "layout update" finished. - (void)_updateSelectionView { _selectionView.frame = _containerView.frame; _selectionView.caretBlinks = NO; _selectionView.caretVisible = NO; _selectionView.selectionRects = nil; [[YYTextEffectWindow sharedWindow] hideSelectionDot:_selectionView]; if (!_innerLayout) return; NSMutableArray *allRects = [NSMutableArray new]; BOOL containsDot = NO; YYTextRange *selectedRange = _selectedTextRange; if (_state.trackingTouch && _trackingRange) { selectedRange = _trackingRange; } if (_markedTextRange) { NSArray *rects = [_innerLayout selectionRectsWithoutStartAndEndForRange:_markedTextRange]; if (rects) [allRects addObjectsFromArray:rects]; if (selectedRange.asRange.length > 0) { rects = [_innerLayout selectionRectsWithOnlyStartAndEndForRange:selectedRange]; if (rects) [allRects addObjectsFromArray:rects]; containsDot = rects.count > 0; } else { CGRect rect = [_innerLayout caretRectForPosition:selectedRange.end]; _selectionView.caretRect = [self _convertRectFromLayout:rect]; _selectionView.caretVisible = YES; _selectionView.caretBlinks = YES; } } else { if (selectedRange.asRange.length == 0) { // only caret if (self.isFirstResponder || _state.trackingPreSelect) { CGRect rect = [_innerLayout caretRectForPosition:selectedRange.end]; _selectionView.caretRect = [self _convertRectFromLayout:rect]; _selectionView.caretVisible = YES; if (!_state.trackingCaret && !_state.trackingPreSelect) { _selectionView.caretBlinks = YES; } } } else { // range selected if ((self.isFirstResponder && !_state.deleteConfirm) || (!self.isFirstResponder && _state.selectedWithoutEdit)) { NSArray *rects = [_innerLayout selectionRectsForRange:selectedRange]; if (rects) [allRects addObjectsFromArray:rects]; containsDot = rects.count > 0; } else if ((!self.isFirstResponder && _state.trackingPreSelect) || (self.isFirstResponder && _state.deleteConfirm)){ NSArray *rects = [_innerLayout selectionRectsWithoutStartAndEndForRange:selectedRange]; if (rects) [allRects addObjectsFromArray:rects]; } } } [allRects enumerateObjectsUsingBlock:^(YYTextSelectionRect *rect, NSUInteger idx, BOOL *stop) { rect.rect = [self _convertRectFromLayout:rect.rect]; }]; _selectionView.selectionRects = allRects; if (!_state.firstShowDot && containsDot) { _state.firstShowDot = YES; /* The dot position may be wrong at the first time displayed. I can't find the reason. Here's a workaround. */ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [[YYTextEffectWindow sharedWindow] showSelectionDot:_selectionView]; }); } [[YYTextEffectWindow sharedWindow] showSelectionDot:_selectionView]; if (containsDot) { [self _startSelectionDotFixTimer]; } else { [self _endSelectionDotFixTimer]; } } /// Update inner contains's size. - (void)_updateInnerContainerSize { CGSize size = [self _getVisibleSize]; if (_innerContainer.isVerticalForm) size.width = CGFLOAT_MAX; else size.height = CGFLOAT_MAX; _innerContainer.size = size; } /// Update placeholder before runloop sleep/end. - (void)_commitPlaceholderUpdate { #if !TARGET_INTERFACE_BUILDER _state.placeholderNeedUpdate = YES; [[YYTransaction transactionWithTarget:self selector:@selector(_updatePlaceholderIfNeeded)] commit]; #else [self _updatePlaceholder]; #endif } /// Update placeholder if needed. - (void)_updatePlaceholderIfNeeded { if (_state.placeholderNeedUpdate) { _state.placeholderNeedUpdate = NO; [self _updatePlaceholder]; } } /// Update placeholder immediately. - (void)_updatePlaceholder { CGRect frame = CGRectZero; _placeHolderView.image = nil; _placeHolderView.frame = frame; if (_placeholderAttributedText.length > 0) { YYTextContainer *container = _innerContainer.copy; container.size = self.bounds.size; container.truncationType = YYTextTruncationTypeEnd; container.truncationToken = nil; YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:_placeholderAttributedText]; CGSize size = [layout textBoundingSize]; BOOL needDraw = size.width > 1 && size.height > 1; if (needDraw) { UIGraphicsBeginImageContextWithOptions(size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); [layout drawInContext:context size:size debug:self.debugOption]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); _placeHolderView.image = image; frame.size = image.size; if (container.isVerticalForm) { frame.origin.x = self.bounds.size.width - image.size.width; } else { frame.origin = CGPointZero; } _placeHolderView.frame = frame; } } } /// Update the `_selectedTextRange` to a single position by `_trackingPoint`. - (void)_updateTextRangeByTrackingCaret { if (!_state.trackingTouch) return; CGPoint trackingPoint = [self _convertPointToLayout:_trackingPoint]; YYTextPosition *newPos = [_innerLayout closestPositionToPoint:trackingPoint]; if (newPos) { newPos = [self _correctedTextPosition:newPos]; if (_markedTextRange) { if ([newPos compare:_markedTextRange.start] == NSOrderedAscending) { newPos = _markedTextRange.start; } else if ([newPos compare:_markedTextRange.end] == NSOrderedDescending) { newPos = _markedTextRange.end; } } YYTextRange *newRange = [YYTextRange rangeWithRange:NSMakeRange(newPos.offset, 0) affinity:newPos.affinity]; _trackingRange = newRange; } } /// Update the `_selectedTextRange` to a new range by `_trackingPoint` and `_state.trackingGrabber`. - (void)_updateTextRangeByTrackingGrabber { if (!_state.trackingTouch || !_state.trackingGrabber) return; BOOL isStart = _state.trackingGrabber == kStart; CGPoint magPoint = _trackingPoint; magPoint.y += kMagnifierRangedTrackFix; magPoint = [self _convertPointToLayout:magPoint]; YYTextPosition *position = [_innerLayout positionForPoint:magPoint oldPosition:(isStart ? _selectedTextRange.start : _selectedTextRange.end) otherPosition:(isStart ? _selectedTextRange.end : _selectedTextRange.start)]; if (position) { position = [self _correctedTextPosition:position]; if ((NSUInteger)position.offset > _innerText.length) { position = [YYTextPosition positionWithOffset:_innerText.length]; } YYTextRange *newRange = [YYTextRange rangeWithStart:(isStart ? position : _selectedTextRange.start) end:(isStart ? _selectedTextRange.end : position)]; _trackingRange = newRange; } } /// Update the `_selectedTextRange` to a new range/position by `_trackingPoint`. - (void)_updateTextRangeByTrackingPreSelect { if (!_state.trackingTouch) return; YYTextRange *newRange = [self _getClosestTokenRangeAtPoint:_trackingPoint]; _trackingRange = newRange; } /// Show or update `_magnifierCaret` based on `_trackingPoint`, and hide `_magnifierRange`. - (void)_showMagnifierCaret { if ([UIApplication isAppExtension]) return; if (_state.showingMagnifierRanged) { _state.showingMagnifierRanged = NO; [[YYTextEffectWindow sharedWindow] hideMagnifier:_magnifierRanged]; } _magnifierCaret.hostPopoverCenter = _trackingPoint; _magnifierCaret.hostCaptureCenter = _trackingPoint; if (!_state.showingMagnifierCaret) { _state.showingMagnifierCaret = YES; [[YYTextEffectWindow sharedWindow] showMagnifier:_magnifierCaret]; } else { [[YYTextEffectWindow sharedWindow] moveMagnifier:_magnifierCaret]; } } /// Show or update `_magnifierRanged` based on `_trackingPoint`, and hide `_magnifierCaret`. - (void)_showMagnifierRanged { if ([UIApplication isAppExtension]) return; if (_verticalForm) { // hack for vertical form... [self _showMagnifierCaret]; return; } if (_state.showingMagnifierCaret) { _state.showingMagnifierCaret = NO; [[YYTextEffectWindow sharedWindow] hideMagnifier:_magnifierCaret]; } CGPoint magPoint = _trackingPoint; if (_verticalForm) { magPoint.x += kMagnifierRangedTrackFix; } else { magPoint.y += kMagnifierRangedTrackFix; } YYTextRange *selectedRange = _selectedTextRange; if (_state.trackingTouch && _trackingRange) { selectedRange = _trackingRange; } YYTextPosition *position; if (_markedTextRange) { position = selectedRange.end; } else { position = [_innerLayout positionForPoint:[self _convertPointToLayout:magPoint] oldPosition:(_state.trackingGrabber == kStart ? selectedRange.start : selectedRange.end) otherPosition:(_state.trackingGrabber == kStart ? selectedRange.end : selectedRange.start)]; } NSUInteger lineIndex = [_innerLayout lineIndexForPosition:position]; if (lineIndex < _innerLayout.lines.count) { YYTextLine *line = _innerLayout.lines[lineIndex]; CGRect lineRect = [self _convertRectFromLayout:line.bounds]; if (_verticalForm) { magPoint.x = YY_CLAMP(magPoint.x, CGRectGetMinX(lineRect), CGRectGetMaxX(lineRect)); } else { magPoint.y = YY_CLAMP(magPoint.y, CGRectGetMinY(lineRect), CGRectGetMaxY(lineRect)); } CGPoint linePoint = [_innerLayout linePositionForPosition:position]; linePoint = [self _convertPointFromLayout:linePoint]; CGPoint popoverPoint = linePoint; if (_verticalForm) { popoverPoint.x = linePoint.x + _magnifierRangedOffset; } else { popoverPoint.y = linePoint.y + _magnifierRangedOffset; } CGPoint capturePoint; if (_verticalForm) { capturePoint.x = linePoint.x + kMagnifierRangedCaptureOffset; capturePoint.y = linePoint.y; } else { capturePoint.x = linePoint.x; capturePoint.y = linePoint.y + kMagnifierRangedCaptureOffset; } _magnifierRanged.hostPopoverCenter = popoverPoint; _magnifierRanged.hostCaptureCenter = capturePoint; if (!_state.showingMagnifierRanged) { _state.showingMagnifierRanged = YES; [[YYTextEffectWindow sharedWindow] showMagnifier:_magnifierRanged]; } else { [[YYTextEffectWindow sharedWindow] moveMagnifier:_magnifierRanged]; } } } /// Update the showing magnifier. - (void)_updateMagnifier { if ([UIApplication isAppExtension]) return; if (_state.showingMagnifierCaret) { [[YYTextEffectWindow sharedWindow] moveMagnifier:_magnifierCaret]; } if (_state.showingMagnifierRanged) { [[YYTextEffectWindow sharedWindow] moveMagnifier:_magnifierRanged]; } } /// Hide the `_magnifierCaret` and `_magnifierRanged`. - (void)_hideMagnifier { if ([UIApplication isAppExtension]) return; if (_state.showingMagnifierCaret || _state.showingMagnifierRanged) { // disable touch began temporary to ignore caret animation overlap _state.ignoreTouchBegan = YES; __weak typeof(self) _self = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ __strong typeof(_self) self = _self; if (self) self->_state.ignoreTouchBegan = NO; }); } if (_state.showingMagnifierCaret) { _state.showingMagnifierCaret = NO; [[YYTextEffectWindow sharedWindow] hideMagnifier:_magnifierCaret]; } if (_state.showingMagnifierRanged) { _state.showingMagnifierRanged = NO; [[YYTextEffectWindow sharedWindow] hideMagnifier:_magnifierRanged]; } } /// Show and update the UIMenuController. - (void)_showMenu { CGRect rect; if (_selectionView.caretVisible) { rect = _selectionView.caretView.frame; } else if (_selectionView.selectionRects.count > 0) { YYTextSelectionRect *sRect = _selectionView.selectionRects.firstObject; rect = sRect.rect; for (NSUInteger i = 1; i < _selectionView.selectionRects.count; i++) { sRect = _selectionView.selectionRects[i]; rect = CGRectUnion(rect, sRect.rect); } CGRect inter = CGRectIntersection(rect, self.bounds); if (!CGRectIsNull(inter) && inter.size.height > 1) { rect = inter; //clip to bounds } else { if (CGRectGetMinY(rect) < CGRectGetMinY(self.bounds)) { rect.size.height = 1; rect.origin.y = CGRectGetMinY(self.bounds); } else { rect.size.height = 1; rect.origin.y = CGRectGetMaxY(self.bounds); } } YYTextKeyboardManager *mgr = [YYTextKeyboardManager defaultManager]; if (mgr.keyboardVisible) { CGRect kbRect = [mgr convertRect:mgr.keyboardFrame toView:self]; CGRect kbInter = CGRectIntersection(rect, kbRect); if (!CGRectIsNull(kbInter) && kbInter.size.height > 1 && kbInter.size.width > 1) { // self is covered by keyboard if (CGRectGetMinY(kbInter) > CGRectGetMinY(rect)) { // keyboard at bottom rect.size.height -= kbInter.size.height; } else if (CGRectGetMaxY(kbInter) < CGRectGetMaxY(rect)) { // keyboard at top rect.origin.y += kbInter.size.height; rect.size.height -= kbInter.size.height; } } } } else { rect = _selectionView.bounds; } if (!self.isFirstResponder) { if (!_containerView.isFirstResponder) { [_containerView becomeFirstResponder]; } } if (self.isFirstResponder || _containerView.isFirstResponder) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ UIMenuController *menu = [UIMenuController sharedMenuController]; [menu setTargetRect:CGRectStandardize(rect) inView:_selectionView]; [menu update]; if (!_state.showingMenu || !menu.menuVisible) { _state.showingMenu = YES; [menu setMenuVisible:YES animated:YES]; } }); } } /// Hide the UIMenuController. - (void)_hideMenu { if (_state.showingMenu) { _state.showingMenu = NO; UIMenuController *menu = [UIMenuController sharedMenuController]; [menu setMenuVisible:NO animated:YES]; } if (_containerView.isFirstResponder) { _state.ignoreFirstResponder = YES; [_containerView resignFirstResponder]; // it will call [self becomeFirstResponder], ignore it temporary. _state.ignoreFirstResponder = NO; } } /// Show highlight layout based on `_highlight` and `_highlightRange` /// If the `_highlightLayout` is nil, try to create. - (void)_showHighlightAnimated:(BOOL)animated { NSTimeInterval fadeDuration = animated ? kHighlightFadeDuration : 0; if (!_highlight) return; if (!_highlightLayout) { NSMutableAttributedString *hiText = (_delectedText ? _delectedText : _innerText).mutableCopy; NSDictionary *newAttrs = _highlight.attributes; [newAttrs enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) { [hiText setAttribute:key value:value range:_highlightRange]; }]; _highlightLayout = [YYTextLayout layoutWithContainer:_innerContainer text:hiText]; if (!_highlightLayout) _highlight = nil; } if (_highlightLayout && !_state.showingHighlight) { _state.showingHighlight = YES; [_containerView setLayout:_highlightLayout withFadeDuration:fadeDuration]; } } /// Show `_innerLayout` instead of `_highlightLayout`. /// It does not destory the `_highlightLayout`. - (void)_hideHighlightAnimated:(BOOL)animated { NSTimeInterval fadeDuration = animated ? kHighlightFadeDuration : 0; if (_state.showingHighlight) { _state.showingHighlight = NO; [_containerView setLayout:_innerLayout withFadeDuration:fadeDuration]; } } /// Show `_innerLayout` and destory the `_highlight` and `_highlightLayout`. - (void)_removeHighlightAnimated:(BOOL)animated { [self _hideHighlightAnimated:animated]; _highlight = nil; _highlightLayout = nil; } /// Scroll current selected range to visible. - (void)_scrollSelectedRangeToVisible { [self _scrollRangeToVisible:_selectedTextRange]; } /// Scroll range to visible, take account into keyboard and insets. - (void)_scrollRangeToVisible:(YYTextRange *)range { if (!range) return; CGRect rect = [_innerLayout rectForRange:range]; if (CGRectIsNull(rect)) return; rect = [self _convertRectFromLayout:rect]; rect = [_containerView convertRect:rect toView:self]; if (rect.size.width < 1) rect.size.width = 1; if (rect.size.height < 1) rect.size.height = 1; CGFloat extend = 3; BOOL insetModified = NO; YYTextKeyboardManager *mgr = [YYTextKeyboardManager defaultManager]; if (mgr.keyboardVisible && self.window && self.superview && self.isFirstResponder && !_verticalForm) { CGRect bounds = self.bounds; bounds.origin = CGPointZero; CGRect kbRect = [mgr convertRect:mgr.keyboardFrame toView:self]; kbRect.origin.y -= _extraAccessoryViewHeight; kbRect.size.height += _extraAccessoryViewHeight; kbRect.origin.x -= self.contentOffset.x; kbRect.origin.y -= self.contentOffset.y; CGRect inter = CGRectIntersection(bounds, kbRect); if (!CGRectIsNull(inter) && inter.size.height > 1 && inter.size.width > extend) { // self is covered by keyboard if (CGRectGetMinY(inter) > CGRectGetMinY(bounds)) { // keyboard below self.top UIEdgeInsets originalContentInset = self.contentInset; UIEdgeInsets originalScrollIndicatorInsets = self.scrollIndicatorInsets; if (_insetModifiedByKeyboard) { originalContentInset = _originalContentInset; originalScrollIndicatorInsets = _originalScrollIndicatorInsets; } if (originalContentInset.bottom < inter.size.height + extend) { insetModified = YES; if (!_insetModifiedByKeyboard) { _insetModifiedByKeyboard = YES; _originalContentInset = self.contentInset; _originalScrollIndicatorInsets = self.scrollIndicatorInsets; } UIEdgeInsets newInset = originalContentInset; UIEdgeInsets newIndicatorInsets = originalScrollIndicatorInsets; newInset.bottom = inter.size.height + extend; newIndicatorInsets.bottom = newInset.bottom; UIViewAnimationOptions curve; if (kiOS7Later) { curve = 7 << 16; } else { curve = UIViewAnimationOptionCurveEaseInOut; } [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction | curve animations:^{ [super setContentInset:newInset]; [super setScrollIndicatorInsets:newIndicatorInsets]; [self scrollRectToVisible:CGRectInset(rect, -extend, -extend) animated:NO]; } completion:NULL]; } } } } if (!insetModified) { [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut animations:^{ [self _restoreInsetsAnimated:NO]; [self scrollRectToVisible:CGRectInset(rect, -extend, -extend) animated:NO]; } completion:NULL]; } } /// Restore contents insets if modified by keyboard. - (void)_restoreInsetsAnimated:(BOOL)animated { if (_insetModifiedByKeyboard) { _insetModifiedByKeyboard = NO; if (animated) { [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut animations:^{ [super setContentInset:_originalContentInset]; [super setScrollIndicatorInsets:_originalScrollIndicatorInsets]; } completion:NULL]; } else { [super setContentInset:_originalContentInset]; [super setScrollIndicatorInsets:_originalScrollIndicatorInsets]; } } } /// Keyboard frame changed, scroll the caret to visible range, or modify the content insets. - (void)_keyboardChanged { if (!self.isFirstResponder) return; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if ([YYTextKeyboardManager defaultManager].keyboardVisible) { [self _scrollRangeToVisible:_selectedTextRange]; } else { [self _restoreInsetsAnimated:YES]; } [self _updateMagnifier]; if (_state.showingMenu) { [self _showMenu]; } }); } /// Start long press timer, used for 'highlight' range text action. - (void)_startLongPressTimer { [_longPressTimer invalidate]; _longPressTimer = [NSTimer timerWithTimeInterval:kLongPressMinimumDuration target:[YYWeakProxy proxyWithTarget:self] selector:@selector(_trackDidLongPress) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:_longPressTimer forMode:NSRunLoopCommonModes]; } /// Invalidate the long press timer. - (void)_endLongPressTimer { [_longPressTimer invalidate]; _longPressTimer = nil; } /// Long press detected. - (void)_trackDidLongPress { [self _endLongPressTimer]; BOOL dealLongPressAction = NO; if (_state.showingHighlight) { [self _hideMenu]; if (_highlight.longPressAction) { dealLongPressAction = YES; CGRect rect = [_innerLayout rectForRange:[YYTextRange rangeWithRange:_highlightRange]]; rect = [self _convertRectFromLayout:rect]; _highlight.longPressAction(self, _innerText, _highlightRange, rect); [self _endTouchTracking]; } else { BOOL shouldHighlight = YES; if ([self.delegate respondsToSelector:@selector(textView:shouldLongPressHighlight:inRange:)]) { shouldHighlight = [self.delegate textView:self shouldLongPressHighlight:_highlight inRange:_highlightRange]; } if (shouldHighlight && [self.delegate respondsToSelector:@selector(textView:didLongPressHighlight:inRange:rect:)]) { dealLongPressAction = YES; CGRect rect = [_innerLayout rectForRange:[YYTextRange rangeWithRange:_highlightRange]]; rect = [self _convertRectFromLayout:rect]; [self.delegate textView:self didLongPressHighlight:_highlight inRange:_highlightRange rect:rect]; [self _endTouchTracking]; } } } if (!dealLongPressAction){ [self _removeHighlightAnimated:NO]; if (_state.trackingTouch) { if (_state.trackingGrabber) { self.panGestureRecognizer.enabled = NO; [self _hideMenu]; [self _showMagnifierRanged]; } else if (self.isFirstResponder){ self.panGestureRecognizer.enabled = NO; _selectionView.caretBlinks = NO; _state.trackingCaret = YES; CGPoint trackingPoint = [self _convertPointToLayout:_trackingPoint]; YYTextPosition *newPos = [_innerLayout closestPositionToPoint:trackingPoint]; newPos = [self _correctedTextPosition:newPos]; if (newPos) { if (_markedTextRange) { if ([newPos compare:_markedTextRange.start] != NSOrderedDescending) { newPos = _markedTextRange.start; } else if ([newPos compare:_markedTextRange.end] != NSOrderedAscending) { newPos = _markedTextRange.end; } } _trackingRange = [YYTextRange rangeWithRange:NSMakeRange(newPos.offset, 0) affinity:newPos.affinity]; [self _updateSelectionView]; } [self _hideMenu]; if (_markedTextRange) { [self _showMagnifierRanged]; } else { [self _showMagnifierCaret]; } } else if (self.selectable) { self.panGestureRecognizer.enabled = NO; _state.trackingPreSelect = YES; _state.selectedWithoutEdit = NO; [self _updateTextRangeByTrackingPreSelect]; [self _updateSelectionView]; [self _showMagnifierCaret]; } } } } /// Start auto scroll timer, used for auto scroll tick. - (void)_startAutoScrollTimer { if (!_autoScrollTimer) { [_autoScrollTimer invalidate]; _autoScrollTimer = [NSTimer timerWithTimeInterval:kAutoScrollMinimumDuration target:[YYWeakProxy proxyWithTarget:self] selector:@selector(_trackDidTickAutoScroll) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:_autoScrollTimer forMode:NSRunLoopCommonModes]; } } /// Invalidate the auto scroll, and restore the text view state. - (void)_endAutoScrollTimer { if (_state.autoScrollTicked) [self flashScrollIndicators]; [_autoScrollTimer invalidate]; _autoScrollTimer = nil; _autoScrollOffset = 0; _autoScrollAcceleration = 0; _state.autoScrollTicked = NO; if (_magnifierCaret.captureDisabled) { _magnifierCaret.captureDisabled = NO; if (_state.showingMagnifierCaret) { [self _showMagnifierCaret]; } } if (_magnifierRanged.captureDisabled) { _magnifierRanged.captureDisabled = NO; if (_state.showingMagnifierRanged) { [self _showMagnifierRanged]; } } } /// Auto scroll ticked by timer. - (void)_trackDidTickAutoScroll { if (_autoScrollOffset != 0) { _magnifierCaret.captureDisabled = YES; _magnifierRanged.captureDisabled = YES; CGPoint offset = self.contentOffset; if (_verticalForm) { offset.x += _autoScrollOffset; if (_autoScrollAcceleration > 0) { offset.x += ((_autoScrollOffset > 0 ? 1 : -1) * _autoScrollAcceleration * _autoScrollAcceleration * 0.5); } _autoScrollAcceleration++; offset.x = round(offset.x); if (_autoScrollOffset < 0) { if (offset.x < -self.contentInset.left) offset.x = -self.contentInset.left; } else { CGFloat maxOffsetX = self.contentSize.width - self.bounds.size.width + self.contentInset.right; if (offset.x > maxOffsetX) offset.x = maxOffsetX; } if (offset.x < -self.contentInset.left) offset.x = -self.contentInset.left; } else { offset.y += _autoScrollOffset; if (_autoScrollAcceleration > 0) { offset.y += ((_autoScrollOffset > 0 ? 1 : -1) * _autoScrollAcceleration * _autoScrollAcceleration * 0.5); } _autoScrollAcceleration++; offset.y = round(offset.y); if (_autoScrollOffset < 0) { if (offset.y < -self.contentInset.top) offset.y = -self.contentInset.top; } else { CGFloat maxOffsetY = self.contentSize.height - self.bounds.size.height + self.contentInset.bottom; if (offset.y > maxOffsetY) offset.y = maxOffsetY; } if (offset.y < -self.contentInset.top) offset.y = -self.contentInset.top; } BOOL shouldScroll; if (_verticalForm) { shouldScroll = fabs(offset.x -self.contentOffset.x) > 0.5; } else { shouldScroll = fabs(offset.y -self.contentOffset.y) > 0.5; } if (shouldScroll) { _state.autoScrollTicked = YES; _trackingPoint.x += offset.x - self.contentOffset.x; _trackingPoint.y += offset.y - self.contentOffset.y; [UIView animateWithDuration:kAutoScrollMinimumDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear animations:^{ [self setContentOffset:offset]; } completion:^(BOOL finished) { if (_state.trackingTouch) { if (_state.trackingGrabber) { [self _showMagnifierRanged]; [self _updateTextRangeByTrackingGrabber]; } else if (_state.trackingPreSelect) { [self _showMagnifierCaret]; [self _updateTextRangeByTrackingPreSelect]; } else if (_state.trackingCaret) { if (_markedTextRange) { [self _showMagnifierRanged]; } else { [self _showMagnifierCaret]; } [self _updateTextRangeByTrackingCaret]; } [self _updateSelectionView]; } }]; } else { [self _endAutoScrollTimer]; } } else { [self _endAutoScrollTimer]; } } /// End current touch tracking (if is tracking now), and update the state. - (void)_endTouchTracking { if (!_state.trackingTouch) return; _state.trackingTouch = NO; _state.trackingGrabber = NO; _state.trackingCaret = NO; _state.trackingPreSelect = NO; _state.touchMoved = NO; _state.deleteConfirm = NO; _state.clearsOnInsertionOnce = NO; _trackingRange = nil; _selectionView.caretBlinks = YES; [self _removeHighlightAnimated:YES]; [self _hideMagnifier]; [self _endLongPressTimer]; [self _endAutoScrollTimer]; [self _updateSelectionView]; self.panGestureRecognizer.enabled = self.scrollEnabled; } /// Start a timer to fix the selection dot. - (void)_startSelectionDotFixTimer { [_selectionDotFixTimer invalidate]; _longPressTimer = [NSTimer timerWithTimeInterval:1/15.0 target:[YYWeakProxy proxyWithTarget:self] selector:@selector(_fixSelectionDot) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:_longPressTimer forMode:NSRunLoopCommonModes]; } /// End the timer. - (void)_endSelectionDotFixTimer { [_selectionDotFixTimer invalidate]; _selectionDotFixTimer = nil; } /// If it shows selection grabber and this view was moved by super view, /// update the selection dot in window. - (void)_fixSelectionDot { if ([UIApplication isAppExtension]) return; CGPoint origin = [self convertPoint:CGPointZero toViewOrWindow:[YYTextEffectWindow sharedWindow]]; if (!CGPointEqualToPoint(origin, _previousOriginInWindow)) { _previousOriginInWindow = origin; [[YYTextEffectWindow sharedWindow] hideSelectionDot:_selectionView]; [[YYTextEffectWindow sharedWindow] showSelectionDot:_selectionView]; } } /// Try to get the character range/position with word granularity from the tokenizer. - (YYTextRange *)_getClosestTokenRangeAtPosition:(YYTextPosition *)position { position = [self _correctedTextPosition:position]; if (!position) return nil; YYTextRange *range = nil; if (_tokenizer) { range = (id)[_tokenizer rangeEnclosingPosition:position withGranularity:UITextGranularityWord inDirection:UITextStorageDirectionForward]; if (range.asRange.length == 0) { range = (id)[_tokenizer rangeEnclosingPosition:position withGranularity:UITextGranularityWord inDirection:UITextStorageDirectionBackward]; } } if (!range || range.asRange.length == 0) { range = [_innerLayout textRangeByExtendingPosition:position inDirection:UITextLayoutDirectionRight offset:1]; range = [self _correctedTextRange:range]; if (range.asRange.length == 0) { range = [_innerLayout textRangeByExtendingPosition:position inDirection:UITextLayoutDirectionLeft offset:1]; range = [self _correctedTextRange:range]; } } else { YYTextRange *extStart = [_innerLayout textRangeByExtendingPosition:range.start]; YYTextRange *extEnd = [_innerLayout textRangeByExtendingPosition:range.end]; if (extStart && extEnd) { NSArray *arr = [@[extStart.start, extStart.end, extEnd.start, extEnd.end] sortedArrayUsingSelector:@selector(compare:)]; range = [YYTextRange rangeWithStart:arr.firstObject end:arr.lastObject]; } } range = [self _correctedTextRange:range]; if (range.asRange.length == 0) { range = [YYTextRange rangeWithRange:NSMakeRange(0, _innerText.length)]; } return [self _correctedTextRange:range]; } /// Try to get the character range/position with word granularity from the tokenizer. - (YYTextRange *)_getClosestTokenRangeAtPoint:(CGPoint)point { point = [self _convertPointToLayout:point]; YYTextRange *touchRange = [_innerLayout closestTextRangeAtPoint:point]; touchRange = [self _correctedTextRange:touchRange]; if (_tokenizer && touchRange) { YYTextRange *encEnd = (id)[_tokenizer rangeEnclosingPosition:touchRange.end withGranularity:UITextGranularityWord inDirection:UITextStorageDirectionBackward]; YYTextRange *encStart = (id)[_tokenizer rangeEnclosingPosition:touchRange.start withGranularity:UITextGranularityWord inDirection:UITextStorageDirectionForward]; if (encEnd && encStart) { NSArray *arr = [@[encEnd.start, encEnd.end, encStart.start, encStart.end] sortedArrayUsingSelector:@selector(compare:)]; touchRange = [YYTextRange rangeWithStart:arr.firstObject end:arr.lastObject]; } } if (touchRange) { YYTextRange *extStart = [_innerLayout textRangeByExtendingPosition:touchRange.start]; YYTextRange *extEnd = [_innerLayout textRangeByExtendingPosition:touchRange.end]; if (extStart && extEnd) { NSArray *arr = [@[extStart.start, extStart.end, extEnd.start, extEnd.end] sortedArrayUsingSelector:@selector(compare:)]; touchRange = [YYTextRange rangeWithStart:arr.firstObject end:arr.lastObject]; } } if (!touchRange) touchRange = [YYTextRange defaultRange]; if (_innerText.length && touchRange.asRange.length == 0) { touchRange = [YYTextRange rangeWithRange:NSMakeRange(0, _innerText.length)]; } return touchRange; } /// Try to get the highlight property. If exist, the range will be returnd by the range pointer. /// If the delegate ignore the highlight, returns nil. - (YYTextHighlight *)_getHighlightAtPoint:(CGPoint)point range:(NSRangePointer)range { if (!_highlightable || !_innerLayout.containsHighlight) return nil; point = [self _convertPointToLayout:point]; YYTextRange *textRange = [_innerLayout textRangeAtPoint:point]; textRange = [self _correctedTextRange:textRange]; if (!textRange) return nil; NSUInteger startIndex = textRange.start.offset; if (startIndex == _innerText.length) { if (startIndex == 0) return nil; else startIndex--; } NSRange highlightRange = {0}; NSAttributedString *text = _delectedText ? _delectedText : _innerText; YYTextHighlight *highlight = [text attribute:YYTextHighlightAttributeName atIndex:startIndex longestEffectiveRange:&highlightRange inRange:NSMakeRange(0, _innerText.length)]; if (!highlight) return nil; BOOL shouldTap = YES, shouldLongPress = YES; if (!highlight.tapAction && !highlight.longPressAction) { if ([self.delegate respondsToSelector:@selector(textView:shouldTapHighlight:inRange:)]) { shouldTap = [self.delegate textView:self shouldTapHighlight:highlight inRange:highlightRange]; } if ([self.delegate respondsToSelector:@selector(textView:shouldLongPressHighlight:inRange:)]) { shouldLongPress = [self.delegate textView:self shouldLongPressHighlight:highlight inRange:highlightRange]; } } if (!shouldTap && !shouldLongPress) return nil; if (range) *range = highlightRange; return highlight; } /// Return the ranged magnifier popover offset from the baseline, base on `_trackingPoint`. - (CGFloat)_getMagnifierRangedOffset { CGPoint magPoint = _trackingPoint; magPoint = [self _convertPointToLayout:magPoint]; if (_verticalForm) { magPoint.x += kMagnifierRangedTrackFix; } else { magPoint.y += kMagnifierRangedTrackFix; } YYTextPosition *position = [_innerLayout closestPositionToPoint:magPoint]; NSUInteger lineIndex = [_innerLayout lineIndexForPosition:position]; if (lineIndex < _innerLayout.lines.count) { YYTextLine *line = _innerLayout.lines[lineIndex]; if (_verticalForm) { magPoint.x = YY_CLAMP(magPoint.x, line.left, line.right); return magPoint.x - line.position.x + kMagnifierRangedPopoverOffset; } else { magPoint.y = YY_CLAMP(magPoint.y, line.top, line.bottom); return magPoint.y - line.position.y + kMagnifierRangedPopoverOffset; } } else { return 0; } } /// Return a YYTextMoveDirection from `_touchBeganPoint` to `_trackingPoint`. - (unsigned int)_getMoveDirection { CGFloat moveH = _trackingPoint.x - _touchBeganPoint.x; CGFloat moveV = _trackingPoint.y - _touchBeganPoint.y; if (fabs(moveH) > fabs(moveV)) { if (fabs(moveH) > kLongPressAllowableMovement) { return moveH > 0 ? kRight : kLeft; } } else { if (fabs(moveV) > kLongPressAllowableMovement) { return moveV > 0 ? kBottom : kTop; } } return 0; } /// Get the auto scroll offset in one tick time. - (CGFloat)_getAutoscrollOffset { if (!_state.trackingTouch) return 0; CGRect bounds = self.bounds; bounds.origin = CGPointZero; YYTextKeyboardManager *mgr = [YYTextKeyboardManager defaultManager]; if (mgr.keyboardVisible && self.window && self.superview && self.isFirstResponder && !_verticalForm) { CGRect kbRect = [mgr convertRect:mgr.keyboardFrame toView:self]; kbRect.origin.y -= _extraAccessoryViewHeight; kbRect.size.height += _extraAccessoryViewHeight; kbRect.origin.x -= self.contentOffset.x; kbRect.origin.y -= self.contentOffset.y; CGRect inter = CGRectIntersection(bounds, kbRect); if (!CGRectIsNull(inter) && inter.size.height > 1 && inter.size.width > 1) { if (CGRectGetMinY(inter) > CGRectGetMinY(bounds)) { bounds.size.height -= inter.size.height; } } } CGPoint point = _trackingPoint; point.x -= self.contentOffset.x; point.y -= self.contentOffset.y; CGFloat maxOfs = 32; // a good value ~ CGFloat ofs = 0; if (_verticalForm) { if (point.x < self.contentInset.left) { ofs = (point.x - self.contentInset.left - 5) * 0.5; if (ofs < -maxOfs) ofs = -maxOfs; } else if (point.x > bounds.size.width) { ofs = ((point.x - bounds.size.width) + 5) * 0.5; if (ofs > maxOfs) ofs = maxOfs; } } else { if (point.y < self.contentInset.top) { ofs = (point.y - self.contentInset.top - 5) * 0.5; if (ofs < -maxOfs) ofs = -maxOfs; } else if (point.y > bounds.size.height) { ofs = ((point.y - bounds.size.height) + 5) * 0.5; if (ofs > maxOfs) ofs = maxOfs; } } return ofs; } /// Visible size based on bounds and insets - (CGSize)_getVisibleSize { CGSize visibleSize = self.bounds.size; visibleSize.width -= self.contentInset.left - self.contentInset.right; visibleSize.height -= self.contentInset.top - self.contentInset.bottom; if (visibleSize.width < 0) visibleSize.width = 0; if (visibleSize.height < 0) visibleSize.height = 0; return visibleSize; } /// Returns whether the text view can paste data from pastboard. - (BOOL)_isPasteboardContainsValidValue { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; if (pasteboard.string.length > 0) { return YES; } if (pasteboard.attributedString.length > 0) { if (_allowsPasteAttributedString) { return YES; } } if (pasteboard.image || pasteboard.imageData.length > 0) { if (_allowsPasteImage) { return YES; } } return NO; } /// Save current selected attributed text to pasteboard. - (void)_copySelectedTextToPasteboard { if (_allowsCopyAttributedString) { NSAttributedString *text = [_innerText attributedSubstringFromRange:_selectedTextRange.asRange]; if (text.length) { [UIPasteboard generalPasteboard].attributedString = text; } } else { NSString *string = [_innerText plainTextForRange:_selectedTextRange.asRange]; if (string.length) { [UIPasteboard generalPasteboard].string = string; } } } /// Update the text view state when pasteboard changed. - (void)_pasteboardChanged { if (_state.showingMenu) { UIMenuController *menu = [UIMenuController sharedMenuController]; [menu update]; } } /// Whether the position is valid (not out of bounds). - (BOOL)_isTextPositionValid:(YYTextPosition *)position { if (!position) return NO; if (position.offset < 0) return NO; if (position.offset > _innerText.length) return NO; if (position.offset == 0 && position.affinity == YYTextAffinityBackward) return NO; if (position.offset == _innerText.length && position.affinity == YYTextAffinityBackward) return NO; return YES; } /// Whether the range is valid (not out of bounds). - (BOOL)_isTextRangeValid:(YYTextRange *)range { if (![self _isTextPositionValid:range.start]) return NO; if (![self _isTextPositionValid:range.end]) return NO; return YES; } /// Correct the position if it out of bounds. - (YYTextPosition *)_correctedTextPosition:(YYTextPosition *)position { if (!position) return nil; if ([self _isTextPositionValid:position]) return position; if (position.offset < 0) { return [YYTextPosition positionWithOffset:0]; } if (position.offset > _innerText.length) { return [YYTextPosition positionWithOffset:_innerText.length]; } if (position.offset == 0 && position.affinity == YYTextAffinityBackward) { return [YYTextPosition positionWithOffset:position.offset]; } if (position.offset == _innerText.length && position.affinity == YYTextAffinityBackward) { return [YYTextPosition positionWithOffset:position.offset]; } return position; } /// Correct the range if it out of bounds. - (YYTextRange *)_correctedTextRange:(YYTextRange *)range { if (!range) return nil; if ([self _isTextRangeValid:range]) return range; YYTextPosition *start = [self _correctedTextPosition:range.start]; YYTextPosition *end = [self _correctedTextPosition:range.end]; return [YYTextRange rangeWithStart:start end:end]; } /// Convert the point from this view to text layout. - (CGPoint)_convertPointToLayout:(CGPoint)point { CGSize boundingSize = _innerLayout.textBoundingSize; if (_innerLayout.container.isVerticalForm) { CGFloat w = _innerLayout.textBoundingSize.width; if (w < self.bounds.size.width) w = self.bounds.size.width; point.x += _innerLayout.container.size.width - w; if (boundingSize.width < self.bounds.size.width) { if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.x += (self.bounds.size.width - boundingSize.width) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.x += (self.bounds.size.width - boundingSize.width); } } return point; } else { if (boundingSize.height < self.bounds.size.height) { if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.y -= (self.bounds.size.height - boundingSize.height) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.y -= (self.bounds.size.height - boundingSize.height); } } return point; } } /// Convert the point from text layout to this view. - (CGPoint)_convertPointFromLayout:(CGPoint)point { CGSize boundingSize = _innerLayout.textBoundingSize; if (_innerLayout.container.isVerticalForm) { CGFloat w = _innerLayout.textBoundingSize.width; if (w < self.bounds.size.width) w = self.bounds.size.width; point.x -= _innerLayout.container.size.width - w; if (boundingSize.width < self.bounds.size.width) { if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.x -= (self.bounds.size.width - boundingSize.width) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.x -= (self.bounds.size.width - boundingSize.width); } } return point; } else { if (boundingSize.height < self.bounds.size.height) { if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { point.y += (self.bounds.size.height - boundingSize.height) * 0.5; } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { point.y += (self.bounds.size.height - boundingSize.height); } } return point; } } /// Convert the rect from this view to text layout. - (CGRect)_convertRectToLayout:(CGRect)rect { rect.origin = [self _convertPointToLayout:rect.origin]; return rect; } /// Convert the rect from text layout to this view. - (CGRect)_convertRectFromLayout:(CGRect)rect { rect.origin = [self _convertPointFromLayout:rect.origin]; return rect; } /// Replace the range with the text, and change the `_selectTextRange`. /// The caller should make sure the `range` and `text` are valid before call this method. - (void)_replaceRange:(YYTextRange *)range withText:(NSString *)text notifyToDelegate:(BOOL)notify{ if (NSEqualRanges(range.asRange, _selectedTextRange.asRange)) { if (notify) [_inputDelegate selectionWillChange:self]; NSRange newRange = NSMakeRange(0, 0); newRange.location = _selectedTextRange.start.offset + text.length; _selectedTextRange = [YYTextRange rangeWithRange:newRange]; if (notify) [_inputDelegate selectionDidChange:self]; } else { if (range.asRange.length != text.length) { if (notify) [_inputDelegate selectionWillChange:self]; NSRange unionRange = NSIntersectionRange(_selectedTextRange.asRange, range.asRange); if (unionRange.length == 0) { // no intersection if (range.end.offset <= _selectedTextRange.start.offset) { NSInteger ofs = (NSInteger)text.length - (NSInteger)range.asRange.length; NSRange newRange = _selectedTextRange.asRange; newRange.location += ofs; _selectedTextRange = [YYTextRange rangeWithRange:newRange]; } } else if (unionRange.length == _selectedTextRange.asRange.length) { // target range contains selected range _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(range.start.offset + text.length, 0)]; } else if (range.start.offset >= _selectedTextRange.start.offset && range.end.offset <= _selectedTextRange.end.offset) { // target range inside selected range NSInteger ofs = (NSInteger)text.length - (NSInteger)range.asRange.length; NSRange newRange = _selectedTextRange.asRange; newRange.length += ofs; _selectedTextRange = [YYTextRange rangeWithRange:newRange]; } else { // interleaving if (range.start.offset < _selectedTextRange.start.offset) { NSRange newRange = _selectedTextRange.asRange; newRange.location = range.start.offset + text.length; newRange.length -= unionRange.length; _selectedTextRange = [YYTextRange rangeWithRange:newRange]; } else { NSRange newRange = _selectedTextRange.asRange; newRange.length -= unionRange.length; _selectedTextRange = [YYTextRange rangeWithRange:newRange]; } } _selectedTextRange = [self _correctedTextRange:_selectedTextRange]; if (notify) [_inputDelegate selectionDidChange:self]; } } if (notify) [_inputDelegate textWillChange:self]; NSRange newRange = NSMakeRange(range.asRange.location, text.length); [_innerText replaceCharactersInRange:range.asRange withString:text]; [_innerText removeDiscontinuousAttributesInRange:newRange]; if (notify) [_inputDelegate textDidChange:self]; } /// Save current typing attributes to the attributes holder. - (void)_updateAttributesHolder { if (_innerText.length > 0) { NSUInteger index = _selectedTextRange.end.offset == 0 ? 0 : _selectedTextRange.end.offset - 1; NSDictionary *attributes = [_innerText attributesAtIndex:index]; if (!attributes) attributes = @{}; _typingAttributesHolder.attributes = attributes; [_typingAttributesHolder removeDiscontinuousAttributesInRange:NSMakeRange(0, _typingAttributesHolder.length)]; [_typingAttributesHolder removeAttribute:YYTextBorderAttributeName range:NSMakeRange(0, _typingAttributesHolder.length)]; [_typingAttributesHolder removeAttribute:YYTextBackgroundBorderAttributeName range:NSMakeRange(0, _typingAttributesHolder.length)]; } } /// Update outer properties from current inner data. - (void)_updateOuterProperties { [self _updateAttributesHolder]; NSParagraphStyle *style = _innerText.paragraphStyle; if (!style) style = _typingAttributesHolder.paragraphStyle; if (!style) style = [NSParagraphStyle defaultParagraphStyle]; UIFont *font = _innerText.font; if (!font) font = _typingAttributesHolder.font; if (!font) font = [self _defaultFont]; UIColor *color = _innerText.color; if (!color) color = _typingAttributesHolder.color; if (!color) color = [UIColor blackColor]; [self _setText:[_innerText plainTextForRange:NSMakeRange(0, _innerText.length)]]; [self _setFont:font]; [self _setTextColor:color]; [self _setTextAlignment:style.alignment]; [self _setSelectedRange:_selectedTextRange.asRange]; [self _setTypingAttributes:_typingAttributesHolder.attributes]; [self _setAttributedText:_innerText]; } /// Parse text with `textParser` and update the _selectedTextRange. /// @return Whether changed (text or selection) - (BOOL)_parseText { if (self.textParser) { YYTextRange *oldTextRange = _selectedTextRange; NSRange newRange = _selectedTextRange.asRange; [_inputDelegate textWillChange:self]; BOOL textChanged = [self.textParser parseText:_innerText selectedRange:&newRange]; [_inputDelegate textDidChange:self]; YYTextRange *newTextRange = [YYTextRange rangeWithRange:newRange]; newTextRange = [self _correctedTextRange:newTextRange]; if (![oldTextRange isEqual:newTextRange]) { [_inputDelegate selectionWillChange:self]; _selectedTextRange = newTextRange; [_inputDelegate selectionDidChange:self]; } return textChanged; } return NO; } /// Returns whether the text should be detected by the data detector. - (BOOL)_shouldDetectText { if (!_dataDetector) return NO; if (!_highlightable) return NO; if (_linkTextAttributes.count == 0 && _highlightTextAttributes.count == 0) return NO; if (self.isFirstResponder || _containerView.isFirstResponder) return NO; return YES; } /// Detect the data in text and add highlight to the data range. /// @return Whether detected. - (BOOL)_detectText:(NSMutableAttributedString *)text { if (![self _shouldDetectText]) return NO; if (text.length == 0) return NO; __block BOOL detected = NO; [_dataDetector enumerateMatchesInString:text.string options:kNilOptions range:NSMakeRange(0, text.length) usingBlock: ^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { switch (result.resultType) { case NSTextCheckingTypeDate: case NSTextCheckingTypeAddress: case NSTextCheckingTypeLink: case NSTextCheckingTypePhoneNumber: { detected = YES; if (_highlightTextAttributes.count) { YYTextHighlight *highlight = [YYTextHighlight highlightWithAttributes:_highlightTextAttributes]; [text setTextHighlight:highlight range:result.range]; } if (_linkTextAttributes.count) { [_linkTextAttributes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [text setAttribute:key value:obj range:result.range]; }]; } } break; default: break; } }]; return detected; } /// Returns the `root` view controller (returns nil if not found). - (UIViewController *)_getRootViewController { UIViewController *ctrl = nil; UIApplication *app = [UIApplication sharedExtensionApplication]; if (!ctrl) ctrl = app.keyWindow.rootViewController; if (!ctrl) ctrl = [app.windows.firstObject rootViewController]; if (!ctrl) ctrl = self.viewController; if (!ctrl) return nil; while (!ctrl.view.window && ctrl.presentedViewController) { ctrl = ctrl.presentedViewController; } if (!ctrl.view.window) return nil; return ctrl; } /// Clear the undo and redo stack, and capture current state to undo stack. - (void)_resetUndoAndRedoStack { [_undoStack removeAllObjects]; [_redoStack removeAllObjects]; _YYTextViewUndoObject *object = [_YYTextViewUndoObject objectWithText:_innerText.copy range:_selectedTextRange.asRange]; _lastTypeRange = _selectedTextRange.asRange; [_undoStack addObject:object]; } /// Clear the redo stack. - (void)_resetRedoStack { [_redoStack removeAllObjects]; } /// Capture current state to undo stack. - (void)_saveToUndoStack { if (!_allowsUndoAndRedo) return; _YYTextViewUndoObject *lastObject = _undoStack.lastObject; if ([lastObject.text isEqualToAttributedString:self.attributedText]) return; _YYTextViewUndoObject *object = [_YYTextViewUndoObject objectWithText:_innerText.copy range:_selectedTextRange.asRange]; _lastTypeRange = _selectedTextRange.asRange; [_undoStack addObject:object]; while (_undoStack.count > _maximumUndoLevel) { [_undoStack removeObjectAtIndex:0]; } } /// Capture current state to redo stack. - (void)_saveToRedoStack { if (!_allowsUndoAndRedo) return; _YYTextViewUndoObject *lastObject = _redoStack.lastObject; if ([lastObject.text isEqualToAttributedString:self.attributedText]) return; _YYTextViewUndoObject *object = [_YYTextViewUndoObject objectWithText:_innerText.copy range:_selectedTextRange.asRange]; [_redoStack addObject:object]; while (_redoStack.count > _maximumUndoLevel) { [_redoStack removeObjectAtIndex:0]; } } - (BOOL)_canUndo { if (_undoStack.count == 0) return NO; _YYTextViewUndoObject *object = _undoStack.lastObject; if ([object.text isEqualToAttributedString:_innerText]) return NO; return YES; } - (BOOL)_canRedo { if (_redoStack.count == 0) return NO; _YYTextViewUndoObject *object = _undoStack.lastObject; if ([object.text isEqualToAttributedString:_innerText]) return NO; return YES; } - (void)_undo { if (![self _canUndo]) return; [self _saveToRedoStack]; _YYTextViewUndoObject *object = _undoStack.lastObject; [_undoStack removeLastObject]; _state.insideUndoBlock = YES; self.attributedText = object.text; self.selectedRange = object.selectedRange; _state.insideUndoBlock = NO; } - (void)_redo { if (![self _canRedo]) return; [self _saveToUndoStack]; _YYTextViewUndoObject *object = _redoStack.lastObject; [_redoStack removeLastObject]; _state.insideUndoBlock = YES; self.attributedText = object.text; self.selectedRange = object.selectedRange; _state.insideUndoBlock = NO; } - (void)_restoreFirstResponderAfterUndoAlert { if (_state.firstResponderBeforeUndoAlert) { [self performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0]; } } /// Show undo alert if it can undo or redo. #ifdef __IPHONE_OS_VERSION_MIN_REQUIRED - (void)_showUndoRedoAlert NS_EXTENSION_UNAVAILABLE_IOS(""){ _state.firstResponderBeforeUndoAlert = self.isFirstResponder; __weak typeof(self) _self = self; NSArray *strings = [self _localizedUndoStrings]; BOOL canUndo = [self _canUndo]; BOOL canRedo = [self _canRedo]; UIViewController *ctrl = [self _getRootViewController]; if (canUndo && canRedo) { if (kiOS8Later) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:strings[4] message:@"" preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:strings[3] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { [_self _undo]; [_self _restoreFirstResponderAfterUndoAlert]; }]]; [alert addAction:[UIAlertAction actionWithTitle:strings[2] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { [_self _redo]; [_self _restoreFirstResponderAfterUndoAlert]; }]]; [alert addAction:[UIAlertAction actionWithTitle:strings[0] style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { [_self _restoreFirstResponderAfterUndoAlert]; }]]; [ctrl presentViewController:alert animated:YES completion:nil]; } else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strings[4] message:@"" delegate:self cancelButtonTitle:strings[0] otherButtonTitles:strings[3], strings[2], nil]; [alert show]; #pragma clang diagnostic pop } } else if (canUndo) { if (kiOS8Later) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:strings[4] message:@"" preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:strings[3] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { [_self _undo]; [_self _restoreFirstResponderAfterUndoAlert]; }]]; [alert addAction:[UIAlertAction actionWithTitle:strings[0] style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { [_self _restoreFirstResponderAfterUndoAlert]; }]]; [ctrl presentViewController:alert animated:YES completion:nil]; } else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strings[4] message:@"" delegate:self cancelButtonTitle:strings[0] otherButtonTitles:strings[3], nil]; [alert show]; #pragma clang diagnostic pop } } else if (canRedo) { if (kiOS8Later) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:strings[2] message:@"" preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:strings[1] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { [_self _redo]; [_self _restoreFirstResponderAfterUndoAlert]; }]]; [alert addAction:[UIAlertAction actionWithTitle:strings[0] style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { [_self _restoreFirstResponderAfterUndoAlert]; }]]; [ctrl presentViewController:alert animated:YES completion:nil]; } else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strings[2] message:@"" delegate:self cancelButtonTitle:strings[0] otherButtonTitles:strings[1], nil]; [alert show]; #pragma clang diagnostic pop } } } #endif /// Get the localized undo alert strings based on app's main bundle. - (NSArray *)_localizedUndoStrings { static NSArray *strings = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSDictionary *dic = @{ @"ar" : @[ @"", @"", @" ", @"", @" " ], @"ca" : @[ @"Cancellar", @"Refer", @"Refer lescriptura", @"Desfer", @"Desfer lescriptura" ], @"cs" : @[ @"Zruit", @"Opakovat akci", @"Opakovat akci Pst", @"Odvolat akci", @"Odvolat akci Pst" ], @"da" : @[ @"Annuller", @"Gentag", @"Gentag Indtastning", @"Fortryd", @"Fortryd Indtastning" ], @"de" : @[ @"Abbrechen", @"Wiederholen", @"Eingabe wiederholen", @"Widerrufen", @"Eingabe widerrufen" ], @"el" : @[ @"", @"", @" ", @"", @" " ], @"en" : @[ @"Cancel", @"Redo", @"Redo Typing", @"Undo", @"Undo Typing" ], @"es" : @[ @"Cancelar", @"Rehacer", @"Rehacer escritura", @"Deshacer", @"Deshacer escritura" ], @"es_MX" : @[ @"Cancelar", @"Rehacer", @"Rehacer escritura", @"Deshacer", @"Deshacer escritura" ], @"fi" : @[ @"Kumoa", @"Tee sittenkin", @"Kirjoita sittenkin", @"Peru", @"Peru kirjoitus" ], @"fr" : @[ @"Annuler", @"Rtablir", @"Rtablir la saisie", @"Annuler", @"Annuler la saisie" ], @"he" : @[ @"", @" ", @" ", @"", @" " ], @"hr" : @[ @"Odustani", @"Ponovi", @"Ponovno upii", @"Poniti", @"Poniti upisivanje" ], @"hu" : @[ @"Mgsem", @"Ismtls", @"Gpels ismtlse", @"Visszavons", @"Gpels visszavonsa" ], @"id" : @[ @"Batalkan", @"Ulang", @"Ulang Pengetikan", @"Kembalikan", @"Batalkan Pengetikan" ], @"it" : @[ @"Annulla", @"Ripristina originale", @"Ripristina Inserimento", @"Annulla", @"Annulla Inserimento" ], @"ja" : @[ @"", @"", @" - ", @"", @" - " ], @"ko" : @[ @"", @" ", @" ", @" ", @" " ], @"ms" : @[ @"Batal", @"Buat semula", @"Ulang Penaipan", @"Buat asal", @"Buat asal Penaipan" ], @"nb" : @[ @"Avbryt", @"Utfr likevel", @"Utfr skriving likevel", @"Angre", @"Angre skriving" ], @"nl" : @[ @"Annuleer", @"Opnieuw", @"Opnieuw typen", @"Herstel", @"Herstel typen" ], @"pl" : @[ @"Anuluj", @"Przywr", @"Przywr Wpisz", @"Cofnij", @"Cofnij Wpisz" ], @"pt" : @[ @"Cancelar", @"Refazer", @"Refazer Digitao", @"Desfazer", @"Desfazer Digitao" ], @"pt_PT" : @[ @"Cancelar", @"Refazer", @"Refazer digitar", @"Desfazer", @"Desfazer digitar" ], @"ro" : @[ @"Renun", @"Ref", @"Ref tastare", @"Anuleaz", @"Anuleaz tastare" ], @"ru" : @[ @"", @"", @" ", @"", @" " ], @"sk" : @[ @"Zrui", @"Obnovi", @"Obnovi psanie", @"Odvola", @"Odvola psanie" ], @"sv" : @[ @"Avbryt", @"Gr om", @"Gr om skriven text", @"ngra", @"ngra skriven text" ], @"th" : @[ @"", @"", @"", @"", @"" ], @"tr" : @[ @"Vazge", @"Yinele", @"Yazmay Yinele", @"Geri Al", @"Yazmay Geri Al" ], @"uk" : @[ @"", @"", @" ", @"", @" " ], @"vi" : @[ @"Hy", @"Lm li", @"Lm li thao tc Nhp", @"Hon tc", @"Hon tc thao tc Nhp" ], @"zh" : @[ @"", @"", @"", @"", @"" ], @"zh_CN" : @[ @"", @"", @"", @"", @"" ], @"zh_HK" : @[ @"", @"", @"", @"", @"" ], @"zh_TW" : @[ @"", @"", @"", @"", @"" ] }; NSString *preferred = [[NSBundle mainBundle] preferredLocalizations].firstObject; if (preferred.length == 0) preferred = @"English"; NSString *canonical = [NSLocale canonicalLocaleIdentifierFromString:preferred]; if (canonical.length == 0) canonical = @"en"; strings = dic[canonical]; if (!strings && [canonical containsString:@"_"]) { NSString *prefix = [canonical componentsSeparatedByString:@"_"].firstObject; if (prefix.length) strings = dic[prefix]; } if (!strings) strings = dic[@"en"]; }); return strings; } /// Returns the default font for text view (same as CoreText). - (UIFont *)_defaultFont { return [UIFont systemFontOfSize:12]; } /// Returns the default tint color for text view (used for caret and select range background). - (UIColor *)_defaultTintColor { return [UIColor colorWithRed:69/255.0 green:111/255.0 blue:238/255.0 alpha:1]; } /// Returns the default placeholder color for text view (same as UITextField). - (UIColor *)_defaultPlaceholderColor { return [UIColor colorWithRed:0 green:0 blue:25/255.0 alpha:44/255.0]; } #pragma mark - Private Setter - (void)_setText:(NSString *)text { if (_text == text || [_text isEqualToString:text]) return; [self willChangeValueForKey:@"text"]; _text = text.copy; if (!_text) _text = @""; [self didChangeValueForKey:@"text"]; self.accessibilityLabel = _text; } - (void)_setFont:(UIFont *)font { if (_font == font || [_font isEqual:font]) return; [self willChangeValueForKey:@"font"]; _font = font; [self didChangeValueForKey:@"font"]; } - (void)_setTextColor:(UIColor *)textColor { if (_textColor == textColor) return; if (_textColor && textColor) { if (CFGetTypeID(_textColor.CGColor) == CFGetTypeID(textColor.CGColor) && CFGetTypeID(_textColor.CGColor) == CGColorGetTypeID()) { if ([_textColor isEqual:textColor]) { return; } } } [self willChangeValueForKey:@"textColor"]; _textColor = textColor; [self didChangeValueForKey:@"textColor"]; } - (void)_setTextAlignment:(NSTextAlignment)textAlignment { if (_textAlignment == textAlignment) return; [self willChangeValueForKey:@"textAlignment"]; _textAlignment = textAlignment; [self didChangeValueForKey:@"textAlignment"]; } - (void)_setDataDetectorTypes:(UIDataDetectorTypes)dataDetectorTypes { if (_dataDetectorTypes == dataDetectorTypes) return; [self willChangeValueForKey:@"dataDetectorTypes"]; _dataDetectorTypes = dataDetectorTypes; [self didChangeValueForKey:@"dataDetectorTypes"]; } - (void)_setLinkTextAttributes:(NSDictionary *)linkTextAttributes { if (_linkTextAttributes == linkTextAttributes || [_linkTextAttributes isEqual:linkTextAttributes]) return; [self willChangeValueForKey:@"linkTextAttributes"]; _linkTextAttributes = linkTextAttributes.copy; [self didChangeValueForKey:@"linkTextAttributes"]; } - (void)_setHighlightTextAttributes:(NSDictionary *)highlightTextAttributes { if (_highlightTextAttributes == highlightTextAttributes || [_highlightTextAttributes isEqual:highlightTextAttributes]) return; [self willChangeValueForKey:@"highlightTextAttributes"]; _highlightTextAttributes = highlightTextAttributes.copy; [self didChangeValueForKey:@"highlightTextAttributes"]; } - (void)_setTextParser:(id<YYTextParser>)textParser { if (_textParser == textParser || [_textParser isEqual:textParser]) return; [self willChangeValueForKey:@"textParser"]; _textParser = textParser; [self didChangeValueForKey:@"textParser"]; } - (void)_setAttributedText:(NSAttributedString *)attributedText { if (_attributedText == attributedText || [_attributedText isEqual:attributedText]) return; [self willChangeValueForKey:@"attributedText"]; _attributedText = attributedText.copy; if (!_attributedText) _attributedText = [NSAttributedString new]; [self didChangeValueForKey:@"attributedText"]; } - (void)_setTextContainerInset:(UIEdgeInsets)textContainerInset { if (UIEdgeInsetsEqualToEdgeInsets(_textContainerInset, textContainerInset)) return; [self willChangeValueForKey:@"textContainerInset"]; _textContainerInset = textContainerInset; [self didChangeValueForKey:@"textContainerInset"]; } - (void)_setExclusionPaths:(NSArray *)exclusionPaths { if (_exclusionPaths == exclusionPaths || [_exclusionPaths isEqual:exclusionPaths]) return; [self willChangeValueForKey:@"exclusionPaths"]; _exclusionPaths = exclusionPaths.copy; [self didChangeValueForKey:@"exclusionPaths"]; } - (void)_setVerticalForm:(BOOL)verticalForm { if (_verticalForm == verticalForm) return; [self willChangeValueForKey:@"verticalForm"]; _verticalForm = verticalForm; [self didChangeValueForKey:@"verticalForm"]; } - (void)_setLinePositionModifier:(id<YYTextLinePositionModifier>)linePositionModifier { if (_linePositionModifier == linePositionModifier) return; [self willChangeValueForKey:@"linePositionModifier"]; _linePositionModifier = [(NSObject *)linePositionModifier copy]; [self didChangeValueForKey:@"linePositionModifier"]; } - (void)_setSelectedRange:(NSRange)selectedRange { if (NSEqualRanges(_selectedRange, selectedRange)) return; [self willChangeValueForKey:@"selectedRange"]; _selectedRange = selectedRange; [self didChangeValueForKey:@"selectedRange"]; if ([self.delegate respondsToSelector:@selector(textViewDidChangeSelection:)]) { [self.delegate textViewDidChangeSelection:self]; } } - (void)_setTypingAttributes:(NSDictionary *)typingAttributes { if (_typingAttributes == typingAttributes || [_typingAttributes isEqual:typingAttributes]) return; [self willChangeValueForKey:@"typingAttributes"]; _typingAttributes = typingAttributes.copy; [self didChangeValueForKey:@"typingAttributes"]; } #pragma mark - Private Init - (void)_initTextView { self.delaysContentTouches = NO; self.canCancelContentTouches = YES; self.multipleTouchEnabled = NO; self.clipsToBounds = YES; [super setDelegate:self]; _text = @""; _attributedText = [NSAttributedString new]; // UITextInputTraits _autocapitalizationType = UITextAutocapitalizationTypeSentences; _autocorrectionType = UITextAutocorrectionTypeDefault; _spellCheckingType = UITextSpellCheckingTypeDefault; _keyboardType = UIKeyboardTypeDefault; _keyboardAppearance = UIKeyboardAppearanceDefault; _returnKeyType = UIReturnKeyDefault; _enablesReturnKeyAutomatically = NO; _secureTextEntry = NO; // UITextInput _selectedTextRange = [YYTextRange defaultRange]; _markedTextRange = nil; _markedTextStyle = nil; _tokenizer = [[UITextInputStringTokenizer alloc] initWithTextInput:self]; _editable = YES; _selectable = YES; _highlightable = YES; _allowsCopyAttributedString = YES; _textAlignment = NSTextAlignmentNatural; _innerText = [NSMutableAttributedString new]; _innerContainer = [YYTextContainer new]; _innerContainer.insets = kDefaultInset; _textContainerInset = kDefaultInset; _typingAttributesHolder = [[NSMutableAttributedString alloc] initWithString:@" "]; _linkTextAttributes = @{NSForegroundColorAttributeName : [self _defaultTintColor], (id)kCTForegroundColorAttributeName : (id)[self _defaultTintColor].CGColor}; YYTextHighlight *highlight = [YYTextHighlight new]; YYTextBorder * border = [YYTextBorder new]; border.insets = UIEdgeInsetsMake(-2, -2, -2, -2); border.fillColor = [UIColor colorWithWhite:0.1 alpha:0.2]; border.cornerRadius = 3; [highlight setBorder:border]; _highlightTextAttributes = highlight.attributes.copy; _placeHolderView = [UIImageView new]; _placeHolderView.userInteractionEnabled = NO; _placeHolderView.hidden = YES; _containerView = [YYTextContainerView new]; _containerView.hostView = self; _selectionView = [YYTextSelectionView new]; _selectionView.userInteractionEnabled = NO; _selectionView.hostView = self; _selectionView.color = [self _defaultTintColor]; _magnifierCaret = [YYTextMagnifier magnifierWithType:YYTextMagnifierTypeCaret]; _magnifierCaret.hostView = _containerView; _magnifierRanged = [YYTextMagnifier magnifierWithType:YYTextMagnifierTypeRanged]; _magnifierRanged.hostView = _containerView; [self addSubview:_placeHolderView]; [self addSubview:_containerView]; [self addSubview:_selectionView]; _undoStack = [NSMutableArray new]; _redoStack = [NSMutableArray new]; _allowsUndoAndRedo = YES; _maximumUndoLevel = kDefaultUndoLevelMax; self.debugOption = [YYTextDebugOption sharedDebugOption]; [YYTextDebugOption addDebugTarget:self]; [self _updateInnerContainerSize]; [self _update]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_pasteboardChanged) name:UIPasteboardChangedNotification object:nil]; [[YYTextKeyboardManager defaultManager] addObserver:self]; self.isAccessibilityElement = YES; } #pragma mark - Public - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (!self) return nil; [self _initTextView]; return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIPasteboardChangedNotification object:nil]; [[YYTextKeyboardManager defaultManager] removeObserver:self]; [[YYTextEffectWindow sharedWindow] hideSelectionDot:_selectionView]; [[YYTextEffectWindow sharedWindow] hideMagnifier:_magnifierCaret]; [[YYTextEffectWindow sharedWindow] hideMagnifier:_magnifierRanged]; [YYTextDebugOption removeDebugTarget:self]; [_longPressTimer invalidate]; [_autoScrollTimer invalidate]; [_selectionDotFixTimer invalidate]; } - (void)scrollRangeToVisible:(NSRange)range { YYTextRange *textRange = [YYTextRange rangeWithRange:range]; textRange = [self _correctedTextRange:textRange]; [self _scrollRangeToVisible:textRange]; } #pragma mark - Property - (void)setText:(NSString *)text { if (_text == text || [_text isEqualToString:text]) return; [self _setText:text]; _state.selectedWithoutEdit = NO; _state.deleteConfirm = NO; [self _endTouchTracking]; [self _hideMenu]; [self _resetUndoAndRedoStack]; [self replaceRange:[YYTextRange rangeWithRange:NSMakeRange(0, _innerText.length)] withText:text]; } - (void)setFont:(UIFont *)font { if (_font == font || [_font isEqual:font]) return; [self _setFont:font]; _state.typingAttributesOnce = NO; _typingAttributesHolder.font = font; _innerText.font = font; [self _resetUndoAndRedoStack]; [self _commitUpdate]; } - (void)setTextColor:(UIColor *)textColor { if (_textColor == textColor || [_textColor isEqual:textColor]) return; [self _setTextColor:textColor]; _state.typingAttributesOnce = NO; _typingAttributesHolder.color = textColor; _innerText.color = textColor; [self _resetUndoAndRedoStack]; [self _commitUpdate]; } - (void)setTextAlignment:(NSTextAlignment)textAlignment { if (_textAlignment == textAlignment) return; [self _setTextAlignment:textAlignment]; _typingAttributesHolder.alignment = textAlignment; _innerText.alignment = textAlignment; [self _resetUndoAndRedoStack]; [self _commitUpdate]; } - (void)setDataDetectorTypes:(UIDataDetectorTypes)dataDetectorTypes { if (_dataDetectorTypes == dataDetectorTypes) return; [self _setDataDetectorTypes:dataDetectorTypes]; NSTextCheckingType type = NSTextCheckingTypeFromUIDataDetectorType(dataDetectorTypes); _dataDetector = type ? [NSDataDetector dataDetectorWithTypes:type error:NULL] : nil; [self _resetUndoAndRedoStack]; [self _commitUpdate]; } - (void)setLinkTextAttributes:(NSDictionary *)linkTextAttributes { if (_linkTextAttributes == linkTextAttributes || [_linkTextAttributes isEqual:linkTextAttributes]) return; [self _setLinkTextAttributes:linkTextAttributes]; if (_dataDetector) { [self _commitUpdate]; } } - (void)setHighlightTextAttributes:(NSDictionary *)highlightTextAttributes { if (_highlightTextAttributes == highlightTextAttributes || [_highlightTextAttributes isEqual:highlightTextAttributes]) return; [self _setHighlightTextAttributes:highlightTextAttributes]; if (_dataDetector) { [self _commitUpdate]; } } - (void)setTextParser:(id<YYTextParser>)textParser { if (_textParser == textParser || [_textParser isEqual:textParser]) return; [self _setTextParser:textParser]; if (textParser && _text.length) { [self replaceRange:[YYTextRange rangeWithRange:NSMakeRange(0, _text.length)] withText:_text]; } [self _resetUndoAndRedoStack]; [self _commitUpdate]; } - (void)setTypingAttributes:(NSDictionary *)typingAttributes { [self _setTypingAttributes:typingAttributes]; _state.typingAttributesOnce = YES; [typingAttributes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [_typingAttributesHolder setAttribute:key value:obj]; }]; [self _commitUpdate]; } - (void)setAttributedText:(NSAttributedString *)attributedText { if (_attributedText == attributedText) return; [self _setAttributedText:attributedText]; _state.typingAttributesOnce = NO; NSMutableAttributedString *text = attributedText.mutableCopy; if (text.length == 0) { [self replaceRange:[YYTextRange rangeWithRange:NSMakeRange(0, _innerText.length)] withText:@""]; return; } if ([self.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) { BOOL should = [self.delegate textView:self shouldChangeTextInRange:NSMakeRange(0, _innerText.length) replacementText:text.string]; if (!should) return; } _state.selectedWithoutEdit = NO; _state.deleteConfirm = NO; [self _endTouchTracking]; [self _hideMenu]; [_inputDelegate selectionWillChange:self]; [_inputDelegate textWillChange:self]; _innerText = text; [self _parseText]; _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(0, _innerText.length)]; [_inputDelegate textDidChange:self]; [_inputDelegate selectionDidChange:self]; [self _setAttributedText:text]; if (_innerText.length > 0) { _typingAttributesHolder.attributes = [_innerText attributesAtIndex:_innerText.length - 1]; } [self _updateOuterProperties]; [self _updateLayout]; [self _updateSelectionView]; if (self.isFirstResponder) { [self _scrollRangeToVisible:_selectedTextRange]; } if ([self.delegate respondsToSelector:@selector(textViewDidChange:)]) { [self.delegate textViewDidChange:self]; } [[NSNotificationCenter defaultCenter] postNotificationName:YYTextViewTextDidChangeNotification object:self]; if (!_state.insideUndoBlock) { [self _resetUndoAndRedoStack]; } } - (void)setTextVerticalAlignment:(YYTextVerticalAlignment)textVerticalAlignment { if (_textVerticalAlignment == textVerticalAlignment) return; [self willChangeValueForKey:@"textVerticalAlignment"]; _textVerticalAlignment = textVerticalAlignment; [self didChangeValueForKey:@"textVerticalAlignment"]; _containerView.textVerticalAlignment = textVerticalAlignment; [self _commitUpdate]; } - (void)setTextContainerInset:(UIEdgeInsets)textContainerInset { if (UIEdgeInsetsEqualToEdgeInsets(_textContainerInset, textContainerInset)) return; [self _setTextContainerInset:textContainerInset]; _innerContainer.insets = textContainerInset; [self _commitUpdate]; } - (void)setExclusionPaths:(NSArray *)exclusionPaths { if (_exclusionPaths == exclusionPaths || [_exclusionPaths isEqual:exclusionPaths]) return; [self _setExclusionPaths:exclusionPaths]; _innerContainer.exclusionPaths = exclusionPaths; if (_innerContainer.isVerticalForm) { CGAffineTransform trans = CGAffineTransformMakeTranslation(_innerContainer.size.width - self.bounds.size.width, 0); [_innerContainer.exclusionPaths enumerateObjectsUsingBlock:^(UIBezierPath *path, NSUInteger idx, BOOL *stop) { [path applyTransform:trans]; }]; } [self _commitUpdate]; } - (void)setVerticalForm:(BOOL)verticalForm { if (_verticalForm == verticalForm) return; [self _setVerticalForm:verticalForm]; _innerContainer.verticalForm = verticalForm; _selectionView.verticalForm = verticalForm; [self _updateInnerContainerSize]; if (verticalForm) { if (UIEdgeInsetsEqualToEdgeInsets(_innerContainer.insets, kDefaultInset)) { _innerContainer.insets = kDefaultVerticalInset; [self _setTextContainerInset:kDefaultVerticalInset]; } } else { if (UIEdgeInsetsEqualToEdgeInsets(_innerContainer.insets, kDefaultVerticalInset)) { _innerContainer.insets = kDefaultInset; [self _setTextContainerInset:kDefaultInset]; } } _innerContainer.exclusionPaths = _exclusionPaths; if (verticalForm) { CGAffineTransform trans = CGAffineTransformMakeTranslation(_innerContainer.size.width - self.bounds.size.width, 0); [_innerContainer.exclusionPaths enumerateObjectsUsingBlock:^(UIBezierPath *path, NSUInteger idx, BOOL *stop) { [path applyTransform:trans]; }]; } [self _keyboardChanged]; [self _commitUpdate]; } - (void)setLinePositionModifier:(id<YYTextLinePositionModifier>)linePositionModifier { if (_linePositionModifier == linePositionModifier) return; [self _setLinePositionModifier:linePositionModifier]; _innerContainer.linePositionModifier = linePositionModifier; [self _commitUpdate]; } - (void)setSelectedRange:(NSRange)selectedRange { if (NSEqualRanges(_selectedRange, selectedRange)) return; if (_markedTextRange) return; _state.typingAttributesOnce = NO; YYTextRange *range = [YYTextRange rangeWithRange:selectedRange]; range = [self _correctedTextRange:range]; [self _endTouchTracking]; _selectedTextRange = range; [self _updateSelectionView]; [self _setSelectedRange:range.asRange]; if (!_state.insideUndoBlock) { [self _resetUndoAndRedoStack]; } } - (void)setHighlightable:(BOOL)highlightable { if (_highlightable == highlightable) return; [self willChangeValueForKey:@"highlightable"]; _highlightable = highlightable; [self didChangeValueForKey:@"highlightable"]; [self _commitUpdate]; } - (void)setEditable:(BOOL)editable { if (_editable == editable) return; [self willChangeValueForKey:@"editable"]; _editable = editable; [self didChangeValueForKey:@"editable"]; if (!editable) { [self resignFirstResponder]; } } - (void)setSelectable:(BOOL)selectable { if (_selectable == selectable) return; [self willChangeValueForKey:@"selectable"]; _selectable = selectable; [self didChangeValueForKey:@"selectable"]; if (!selectable) { if (self.isFirstResponder) { [self resignFirstResponder]; } else { _state.selectedWithoutEdit = NO; [self _endTouchTracking]; [self _hideMenu]; [self _updateSelectionView]; } } } - (void)setClearsOnInsertion:(BOOL)clearsOnInsertion { if (_clearsOnInsertion == clearsOnInsertion) return; _clearsOnInsertion = clearsOnInsertion; if (clearsOnInsertion) { if (self.isFirstResponder) { self.selectedRange = NSMakeRange(0, _attributedText.length); } else { _state.clearsOnInsertionOnce = YES; } } } - (void)setDebugOption:(YYTextDebugOption *)debugOption { _containerView.debugOption = debugOption; } - (YYTextDebugOption *)debugOption { return _containerView.debugOption; } - (YYTextLayout *)textLayout { [self _updateIfNeeded]; return _innerLayout; } - (void)setPlaceholderText:(NSString *)placeholderText { if (_placeholderAttributedText.length > 0) { if (placeholderText.length > 0) { [((NSMutableAttributedString *)_placeholderAttributedText) replaceCharactersInRange:NSMakeRange(0, _placeholderAttributedText.length) withString:placeholderText]; } else { [((NSMutableAttributedString *)_placeholderAttributedText) replaceCharactersInRange:NSMakeRange(0, _placeholderAttributedText.length) withString:@""]; } ((NSMutableAttributedString *)_placeholderAttributedText).font = _placeholderFont; ((NSMutableAttributedString *)_placeholderAttributedText).color = _placeholderTextColor; } else { if (placeholderText.length > 0) { NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:placeholderText]; if (!_placeholderFont) _placeholderFont = _font; if (!_placeholderFont) _placeholderFont = [self _defaultFont]; if (!_placeholderTextColor) _placeholderTextColor = [self _defaultPlaceholderColor]; atr.font = _placeholderFont; atr.color = _placeholderTextColor; _placeholderAttributedText = atr; } } _placeholderText = [_placeholderAttributedText plainTextForRange:NSMakeRange(0, _placeholderAttributedText.length)]; [self _commitPlaceholderUpdate]; } - (void)setPlaceholderFont:(UIFont *)placeholderFont { _placeholderFont = placeholderFont; ((NSMutableAttributedString *)_placeholderAttributedText).font = _placeholderFont; [self _commitPlaceholderUpdate]; } - (void)setPlaceholderTextColor:(UIColor *)placeholderTextColor { _placeholderTextColor = placeholderTextColor; ((NSMutableAttributedString *)_placeholderAttributedText).color = _placeholderTextColor; [self _commitPlaceholderUpdate]; } - (void)setPlaceholderAttributedText:(NSAttributedString *)placeholderAttributedText { _placeholderAttributedText = placeholderAttributedText.mutableCopy; _placeholderText = [_placeholderAttributedText plainTextForRange:NSMakeRange(0, _placeholderAttributedText.length)]; _placeholderFont = _placeholderAttributedText.font; _placeholderTextColor = _placeholderAttributedText.color; [self _commitPlaceholderUpdate]; } #pragma mark - Override For Protect - (void)setMultipleTouchEnabled:(BOOL)multipleTouchEnabled { [super setMultipleTouchEnabled:NO]; // must not enabled } - (void)setContentInset:(UIEdgeInsets)contentInset { UIEdgeInsets oldInsets = self.contentInset; if (_insetModifiedByKeyboard) { _originalContentInset = contentInset; } else { [super setContentInset:contentInset]; BOOL changed = !UIEdgeInsetsEqualToEdgeInsets(oldInsets, contentInset); if (changed) { [self _updateInnerContainerSize]; [self _commitUpdate]; [self _commitPlaceholderUpdate]; } } } - (void)setScrollIndicatorInsets:(UIEdgeInsets)scrollIndicatorInsets { if (_insetModifiedByKeyboard) { _originalScrollIndicatorInsets = scrollIndicatorInsets; } else { [super setScrollIndicatorInsets:scrollIndicatorInsets]; } } - (void)setFrame:(CGRect)frame { CGSize oldSize = self.bounds.size; [super setFrame:frame]; CGSize newSize = self.bounds.size; BOOL changed = _innerContainer.isVerticalForm ? (oldSize.height != newSize.height) : (oldSize.width != newSize.width); if (changed) { [self _updateInnerContainerSize]; [self _commitUpdate]; } if (!CGSizeEqualToSize(oldSize, newSize)) { [self _commitPlaceholderUpdate]; } } - (void)setBounds:(CGRect)bounds { CGSize oldSize = self.bounds.size; [super setBounds:bounds]; CGSize newSize = self.bounds.size; BOOL changed = _innerContainer.isVerticalForm ? (oldSize.height != newSize.height) : (oldSize.width != newSize.width); if (changed) { [self _updateInnerContainerSize]; [self _commitUpdate]; } if (!CGSizeEqualToSize(oldSize, newSize)) { [self _commitPlaceholderUpdate]; } } - (void)tintColorDidChange { if ([self respondsToSelector:@selector(tintColor)]) { UIColor *color = self.tintColor; NSMutableDictionary *attrs = _highlightTextAttributes.mutableCopy; NSMutableDictionary *linkAttrs = _linkTextAttributes.mutableCopy; if (!linkAttrs) linkAttrs = @{}.mutableCopy; if (!color) { [attrs removeObjectForKey:NSForegroundColorAttributeName]; [attrs removeObjectForKey:(id)kCTForegroundColorAttributeName]; [linkAttrs setObject:[self _defaultTintColor] forKey:NSForegroundColorAttributeName]; [linkAttrs setObject:(id)[self _defaultTintColor].CGColor forKey:(id)kCTForegroundColorAttributeName]; } else { [attrs setObject:color forKey:NSForegroundColorAttributeName]; [attrs setObject:(id)color.CGColor forKey:(id)kCTForegroundColorAttributeName]; [linkAttrs setObject:color forKey:NSForegroundColorAttributeName]; [linkAttrs setObject:(id)color.CGColor forKey:(id)kCTForegroundColorAttributeName]; } self.highlightTextAttributes = attrs; _selectionView.color = color ? color : [self _defaultTintColor]; _linkTextAttributes = linkAttrs; [self _commitUpdate]; } } - (CGSize)sizeThatFits:(CGSize)size { if (!_verticalForm && size.width <= 0) size.width = YYTextContainerMaxSize.width; if (_verticalForm && size.height <= 0) size.height = YYTextContainerMaxSize.height; if ((!_verticalForm && size.width == self.bounds.size.width) || (_verticalForm && size.height == self.bounds.size.height)) { [self _updateIfNeeded]; if (!_verticalForm) { if (_containerView.bounds.size.height <= size.height) { return _containerView.bounds.size; } } else { if (_containerView.bounds.size.width <= size.width) { return _containerView.bounds.size; } } } if (!_verticalForm) { size.height = YYTextContainerMaxSize.height; } else { size.width = YYTextContainerMaxSize.width; } YYTextContainer *container = [_innerContainer copy]; container.size = size; YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:_innerText]; return layout.textBoundingSize; } #pragma mark - Override UIResponder - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self _updateIfNeeded]; UITouch *touch = touches.anyObject; CGPoint point = [touch locationInView:_containerView]; _touchBeganTime = _trackingTime = touch.timestamp; _touchBeganPoint = _trackingPoint = point; _trackingRange = _selectedTextRange; _state.trackingGrabber = NO; _state.trackingCaret = NO; _state.trackingPreSelect = NO; _state.trackingTouch = YES; _state.swallowTouch = YES; _state.touchMoved = NO; if (!self.isFirstResponder && !_state.selectedWithoutEdit && self.highlightable) { _highlight = [self _getHighlightAtPoint:point range:&_highlightRange]; _highlightLayout = nil; } if ((!self.selectable && !_highlight) || _state.ignoreTouchBegan) { _state.swallowTouch = NO; _state.trackingTouch = NO; } if (_state.trackingTouch) { [self _startLongPressTimer]; if (_highlight) { [self _showHighlightAnimated:NO]; } else { if ([_selectionView isGrabberContainsPoint:point]) { // track grabber self.panGestureRecognizer.enabled = NO; // disable scroll view [self _hideMenu]; _state.trackingGrabber = [_selectionView isStartGrabberContainsPoint:point] ? kStart : kEnd; _magnifierRangedOffset = [self _getMagnifierRangedOffset]; } else { if (_selectedTextRange.asRange.length == 0 && self.isFirstResponder) { if ([_selectionView isCaretContainsPoint:point]) { // track caret _state.trackingCaret = YES; self.panGestureRecognizer.enabled = NO; // disable scroll view } } } } [self _updateSelectionView]; } if (!_state.swallowTouch) [super touchesBegan:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [self _updateIfNeeded]; UITouch *touch = touches.anyObject; CGPoint point = [touch locationInView:_containerView]; _trackingTime = touch.timestamp; _trackingPoint = point; if (!_state.touchMoved) { _state.touchMoved = [self _getMoveDirection]; if (_state.touchMoved) [self _endLongPressTimer]; } _state.clearsOnInsertionOnce = NO; if (_state.trackingTouch) { BOOL showMagnifierCaret = NO; BOOL showMagnifierRanged = NO; if (_highlight) { YYTextHighlight *highlight = [self _getHighlightAtPoint:_trackingPoint range:NULL]; if (highlight == _highlight) { [self _showHighlightAnimated:YES]; } else { [self _hideHighlightAnimated:YES]; } } else { _trackingRange = _selectedTextRange; if (_state.trackingGrabber) { self.panGestureRecognizer.enabled = NO; [self _hideMenu]; [self _updateTextRangeByTrackingGrabber]; showMagnifierRanged = YES; } else if (_state.trackingPreSelect) { [self _updateTextRangeByTrackingPreSelect]; showMagnifierCaret = YES; } else if (_state.trackingCaret || _markedTextRange || self.isFirstResponder) { if (_state.trackingCaret || _state.touchMoved) { _state.trackingCaret = YES; [self _hideMenu]; if (_verticalForm) { if (_state.touchMoved == kTop || _state.touchMoved == kBottom) { self.panGestureRecognizer.enabled = NO; } } else { if (_state.touchMoved == kLeft || _state.touchMoved == kRight) { self.panGestureRecognizer.enabled = NO; } } [self _updateTextRangeByTrackingCaret]; if (_markedTextRange) { showMagnifierRanged = YES; } else { showMagnifierCaret = YES; } } } } [self _updateSelectionView]; if (showMagnifierCaret) [self _showMagnifierCaret]; if (showMagnifierRanged) [self _showMagnifierRanged]; } CGFloat autoScrollOffset = [self _getAutoscrollOffset]; if (_autoScrollOffset != autoScrollOffset) { if (fabs(autoScrollOffset) < fabs(_autoScrollOffset)) { _autoScrollAcceleration *= 0.5; } _autoScrollOffset = autoScrollOffset; if (_autoScrollOffset != 0 && _state.touchMoved) { [self _startAutoScrollTimer]; } } if (!_state.swallowTouch) [super touchesMoved:touches withEvent:event]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [self _updateIfNeeded]; UITouch *touch = touches.anyObject; CGPoint point = [touch locationInView:_containerView]; _trackingTime = touch.timestamp; _trackingPoint = point; if (!_state.touchMoved) { _state.touchMoved = [self _getMoveDirection]; } if (_state.trackingTouch) { [self _hideMagnifier]; if (_highlight) { if (_state.showingHighlight) { if (_highlight.tapAction) { CGRect rect = [_innerLayout rectForRange:[YYTextRange rangeWithRange:_highlightRange]]; rect = [self _convertRectFromLayout:rect]; _highlight.tapAction(self, _innerText, _highlightRange, rect); } else { BOOL shouldTap = YES; if ([self.delegate respondsToSelector:@selector(textView:shouldTapHighlight:inRange:)]) { shouldTap = [self.delegate textView:self shouldTapHighlight:_highlight inRange:_highlightRange]; } if (shouldTap && [self.delegate respondsToSelector:@selector(textView:didTapHighlight:inRange:rect:)]) { CGRect rect = [_innerLayout rectForRange:[YYTextRange rangeWithRange:_highlightRange]]; rect = [self _convertRectFromLayout:rect]; [self.delegate textView:self didTapHighlight:_highlight inRange:_highlightRange rect:rect]; } } [self _removeHighlightAnimated:YES]; } } else { if (_state.trackingCaret) { if (_state.touchMoved) { [self _updateTextRangeByTrackingCaret]; [self _showMenu]; } else { if (_state.showingMenu) [self _hideMenu]; else [self _showMenu]; } } else if (_state.trackingGrabber) { [self _updateTextRangeByTrackingGrabber]; [self _showMenu]; } else if (_state.trackingPreSelect) { [self _updateTextRangeByTrackingPreSelect]; if (_trackingRange.asRange.length > 0) { _state.selectedWithoutEdit = YES; [self _showMenu]; } else { [self performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0]; } } else if (_state.deleteConfirm || _markedTextRange) { [self _updateTextRangeByTrackingCaret]; [self _hideMenu]; } else { if (!_state.touchMoved) { if (_state.selectedWithoutEdit) { _state.selectedWithoutEdit = NO; [self _hideMenu]; } else { if (self.isFirstResponder) { YYTextRange *_oldRange = _trackingRange; [self _updateTextRangeByTrackingCaret]; if ([_oldRange isEqual:_trackingRange]) { if (_state.showingMenu) [self _hideMenu]; else [self _showMenu]; } else { [self _hideMenu]; } } else { [self _hideMenu]; if (_state.clearsOnInsertionOnce) { _state.clearsOnInsertionOnce = NO; _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(0, _innerText.length)]; [self _setSelectedRange:_selectedTextRange.asRange]; } else { [self _updateTextRangeByTrackingCaret]; } [self performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0]; } } } } } if (_trackingRange && (![_trackingRange isEqual:_selectedTextRange] || _state.trackingPreSelect)) { if (![_trackingRange isEqual:_selectedTextRange]) { [_inputDelegate selectionWillChange:self]; _selectedTextRange = _trackingRange; [_inputDelegate selectionDidChange:self]; [self _updateAttributesHolder]; [self _updateOuterProperties]; } if (!_state.trackingGrabber && !_state.trackingPreSelect) { [self _scrollRangeToVisible:_selectedTextRange]; } } [self _endTouchTracking]; } if (!_state.swallowTouch) [super touchesEnded:touches withEvent:event]; } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [self _endTouchTracking]; [self _hideMenu]; if (!_state.swallowTouch) [super touchesCancelled:touches withEvent:event]; } - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake && _allowsUndoAndRedo) { if (![UIApplication isAppExtension]) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wundeclared-selector" [self performSelector:@selector(_showUndoRedoAlert)]; #pragma clang diagnostic pop } } else { [super motionEnded:motion withEvent:event]; } } - (BOOL)canBecomeFirstResponder { if (!self.isSelectable) return NO; if (!self.isEditable) return NO; if (_state.ignoreFirstResponder) return NO; if ([self.delegate respondsToSelector:@selector(textViewShouldBeginEditing:)]) { if (![self.delegate textViewShouldBeginEditing:self]) return NO; } return YES; } - (BOOL)becomeFirstResponder { BOOL isFirstResponder = self.isFirstResponder; if (isFirstResponder) return YES; BOOL shouldDetectData = [self _shouldDetectText]; BOOL become = [super becomeFirstResponder]; if (!isFirstResponder && become) { [self _endTouchTracking]; [self _hideMenu]; _state.selectedWithoutEdit = NO; if (shouldDetectData != [self _shouldDetectText]) { [self _update]; } [self _updateIfNeeded]; [self _updateSelectionView]; [self performSelector:@selector(_scrollSelectedRangeToVisible) withObject:nil afterDelay:0]; if ([self.delegate respondsToSelector:@selector(textViewDidBeginEditing:)]) { [self.delegate textViewDidBeginEditing:self]; } [[NSNotificationCenter defaultCenter] postNotificationName:YYTextViewTextDidBeginEditingNotification object:self]; } return become; } - (BOOL)canResignFirstResponder { if (!self.isFirstResponder) return YES; if ([self.delegate respondsToSelector:@selector(textViewShouldEndEditing:)]) { if (![self.delegate textViewShouldEndEditing:self]) return NO; } return YES; } - (BOOL)resignFirstResponder { BOOL isFirstResponder = self.isFirstResponder; if (!isFirstResponder) return YES; BOOL resign = [super resignFirstResponder]; if (resign) { if (_markedTextRange) { _markedTextRange = nil; [self _parseText]; [self _setText:[_innerText plainTextForRange:NSMakeRange(0, _innerText.length)]]; } _state.selectedWithoutEdit = NO; if ([self _shouldDetectText]) { [self _update]; } [self _endTouchTracking]; [self _hideMenu]; [self _updateIfNeeded]; [self _updateSelectionView]; [self _restoreInsetsAnimated:YES]; if ([self.delegate respondsToSelector:@selector(textViewDidEndEditing:)]) { [self.delegate textViewDidEndEditing:self]; } [[NSNotificationCenter defaultCenter] postNotificationName:YYTextViewTextDidEndEditingNotification object:self]; } return resign; } - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { /* ------------------------------------------------------ Default menu actions list: cut: Cut copy: Copy select: Select selectAll: Select All paste: Paste delete: Delete _promptForReplace: Replace... _transliterateChinese: _showTextStyleOptions: _define: Define _addShortcut: Add... _accessibilitySpeak: Speak _accessibilitySpeakLanguageSelection: Speak... _accessibilityPauseSpeaking: Pause Speak makeTextWritingDirectionRightToLeft: makeTextWritingDirectionLeftToRight: ------------------------------------------------------ Default attribute modifier list: toggleBoldface: toggleItalics: toggleUnderline: increaseSize: decreaseSize: */ if (_selectedTextRange.asRange.length == 0) { if (action == @selector(select:) || action == @selector(selectAll:)) { return _innerText.length > 0; } if (action == @selector(paste:)) { return [self _isPasteboardContainsValidValue]; } } else { if (action == @selector(cut:)) { return self.isFirstResponder && self.editable; } if (action == @selector(copy:)) { return YES; } if (action == @selector(selectAll:)) { return _selectedTextRange.asRange.length < _innerText.length; } if (action == @selector(paste:)) { return self.isFirstResponder && self.editable && [self _isPasteboardContainsValidValue]; } NSString *selString = NSStringFromSelector(action); if ([selString hasSuffix:@"define:"] && [selString hasPrefix:@"_"]) { return [self _getRootViewController] != nil; } } return NO; } - (void)reloadInputViews { [super reloadInputViews]; if (_markedTextRange) { [self unmarkText]; } } #pragma mark - Override NSObject(UIResponderStandardEditActions) - (void)cut:(id)sender { [self _endTouchTracking]; if (_selectedTextRange.asRange.length == 0) return; [self _copySelectedTextToPasteboard]; [self _saveToUndoStack]; [self _resetRedoStack]; [self replaceRange:_selectedTextRange withText:@""]; } - (void)copy:(id)sender { [self _endTouchTracking]; [self _copySelectedTextToPasteboard]; } - (void)paste:(id)sender { [self _endTouchTracking]; UIPasteboard *p = [UIPasteboard generalPasteboard]; NSAttributedString *atr = nil; if (_allowsPasteAttributedString) { atr = p.attributedString; if (atr.length == 0) atr = nil; } if (!atr && _allowsPasteImage) { UIImage *img = nil; if (p.GIFData) { img = [YYImage imageWithData:p.GIFData scale:kScreenScale]; } if (!img && p.PNGData) { img = [YYImage imageWithData:p.PNGData scale:kScreenScale]; } if (!img && p.WEBPData) { img = [YYImage imageWithData:p.WEBPData scale:kScreenScale]; } if (!img) { img = p.image; } if (!img && p.imageData) { img = [UIImage imageWithData:p.imageData scale:kScreenScale]; } if (img && img.size.width > 1 && img.size.height > 1) { id content = img; if ([img conformsToProtocol:@protocol(YYAnimatedImage)]) { id<YYAnimatedImage> ani = (id)img; if (ani.animatedImageFrameCount > 1) { YYAnimatedImageView *aniView = [[YYAnimatedImageView alloc] initWithImage:img]; if (aniView) { content = aniView; } } } if ([content isKindOfClass:[UIImage class]] && img.images.count > 1) { UIImageView *imgView = [UIImageView new]; imgView.image = img; imgView.frame = CGRectMake(0, 0, img.size.width, img.size.height); if (imgView) { content = imgView; } } NSMutableAttributedString *attText = [NSAttributedString attachmentStringWithContent:content contentMode:UIViewContentModeScaleToFill width:img.size.width ascent:img.size.height descent:0]; NSDictionary *attrs = _typingAttributesHolder.attributes; if (attrs) [attText addAttributes:attrs range:NSMakeRange(0, attText.length)]; atr = attText; } } if (atr) { NSUInteger endPosition = _selectedTextRange.start.offset + atr.length; NSMutableAttributedString *text = _innerText.mutableCopy; [text replaceCharactersInRange:_selectedTextRange.asRange withAttributedString:atr]; self.attributedText = text; YYTextPosition *pos = [self _correctedTextPosition:[YYTextPosition positionWithOffset:endPosition]]; YYTextRange *range = [_innerLayout textRangeByExtendingPosition:pos]; range = [self _correctedTextRange:range]; if (range) { self.selectedRange = NSMakeRange(range.end.offset, 0); } } else { NSString *string = p.string; if (string.length > 0) { [self _saveToUndoStack]; [self _resetRedoStack]; [self replaceRange:_selectedTextRange withText:string]; } } } - (void)select:(id)sender { [self _endTouchTracking]; if (_selectedTextRange.asRange.length > 0 || _innerText.length == 0) return; YYTextRange *newRange = [self _getClosestTokenRangeAtPosition:_selectedTextRange.start]; if (newRange.asRange.length > 0) { [_inputDelegate selectionWillChange:self]; _selectedTextRange = newRange; [_inputDelegate selectionDidChange:self]; } [self _updateIfNeeded]; [self _updateOuterProperties]; [self _updateSelectionView]; [self _hideMenu]; [self _showMenu]; } - (void)selectAll:(id)sender { _trackingRange = nil; [_inputDelegate selectionWillChange:self]; _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(0, _innerText.length)]; [_inputDelegate selectionDidChange:self]; [self _updateIfNeeded]; [self _updateOuterProperties]; [self _updateSelectionView]; [self _hideMenu]; [self _showMenu]; } - (void)_define:(id)sender { [self _hideMenu]; NSString *string = [_innerText plainTextForRange:_selectedTextRange.asRange]; if (string.length == 0) return; BOOL resign = [self resignFirstResponder]; if (!resign) return; UIReferenceLibraryViewController* ref = [[UIReferenceLibraryViewController alloc] initWithTerm:string]; ref.view.backgroundColor = [UIColor whiteColor]; [[self _getRootViewController] presentViewController:ref animated:YES completion:^{}]; } #pragma mark - Overrice NSObject(NSKeyValueObservingCustomization) + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { static NSSet *keys = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ keys = [NSSet setWithArray:@[ @"text", @"font", @"textColor", @"textAlignment", @"dataDetectorTypes", @"linkTextAttributes", @"highlightTextAttributes", @"textParser", @"attributedText", @"textVerticalAlignment", @"textContainerInset", @"exclusionPaths", @"verticalForm", @"linePositionModifier", @"selectedRange", @"typingAttributes" ]]; }); if ([keys containsObject:key]) { return NO; } return [super automaticallyNotifiesObserversForKey:key]; } #pragma mark - @protocol NSCoding - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; [self _initTextView]; self.attributedText = [aDecoder decodeObjectForKey:@"attributedText"]; self.selectedRange = ((NSValue *)[aDecoder decodeObjectForKey:@"selectedRange"]).rangeValue; self.textVerticalAlignment = [aDecoder decodeIntegerForKey:@"textVerticalAlignment"]; self.dataDetectorTypes = [aDecoder decodeIntegerForKey:@"dataDetectorTypes"]; self.textContainerInset = ((NSValue *)[aDecoder decodeObjectForKey:@"textContainerInset"]).UIEdgeInsetsValue; self.exclusionPaths = [aDecoder decodeObjectForKey:@"exclusionPaths"]; self.verticalForm = [aDecoder decodeBoolForKey:@"verticalForm"]; return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [super encodeWithCoder:aCoder]; [aCoder encodeObject:self.attributedText forKey:@"attributedText"]; [aCoder encodeObject:[NSValue valueWithRange:self.selectedRange] forKey:@"selectedRange"]; [aCoder encodeInteger:self.textVerticalAlignment forKey:@"textVerticalAlignment"]; [aCoder encodeInteger:self.dataDetectorTypes forKey:@"dataDetectorTypes"]; [aCoder encodeUIEdgeInsets:self.textContainerInset forKey:@"textContainerInset"]; [aCoder encodeObject:self.exclusionPaths forKey:@"exclusionPaths"]; [aCoder encodeBool:self.verticalForm forKey:@"verticalForm"]; } #pragma mark - @protocol UIScrollViewDelegate - (id<YYTextViewDelegate>)delegate { return _outerDelegate; } - (void)setDelegate:(id<YYTextViewDelegate>)delegate { _outerDelegate = delegate; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [[YYTextEffectWindow sharedWindow] hideSelectionDot:_selectionView]; if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewDidScroll:scrollView]; } } - (void)scrollViewDidZoom:(UIScrollView *)scrollView { if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewDidZoom:scrollView]; } } - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewWillBeginDragging:scrollView]; } } - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset]; } } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { if (!decelerate) { [[YYTextEffectWindow sharedWindow] showSelectionDot:_selectionView]; } if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewDidEndDragging:scrollView willDecelerate:decelerate]; } } - (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView { if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewWillBeginDecelerating:scrollView]; } } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { [[YYTextEffectWindow sharedWindow] showSelectionDot:_selectionView]; if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewDidEndDecelerating:scrollView]; } } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewDidEndScrollingAnimation:scrollView]; } } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { if ([_outerDelegate respondsToSelector:_cmd]) { return [_outerDelegate viewForZoomingInScrollView:scrollView]; } else { return nil; } } - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{ if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewWillBeginZooming:scrollView withView:view]; } } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale { if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewDidEndZooming:scrollView withView:view atScale:scale]; } } - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView { if ([_outerDelegate respondsToSelector:_cmd]) { return [_outerDelegate scrollViewShouldScrollToTop:scrollView]; } return YES; } - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView { if ([_outerDelegate respondsToSelector:_cmd]) { [_outerDelegate scrollViewDidScrollToTop:scrollView]; } } #pragma mark - @protocol YYTextKeyboardObserver - (void)keyboardChangedWithTransition:(YYTextKeyboardTransition)transition { [self _keyboardChanged]; } #pragma mark - @protocol UIALertViewDelegate - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *title = [alertView buttonTitleAtIndex:buttonIndex]; if (title.length == 0) return; NSArray *strings = [self _localizedUndoStrings]; if ([title isEqualToString:strings[1]] || [title isEqualToString:strings[2]]) { [self _redo]; } else if ([title isEqualToString:strings[3]] || [title isEqualToString:strings[4]]) { [self _undo]; } [self _restoreFirstResponderAfterUndoAlert]; } #pragma mark - @protocol UIKeyInput - (BOOL)hasText { return _innerText.length > 0; } - (void)insertText:(NSString *)text { if (text.length == 0) return; if (!NSEqualRanges(_lastTypeRange, _selectedTextRange.asRange)) { [self _saveToUndoStack]; [self _resetRedoStack]; } [self replaceRange:_selectedTextRange withText:text]; } - (void)deleteBackward { [self _updateIfNeeded]; NSRange range = _selectedTextRange.asRange; if (range.location == 0 && range.length == 0) return; _state.typingAttributesOnce = NO; // test if there's 'TextBinding' before the caret if (!_state.deleteConfirm && range.length == 0 && range.location > 0) { NSRange effectiveRange; YYTextBinding *binding = [_innerText attribute:YYTextBindingAttributeName atIndex:range.location - 1 longestEffectiveRange:&effectiveRange inRange:NSMakeRange(0, _innerText.length)]; if (binding && binding.deleteConfirm) { _state.deleteConfirm = YES; [_inputDelegate selectionWillChange:self]; _selectedTextRange = [YYTextRange rangeWithRange:effectiveRange]; _selectedTextRange = [self _correctedTextRange:_selectedTextRange]; [_inputDelegate selectionDidChange:self]; [self _updateOuterProperties]; [self _updateSelectionView]; return; } } _state.deleteConfirm = NO; if (range.length == 0) { YYTextRange *extendRange = [_innerLayout textRangeByExtendingPosition:_selectedTextRange.end inDirection:UITextLayoutDirectionLeft offset:1]; if ([self _isTextRangeValid:extendRange]) { range = extendRange.asRange; } } if (!NSEqualRanges(_lastTypeRange, _selectedTextRange.asRange)) { [self _saveToUndoStack]; [self _resetRedoStack]; } [self replaceRange:[YYTextRange rangeWithRange:range] withText:@""]; } #pragma mark - @protocol UITextInput - (void)setInputDelegate:(id<UITextInputDelegate>)inputDelegate { _inputDelegate = inputDelegate; } - (void)setSelectedTextRange:(YYTextRange *)selectedTextRange { if (!selectedTextRange) return; selectedTextRange = [self _correctedTextRange:selectedTextRange]; if ([selectedTextRange isEqual:_selectedTextRange]) return; [self _updateIfNeeded]; [self _endTouchTracking]; [self _hideMenu]; _state.deleteConfirm = NO; _state.typingAttributesOnce = NO; [_inputDelegate selectionWillChange:self]; _selectedTextRange = selectedTextRange; _lastTypeRange = _selectedTextRange.asRange; [_inputDelegate selectionDidChange:self]; [self _updateOuterProperties]; [self _updateSelectionView]; if (self.isFirstResponder) { [self _scrollRangeToVisible:_selectedTextRange]; } } - (void)setMarkedTextStyle:(NSDictionary *)markedTextStyle { _markedTextStyle = markedTextStyle.copy; } /* Replace current markedText with the new markedText @param markedText New marked text. @param selectedRange The range from the '_markedTextRange' */ - (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRange { [self _updateIfNeeded]; [self _endTouchTracking]; [self _hideMenu]; if ([self.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) { NSRange range = _markedTextRange ? _markedTextRange.asRange : NSMakeRange(_selectedTextRange.end.offset, 0); BOOL should = [self.delegate textView:self shouldChangeTextInRange:range replacementText:markedText]; if (!should) return; } if (!NSEqualRanges(_lastTypeRange, _selectedTextRange.asRange)) { [self _saveToUndoStack]; [self _resetRedoStack]; } BOOL needApplyHolderAttribute = NO; if (_innerText.length > 0 && _markedTextRange) { [self _updateAttributesHolder]; } else { needApplyHolderAttribute = YES; } if (_selectedTextRange.asRange.length > 0) { [self replaceRange:_selectedTextRange withText:@""]; } [_inputDelegate textWillChange:self]; [_inputDelegate selectionWillChange:self]; if (!markedText) markedText = @""; if (_markedTextRange == nil) { _markedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_selectedTextRange.end.offset, markedText.length)]; [_innerText replaceCharactersInRange:NSMakeRange(_selectedTextRange.end.offset, 0) withString:markedText]; _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_selectedTextRange.start.offset + selectedRange.location, selectedRange.length)]; } else { _markedTextRange = [self _correctedTextRange:_markedTextRange]; [_innerText replaceCharactersInRange:_markedTextRange.asRange withString:markedText]; _markedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_markedTextRange.start.offset, markedText.length)]; _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_markedTextRange.start.offset + selectedRange.location, selectedRange.length)]; } _selectedTextRange = [self _correctedTextRange:_selectedTextRange]; _markedTextRange = [self _correctedTextRange:_markedTextRange]; if (_markedTextRange.asRange.length == 0) { _markedTextRange = nil; } else { if (needApplyHolderAttribute) { [_innerText setAttributes:_typingAttributesHolder.attributes range:_markedTextRange.asRange]; } [_innerText removeDiscontinuousAttributesInRange:_markedTextRange.asRange]; } [_inputDelegate selectionDidChange:self]; [_inputDelegate textDidChange:self]; [self _updateOuterProperties]; [self _updateLayout]; [self _updateSelectionView]; [self _scrollRangeToVisible:_selectedTextRange]; if ([self.delegate respondsToSelector:@selector(textViewDidChange:)]) { [self.delegate textViewDidChange:self]; } [[NSNotificationCenter defaultCenter] postNotificationName:YYTextViewTextDidChangeNotification object:self]; _lastTypeRange = _selectedTextRange.asRange; } - (void)unmarkText { _markedTextRange = nil; [self _endTouchTracking]; [self _hideMenu]; if ([self _parseText]) _state.needUpdate = YES; [self _updateIfNeeded]; [self _updateOuterProperties]; [self _updateSelectionView]; [self _scrollRangeToVisible:_selectedTextRange]; } - (void)replaceRange:(YYTextRange *)range withText:(NSString *)text { if (!range) return; if (!text) text = @""; if (range.asRange.length == 0 && text.length == 0) return; range = [self _correctedTextRange:range]; if ([self.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) { BOOL should = [self.delegate textView:self shouldChangeTextInRange:range.asRange replacementText:text]; if (!should) return; } BOOL useInnerAttributes = NO; if (_innerText.length > 0) { if (range.start.offset == 0 && range.end.offset == _innerText.length) { if (text.length == 0) { NSMutableDictionary *attrs = [_innerText attributesAtIndex:0].mutableCopy; [attrs removeObjectsForKeys:[NSMutableAttributedString allDiscontinuousAttributeKeys]]; _typingAttributesHolder.attributes = attrs; } } } else { // no text useInnerAttributes = YES; } BOOL applyTypingAttributes = NO; if (_state.typingAttributesOnce) { _state.typingAttributesOnce = NO; if (!useInnerAttributes) { if (range.asRange.length == 0 && text.length > 0) { applyTypingAttributes = YES; } } } _state.selectedWithoutEdit = NO; _state.deleteConfirm = NO; [self _endTouchTracking]; [self _hideMenu]; [self _replaceRange:range withText:text notifyToDelegate:YES]; if (useInnerAttributes) { [_innerText setAttributes:_typingAttributesHolder.attributes]; } else if (applyTypingAttributes) { NSRange newRange = NSMakeRange(range.asRange.location, text.length); [_typingAttributesHolder.attributes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [_innerText setAttribute:key value:obj range:newRange]; }]; } [self _parseText]; [self _updateOuterProperties]; [self _update]; if (self.isFirstResponder) { [self _scrollRangeToVisible:_selectedTextRange]; } if ([self.delegate respondsToSelector:@selector(textViewDidChange:)]) { [self.delegate textViewDidChange:self]; } [[NSNotificationCenter defaultCenter] postNotificationName:YYTextViewTextDidChangeNotification object:self]; _lastTypeRange = _selectedTextRange.asRange; } - (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection forRange:(YYTextRange *)range { if (!range) return; range = [self _correctedTextRange:range]; [_innerText setBaseWritingDirection:(NSWritingDirection)writingDirection range:range.asRange]; [self _commitUpdate]; } - (NSString *)textInRange:(YYTextRange *)range { range = [self _correctedTextRange:range]; if (!range) return @""; return [_innerText.string substringWithRange:range.asRange]; } - (UITextWritingDirection)baseWritingDirectionForPosition:(YYTextPosition *)position inDirection:(UITextStorageDirection)direction { [self _updateIfNeeded]; position = [self _correctedTextPosition:position]; if (!position) return UITextWritingDirectionNatural; if (_innerText.length == 0) return UITextWritingDirectionNatural; NSUInteger idx = position.offset; if (idx == _innerText.length) idx--; NSDictionary *attrs = [_innerText attributesAtIndex:idx]; CTParagraphStyleRef paraStyle = (__bridge CFTypeRef)(attrs[NSParagraphStyleAttributeName]); if (paraStyle) { CTWritingDirection baseWritingDirection; if (CTParagraphStyleGetValueForSpecifier(paraStyle, kCTParagraphStyleSpecifierBaseWritingDirection, sizeof(CTWritingDirection), &baseWritingDirection)) { return (UITextWritingDirection)baseWritingDirection; } } return UITextWritingDirectionNatural; } - (YYTextPosition *)beginningOfDocument { return [YYTextPosition positionWithOffset:0]; } - (YYTextPosition *)endOfDocument { return [YYTextPosition positionWithOffset:_innerText.length]; } - (YYTextPosition *)positionFromPosition:(YYTextPosition *)position offset:(NSInteger)offset { if (offset == 0) return position; NSUInteger location = position.offset; NSInteger newLocation = (NSInteger)location + offset; if (newLocation < 0 || newLocation > _innerText.length) return nil; if (newLocation != 0 && newLocation != _innerText.length) { // fix emoji [self _updateIfNeeded]; YYTextRange *extendRange = [_innerLayout textRangeByExtendingPosition:[YYTextPosition positionWithOffset:newLocation]]; if (extendRange.asRange.length > 0) { if (offset < 0) { newLocation = extendRange.start.offset; } else { newLocation = extendRange.end.offset; } } } YYTextPosition *p = [YYTextPosition positionWithOffset:newLocation]; return [self _correctedTextPosition:p]; } - (YYTextPosition *)positionFromPosition:(YYTextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { [self _updateIfNeeded]; YYTextRange *range = [_innerLayout textRangeByExtendingPosition:position inDirection:direction offset:offset]; BOOL forward; if (_innerContainer.isVerticalForm) { forward = direction == UITextLayoutDirectionLeft || direction == UITextLayoutDirectionDown; } else { forward = direction == UITextLayoutDirectionDown || direction == UITextLayoutDirectionRight; } if (!forward && offset < 0) { forward = -forward; } YYTextPosition *newPosition = forward ? range.end : range.start; if (newPosition.offset > _innerText.length) { newPosition = [YYTextPosition positionWithOffset:_innerText.length affinity:YYTextAffinityBackward]; } return [self _correctedTextPosition:newPosition]; } - (YYTextRange *)textRangeFromPosition:(YYTextPosition *)fromPosition toPosition:(YYTextPosition *)toPosition { return [YYTextRange rangeWithStart:fromPosition end:toPosition]; } - (NSComparisonResult)comparePosition:(YYTextPosition *)position toPosition:(YYTextPosition *)other { return [position compare:other]; } - (NSInteger)offsetFromPosition:(YYTextPosition *)from toPosition:(YYTextPosition *)toPosition { return toPosition.offset - from.offset; } - (YYTextPosition *)positionWithinRange:(YYTextRange *)range farthestInDirection:(UITextLayoutDirection)direction { NSRange nsRange = range.asRange; if (direction == UITextLayoutDirectionLeft | direction == UITextLayoutDirectionUp) { return [YYTextPosition positionWithOffset:nsRange.location]; } else { return [YYTextPosition positionWithOffset:nsRange.location + nsRange.length affinity:YYTextAffinityBackward]; } } - (YYTextRange *)characterRangeByExtendingPosition:(YYTextPosition *)position inDirection:(UITextLayoutDirection)direction { [self _updateIfNeeded]; YYTextRange *range = [_innerLayout textRangeByExtendingPosition:position inDirection:direction offset:1]; return [self _correctedTextRange:range]; } - (YYTextPosition *)closestPositionToPoint:(CGPoint)point { [self _updateIfNeeded]; point = [self _convertPointToLayout:point]; YYTextPosition *position = [_innerLayout closestPositionToPoint:point]; return [self _correctedTextPosition:position]; } - (YYTextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(YYTextRange *)range { YYTextPosition *pos = (id)[self closestPositionToPoint:point]; if (!pos) return nil; range = [self _correctedTextRange:range]; if ([pos compare:range.start] == NSOrderedAscending) { pos = range.start; } else if ([pos compare:range.end] == NSOrderedDescending) { pos = range.end; } return pos; } - (YYTextRange *)characterRangeAtPoint:(CGPoint)point { [self _updateIfNeeded]; point = [self _convertPointToLayout:point]; YYTextRange *r = [_innerLayout closestTextRangeAtPoint:point]; return [self _correctedTextRange:r]; } - (CGRect)firstRectForRange:(YYTextRange *)range { [self _updateIfNeeded]; CGRect rect = [_innerLayout firstRectForRange:range]; if (CGRectIsNull(rect)) rect = CGRectZero; return [self _convertRectFromLayout:rect]; } - (CGRect)caretRectForPosition:(YYTextPosition *)position { [self _updateIfNeeded]; CGRect caretRect = [_innerLayout caretRectForPosition:position]; if (!CGRectIsNull(caretRect)) { caretRect = [self _convertRectFromLayout:caretRect]; caretRect = CGRectStandardize(caretRect); if (_verticalForm) { if (caretRect.size.height == 0) { caretRect.size.height = 2; caretRect.origin.y -= 2 * 0.5; } if (caretRect.origin.y < 0) { caretRect.origin.y = 0; } else if (caretRect.origin.y + caretRect.size.height > self.bounds.size.height) { caretRect.origin.y = self.bounds.size.height - caretRect.size.height; } } else { if (caretRect.size.width == 0) { caretRect.size.width = 2; caretRect.origin.x -= 2 * 0.5; } if (caretRect.origin.x < 0) { caretRect.origin.x = 0; } else if (caretRect.origin.x + caretRect.size.width > self.bounds.size.width) { caretRect.origin.x = self.bounds.size.width - caretRect.size.width; } } return CGRectPixelRound(caretRect); } return CGRectZero; } - (NSArray *)selectionRectsForRange:(YYTextRange *)range { [self _updateIfNeeded]; NSArray *rects = [_innerLayout selectionRectsForRange:range]; [rects enumerateObjectsUsingBlock:^(YYTextSelectionRect *rect, NSUInteger idx, BOOL *stop) { rect.rect = [self _convertRectFromLayout:rect.rect]; }]; return rects; } #pragma mark - @protocol UITextInput optional - (UITextStorageDirection)selectionAffinity { if (_selectedTextRange.end.affinity == YYTextAffinityForward) { return UITextStorageDirectionForward; } else { return UITextStorageDirectionBackward; } } - (void)setSelectionAffinity:(UITextStorageDirection)selectionAffinity { _selectedTextRange = [YYTextRange rangeWithRange:_selectedTextRange.asRange affinity:selectionAffinity == UITextStorageDirectionForward ? YYTextAffinityForward : YYTextAffinityBackward]; [self _updateSelectionView]; } - (NSDictionary *)textStylingAtPosition:(YYTextPosition *)position inDirection:(UITextStorageDirection)direction { if (!position) return nil; if (_innerText.length == 0) return _typingAttributesHolder.attributes; NSDictionary *attrs = nil; if (0 <= position.offset && position.offset <= _innerText.length) { NSUInteger ofs = position.offset; if (position.offset == _innerText.length || direction == UITextStorageDirectionBackward) { ofs--; } attrs = [_innerText attributesAtIndex:ofs effectiveRange:NULL]; } return attrs; } - (YYTextPosition *)positionWithinRange:(YYTextRange *)range atCharacterOffset:(NSInteger)offset { if (!range) return nil; if (offset < range.start.offset || offset > range.end.offset) return nil; if (offset == range.start.offset) return range.start; else if (offset == range.end.offset) return range.end; else return [YYTextPosition positionWithOffset:offset]; } - (NSInteger)characterOffsetOfPosition:(YYTextPosition *)position withinRange:(YYTextRange *)range { return position ? position.offset : NSNotFound; } @end @interface YYTextView(IBInspectableProperties) @end @implementation YYTextView(IBInspectableProperties) - (BOOL)fontIsBold_:(UIFont *)font { if (![font respondsToSelector:@selector(fontDescriptor)]) return NO; return (font.fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold) > 0; } - (UIFont *)boldFont_:(UIFont *)font { if (![font respondsToSelector:@selector(fontDescriptor)]) return font; return [UIFont fontWithDescriptor:[font.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:font.pointSize]; } - (UIFont *)normalFont_:(UIFont *)font { if (![font respondsToSelector:@selector(fontDescriptor)]) return font; return [UIFont fontWithDescriptor:[font.fontDescriptor fontDescriptorWithSymbolicTraits:0] size:font.pointSize]; } - (void)setFontName_:(NSString *)fontName { if (!fontName) return; UIFont *font = self.font; if (!font) font = [self _defaultFont]; if ((fontName.length == 0 || [fontName.lowercaseString isEqualToString:@"system"]) && ![self fontIsBold_:font]) { font = [UIFont systemFontOfSize:font.pointSize]; } else if ([fontName.lowercaseString isEqualToString:@"system bold"]) { font = [UIFont boldSystemFontOfSize:font.pointSize]; } else { if ([self fontIsBold_:font] && ![fontName.lowercaseString containsString:@"bold"]) { font = [UIFont fontWithName:fontName size:font.pointSize]; font = [self boldFont_:font]; } else { font = [UIFont fontWithName:fontName size:font.pointSize]; } } if (font) self.font = font; } - (void)setFontSize_:(CGFloat)fontSize { if (fontSize <= 0) return; UIFont *font = self.font; if (!font) font = [self _defaultFont]; if (!font) font = [self _defaultFont]; font = [font fontWithSize:fontSize]; if (font) self.font = font; } - (void)setFontIsBold_:(BOOL)fontBold { UIFont *font = self.font; if (!font) font = [self _defaultFont]; if ([self fontIsBold_:font] == fontBold) return; if (fontBold) { font = [self boldFont_:font]; } else { font = [self normalFont_:font]; } if (font) self.font = font; } - (void)setPlaceholderFontName_:(NSString *)fontName { if (!fontName) return; UIFont *font = self.placeholderFont; if (!font) font = [self _defaultFont]; if ((fontName.length == 0 || [fontName.lowercaseString isEqualToString:@"system"]) && ![self fontIsBold_:font]) { font = [UIFont systemFontOfSize:font.pointSize]; } else if ([fontName.lowercaseString isEqualToString:@"system bold"]) { font = [UIFont boldSystemFontOfSize:font.pointSize]; } else { if ([self fontIsBold_:font] && ![fontName.lowercaseString containsString:@"bold"]) { font = [UIFont fontWithName:fontName size:font.pointSize]; font = [self boldFont_:font]; } else { font = [UIFont fontWithName:fontName size:font.pointSize]; } } if (font) self.placeholderFont = font; } - (void)setPlaceholderFontSize_:(CGFloat)fontSize { if (fontSize <= 0) return; UIFont *font = self.placeholderFont; if (!font) font = [self _defaultFont]; font = [font fontWithSize:fontSize]; if (font) self.placeholderFont = font; } - (void)setPlaceholderFontIsBold_:(BOOL)fontBold { UIFont *font = self.placeholderFont; if (!font) font = [self _defaultFont]; if ([self fontIsBold_:font] == fontBold) return; if (fontBold) { font = [self boldFont_:font]; } else { font = [self normalFont_:font]; } if (font) self.placeholderFont = font; } - (void)setInsetTop_:(CGFloat)textInsetTop { UIEdgeInsets insets = self.textContainerInset; insets.top = textInsetTop; self.textContainerInset = insets; } - (void)setInsetBottom_:(CGFloat)textInsetBottom { UIEdgeInsets insets = self.textContainerInset; insets.bottom = textInsetBottom; self.textContainerInset = insets; } - (void)setInsetLeft_:(CGFloat)textInsetLeft { UIEdgeInsets insets = self.textContainerInset; insets.left = textInsetLeft; self.textContainerInset = insets; } - (void)setInsetRight_:(CGFloat)textInsetRight { UIEdgeInsets insets = self.textContainerInset; insets.right = textInsetRight; self.textContainerInset = insets; } - (void)setDebugEnabled_:(BOOL)enabled { if (!enabled) { self.debugOption = nil; } else { YYTextDebugOption *debugOption = [YYTextDebugOption new]; debugOption.baselineColor = [UIColor redColor]; debugOption.CTFrameBorderColor = [UIColor redColor]; debugOption.CTLineFillColor = [UIColor colorWithRed:0.000 green:0.463 blue:1.000 alpha:0.180]; debugOption.CGGlyphBorderColor = [UIColor colorWithRed:1.000 green:0.524 blue:0.000 alpha:0.200]; self.debugOption = debugOption; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/YYTextView.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
34,374
```objective-c // // YYTextUtilities.h // YYKit <path_to_url // // Created by ibireme on 15/4/6. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYKitMacro.h> #else #import "YYKitMacro.h" #endif YY_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN /** Whether the character is 'line break char': U+000D (\\r or CR) U+2028 (Unicode line separator) U+000A (\\n or LF) U+2029 (Unicode paragraph separator) @param c A character @return YES or NO. */ static inline BOOL YYTextIsLinebreakChar(unichar c) { switch (c) { case 0x000D: case 0x2028: case 0x000A: case 0x2029: return YES; default: return NO; } } /** Whether the string is a 'line break': U+000D (\\r or CR) U+2028 (Unicode line separator) U+000A (\\n or LF) U+2029 (Unicode paragraph separator) \\r\\n, in that order (also known as CRLF) @param str A string @return YES or NO. */ static inline BOOL YYTextIsLinebreakString(NSString * _Nullable str) { if (str.length > 2 || str.length == 0) return NO; if (str.length == 1) { unichar c = [str characterAtIndex:0]; return YYTextIsLinebreakChar(c); } else { return ([str characterAtIndex:0] == '\r') && ([str characterAtIndex:1] == '\n'); } } /** If the string has a 'line break' suffix, return the 'line break' length. @param str A string. @return The length of the tail line break: 0, 1 or 2. */ static inline NSUInteger YYTextLinebreakTailLength(NSString * _Nullable str) { if (str.length >= 2) { unichar c2 = [str characterAtIndex:str.length - 1]; if (YYTextIsLinebreakChar(c2)) { unichar c1 = [str characterAtIndex:str.length - 2]; if (c1 == '\r' && c2 == '\n') return 2; else return 1; } else { return 0; } } else if (str.length == 1) { return YYTextIsLinebreakChar([str characterAtIndex:0]) ? 1 : 0; } else { return 0; } } /** Convert `UIDataDetectorTypes` to `NSTextCheckingType`. @param types The `UIDataDetectorTypes` type. @return The `NSTextCheckingType` type. */ static inline NSTextCheckingType NSTextCheckingTypeFromUIDataDetectorType(UIDataDetectorTypes types) { NSTextCheckingType t = 0; if (types & UIDataDetectorTypePhoneNumber) t |= NSTextCheckingTypePhoneNumber; if (types & UIDataDetectorTypeLink) t |= NSTextCheckingTypeLink; if (types & UIDataDetectorTypeAddress) t |= NSTextCheckingTypeAddress; if (types & UIDataDetectorTypeCalendarEvent) t |= NSTextCheckingTypeDate; return t; } /** Whether the font is `AppleColorEmoji` font. @param font A font. @return YES: the font is Emoji, NO: the font is not Emoji. */ static inline BOOL UIFontIsEmoji(UIFont *font) { return [font.fontName isEqualToString:@"AppleColorEmoji"]; } /** Whether the font is `AppleColorEmoji` font. @param font A font. @return YES: the font is Emoji, NO: the font is not Emoji. */ static inline BOOL CTFontIsEmoji(CTFontRef font) { BOOL isEmoji = NO; CFStringRef name = CTFontCopyPostScriptName(font); if (name && CFEqual(CFSTR("AppleColorEmoji"), name)) isEmoji = YES; if (name) CFRelease(name); return isEmoji; } /** Whether the font is `AppleColorEmoji` font. @param font A font. @return YES: the font is Emoji, NO: the font is not Emoji. */ static inline BOOL CGFontIsEmoji(CGFontRef font) { BOOL isEmoji = NO; CFStringRef name = CGFontCopyPostScriptName(font); if (name && CFEqual(CFSTR("AppleColorEmoji"), name)) isEmoji = YES; if (name) CFRelease(name); return isEmoji; } /** Whether the font contains color bitmap glyphs. @discussion Only `AppleColorEmoji` contains color bitmap glyphs in iOS system fonts. @param font A font. @return YES: the font contains color bitmap glyphs, NO: the font has no color bitmap glyph. */ static inline BOOL CTFontContainsColorBitmapGlyphs(CTFontRef font) { return (CTFontGetSymbolicTraits(font) & kCTFontTraitColorGlyphs) != 0; } /** Whether the glyph is bitmap. @param font The glyph's font. @param glyph The glyph which is created from the specified font. @return YES: the glyph is bitmap, NO: the glyph is vector. */ static inline BOOL CGGlyphIsBitmap(CTFontRef font, CGGlyph glyph) { if (!font && !glyph) return NO; if (!CTFontContainsColorBitmapGlyphs(font)) return NO; CGPathRef path = CTFontCreatePathForGlyph(font, glyph, NULL); if (path) { CFRelease(path); return NO; } return YES; } /** Get the `AppleColorEmoji` font's ascent with a specified font size. It may used to create custom emoji. @param fontSize The specified font size. @return The font ascent. */ static inline CGFloat YYEmojiGetAscentWithFontSize(CGFloat fontSize) { if (fontSize < 16) { return 1.25 * fontSize; } else if (16 <= fontSize && fontSize <= 24) { return 0.5 * fontSize + 12; } else { return fontSize; } } /** Get the `AppleColorEmoji` font's descent with a specified font size. It may used to create custom emoji. @param fontSize The specified font size. @return The font descent. */ static inline CGFloat YYEmojiGetDescentWithFontSize(CGFloat fontSize) { if (fontSize < 16) { return 0.390625 * fontSize; } else if (16 <= fontSize && fontSize <= 24) { return 0.15625 * fontSize + 3.75; } else { return 0.3125 * fontSize; } return 0; } /** Get the `AppleColorEmoji` font's glyph bounding rect with a specified font size. It may used to create custom emoji. @param fontSize The specified font size. @return The font glyph bounding rect. */ static inline CGRect YYEmojiGetGlyphBoundingRectWithFontSize(CGFloat fontSize) { CGRect rect; rect.origin.x = 0.75; rect.size.width = rect.size.height = YYEmojiGetAscentWithFontSize(fontSize); if (fontSize < 16) { rect.origin.y = -0.2525 * fontSize; } else if (16 <= fontSize && fontSize <= 24) { rect.origin.y = 0.1225 * fontSize -6; } else { rect.origin.y = -0.1275 * fontSize; } return rect; } /** Convert a UTF-32 character (equal or larger than 0x10000) to two UTF-16 surrogate pair. @param char32 Input: a UTF-32 character (equal or larger than 0x10000, not in BMP) @param char16 Output: two UTF-16 characters. */ static inline void UTF32CharToUTF16SurrogatePair(UTF32Char char32, UTF16Char char16[2]) { char32 -= 0x10000; char16[0] = (char32 >> 10) + 0xD800; char16[1] = (char32 & 0x3FF) + 0xDC00; } /** Convert UTF-16 surrogate pair to a UTF-32 character. @param char16 Two UTF-16 characters. @return A single UTF-32 character. */ static inline UTF32Char UTF16SurrogatePairToUTF32Char(UTF16Char char16[2]) { return ((char16[0] - 0xD800) << 10) + (char16[1] - 0xDC00) + 0x10000; } /** Get the character set which should rotate in vertical form. @return The shared character set. */ NSCharacterSet *YYTextVerticalFormRotateCharacterSet(); /** Get the character set which should rotate and move in vertical form. @return The shared character set. */ NSCharacterSet *YYTextVerticalFormRotateAndMoveCharacterSet(); NS_ASSUME_NONNULL_END YY_EXTERN_C_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextUtilities.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,031
```objective-c // // NSAttributedString+YYText.m // YYKit <path_to_url // // Created by ibireme on 14/10/7. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "NSAttributedString+YYText.h" #import "YYKitMacro.h" #import "UIDevice+YYAdd.h" #import "UIFont+YYAdd.h" #import "NSParagraphStyle+YYText.h" #import "YYTextArchiver.h" #import "YYTextRunDelegate.h" #import "YYAnimatedImageView.h" #import "YYTextUtilities.h" #import <CoreFoundation/CoreFoundation.h> YYSYNTH_DUMMY_CLASS(NSAttributedString_YYText) @implementation NSAttributedString (YYText) - (NSData *)archiveToData { NSData *data = nil; @try { data = [YYTextArchiver archivedDataWithRootObject:self]; } @catch (NSException *exception) { NSLog(@"%@",exception); } return data; } + (instancetype)unarchiveFromData:(NSData *)data { NSAttributedString *one = nil; @try { one = [YYTextUnarchiver unarchiveObjectWithData:data]; } @catch (NSException *exception) { NSLog(@"%@",exception); } return one; } - (NSDictionary *)attributesAtIndex:(NSUInteger)index { if (index > self.length || self.length == 0) return nil; if (self.length > 0 && index == self.length) index--; return [self attributesAtIndex:index effectiveRange:NULL]; } - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index { if (!attributeName) return nil; if (index > self.length || self.length == 0) return nil; if (self.length > 0 && index == self.length) index--; return [self attribute:attributeName atIndex:index effectiveRange:NULL]; } - (NSDictionary *)attributes { return [self attributesAtIndex:0]; } - (UIFont *)font { return [self fontAtIndex:0]; } - (UIFont *)fontAtIndex:(NSUInteger)index { /* In iOS7 and later, UIFont is toll-free bridged to CTFontRef, although Apple does not mention it in documentation. In iOS6, UIFont is a wrapper for CTFontRef, so CoreText can alse use UIfont, but UILabel/UITextView cannot use CTFontRef. We use UIFont for both CoreText and UIKit. */ UIFont *font = [self attribute:NSFontAttributeName atIndex:index]; if (kSystemVersion <= 6) { if (font) { if (CFGetTypeID((__bridge CFTypeRef)(font)) == CTFontGetTypeID()) { font = [UIFont fontWithCTFont:(CTFontRef)font]; } } } return font; } - (NSNumber *)kern { return [self kernAtIndex:0]; } - (NSNumber *)kernAtIndex:(NSUInteger)index { return [self attribute:NSKernAttributeName atIndex:index]; } - (UIColor *)color { return [self colorAtIndex:0]; } - (UIColor *)colorAtIndex:(NSUInteger)index { UIColor *color = [self attribute:NSForegroundColorAttributeName atIndex:index]; if (!color) { CGColorRef ref = (__bridge CGColorRef)([self attribute:(NSString *)kCTForegroundColorAttributeName atIndex:index]); color = [UIColor colorWithCGColor:ref]; } if (color && ![color isKindOfClass:[UIColor class]]) { if (CFGetTypeID((__bridge CFTypeRef)(color)) == CGColorGetTypeID()) { color = [UIColor colorWithCGColor:(__bridge CGColorRef)(color)]; } else { color = nil; } } return color; } - (UIColor *)backgroundColor { return [self backgroundColorAtIndex:0]; } - (UIColor *)backgroundColorAtIndex:(NSUInteger)index { return [self attribute:NSBackgroundColorAttributeName atIndex:index]; } - (NSNumber *)strokeWidth { return [self strokeWidthAtIndex:0]; } - (NSNumber *)strokeWidthAtIndex:(NSUInteger)index { return [self attribute:NSStrokeWidthAttributeName atIndex:index]; } - (UIColor *)strokeColor { return [self strokeColorAtIndex:0]; } - (UIColor *)strokeColorAtIndex:(NSUInteger)index { UIColor *color = [self attribute:NSStrokeColorAttributeName atIndex:index]; if (!color) { CGColorRef ref = (__bridge CGColorRef)([self attribute:(NSString *)kCTStrokeColorAttributeName atIndex:index]); color = [UIColor colorWithCGColor:ref]; } return color; } - (NSShadow *)shadow { return [self shadowAtIndex:0]; } - (NSShadow *)shadowAtIndex:(NSUInteger)index { return [self attribute:NSShadowAttributeName atIndex:index]; } - (NSUnderlineStyle)strikethroughStyle { return [self strikethroughStyleAtIndex:0]; } - (NSUnderlineStyle)strikethroughStyleAtIndex:(NSUInteger)index { NSNumber *style = [self attribute:NSStrikethroughStyleAttributeName atIndex:index]; return style.integerValue; } - (UIColor *)strikethroughColor { return [self strikethroughColorAtIndex:0]; } - (UIColor *)strikethroughColorAtIndex:(NSUInteger)index { if (kSystemVersion >= 7) { return [self attribute:NSStrikethroughColorAttributeName atIndex:index]; } return nil; } - (NSUnderlineStyle)underlineStyle { return [self underlineStyleAtIndex:0]; } - (NSUnderlineStyle)underlineStyleAtIndex:(NSUInteger)index { NSNumber *style = [self attribute:NSUnderlineStyleAttributeName atIndex:index]; return style.integerValue; } - (UIColor *)underlineColor { return [self underlineColorAtIndex:0]; } - (UIColor *)underlineColorAtIndex:(NSUInteger)index { UIColor *color = nil; if (kSystemVersion >= 7) { color = [self attribute:NSUnderlineColorAttributeName atIndex:index]; } if (!color) { CGColorRef ref = (__bridge CGColorRef)([self attribute:(NSString *)kCTUnderlineColorAttributeName atIndex:index]); color = [UIColor colorWithCGColor:ref]; } return color; } - (NSNumber *)ligature { return [self ligatureAtIndex:0]; } - (NSNumber *)ligatureAtIndex:(NSUInteger)index { return [self attribute:NSLigatureAttributeName atIndex:index]; } - (NSString *)textEffect { return [self textEffectAtIndex:0]; } - (NSString *)textEffectAtIndex:(NSUInteger)index { if (kSystemVersion >= 7) { return [self attribute:NSTextEffectAttributeName atIndex:index]; } return nil; } - (NSNumber *)obliqueness { return [self obliquenessAtIndex:0]; } - (NSNumber *)obliquenessAtIndex:(NSUInteger)index { if (kSystemVersion >= 7) { return [self attribute:NSObliquenessAttributeName atIndex:index]; } return nil; } - (NSNumber *)expansion { return [self expansionAtIndex:0]; } - (NSNumber *)expansionAtIndex:(NSUInteger)index { if (kSystemVersion >= 7) { return [self attribute:NSExpansionAttributeName atIndex:index]; } return nil; } - (NSNumber *)baselineOffset { return [self baselineOffsetAtIndex:0]; } - (NSNumber *)baselineOffsetAtIndex:(NSUInteger)index { if (kSystemVersion >= 7) { return [self attribute:NSBaselineOffsetAttributeName atIndex:index]; } return nil; } - (BOOL)verticalGlyphForm { return [self verticalGlyphFormAtIndex:0]; } - (BOOL)verticalGlyphFormAtIndex:(NSUInteger)index { NSNumber *num = [self attribute:NSVerticalGlyphFormAttributeName atIndex:index]; return num.boolValue; } - (NSString *)language { return [self languageAtIndex:0]; } - (NSString *)languageAtIndex:(NSUInteger)index { if (kSystemVersion >= 7) { return [self attribute:(id)kCTLanguageAttributeName atIndex:index]; } return nil; } - (NSArray *)writingDirection { return [self writingDirectionAtIndex:0]; } - (NSArray *)writingDirectionAtIndex:(NSUInteger)index { return [self attribute:(id)kCTWritingDirectionAttributeName atIndex:index]; } - (NSParagraphStyle *)paragraphStyle { return [self paragraphStyleAtIndex:0]; } - (NSParagraphStyle *)paragraphStyleAtIndex:(NSUInteger)index { /* NSParagraphStyle is NOT toll-free bridged to CTParagraphStyleRef. CoreText can use both NSParagraphStyle and CTParagraphStyleRef, but UILabel/UITextView can only use NSParagraphStyle. We use NSParagraphStyle in both CoreText and UIKit. */ NSParagraphStyle *style = [self attribute:NSParagraphStyleAttributeName atIndex:index]; if (style) { if (CFGetTypeID((__bridge CFTypeRef)(style)) == CTParagraphStyleGetTypeID()) { \ style = [NSParagraphStyle styleWithCTStyle:(__bridge CTParagraphStyleRef)(style)]; } } return style; } #define ParagraphAttribute(_attr_) \ NSParagraphStyle *style = self.paragraphStyle; \ if (!style) style = [NSParagraphStyle defaultParagraphStyle]; \ return style. _attr_; #define ParagraphAttributeAtIndex(_attr_) \ NSParagraphStyle *style = [self paragraphStyleAtIndex:index]; \ if (!style) style = [NSParagraphStyle defaultParagraphStyle]; \ return style. _attr_; - (NSTextAlignment)alignment { ParagraphAttribute(alignment); } - (NSLineBreakMode)lineBreakMode { ParagraphAttribute(lineBreakMode); } - (CGFloat)lineSpacing { ParagraphAttribute(lineSpacing); } - (CGFloat)paragraphSpacing { ParagraphAttribute(paragraphSpacing); } - (CGFloat)paragraphSpacingBefore { ParagraphAttribute(paragraphSpacingBefore); } - (CGFloat)firstLineHeadIndent { ParagraphAttribute(firstLineHeadIndent); } - (CGFloat)headIndent { ParagraphAttribute(headIndent); } - (CGFloat)tailIndent { ParagraphAttribute(tailIndent); } - (CGFloat)minimumLineHeight { ParagraphAttribute(minimumLineHeight); } - (CGFloat)maximumLineHeight { ParagraphAttribute(maximumLineHeight); } - (CGFloat)lineHeightMultiple { ParagraphAttribute(lineHeightMultiple); } - (NSWritingDirection)baseWritingDirection { ParagraphAttribute(baseWritingDirection); } - (float)hyphenationFactor { ParagraphAttribute(hyphenationFactor); } - (CGFloat)defaultTabInterval { if (!kiOS7Later) return 0; ParagraphAttribute(defaultTabInterval); } - (NSArray *)tabStops { if (!kiOS7Later) return nil; ParagraphAttribute(tabStops); } - (NSTextAlignment)alignmentAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(alignment); } - (NSLineBreakMode)lineBreakModeAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(lineBreakMode); } - (CGFloat)lineSpacingAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(lineSpacing); } - (CGFloat)paragraphSpacingAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(paragraphSpacing); } - (CGFloat)paragraphSpacingBeforeAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(paragraphSpacingBefore); } - (CGFloat)firstLineHeadIndentAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(firstLineHeadIndent); } - (CGFloat)headIndentAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(headIndent); } - (CGFloat)tailIndentAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(tailIndent); } - (CGFloat)minimumLineHeightAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(minimumLineHeight); } - (CGFloat)maximumLineHeightAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(maximumLineHeight); } - (CGFloat)lineHeightMultipleAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(lineHeightMultiple); } - (NSWritingDirection)baseWritingDirectionAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(baseWritingDirection); } - (float)hyphenationFactorAtIndex:(NSUInteger)index { ParagraphAttributeAtIndex(hyphenationFactor); } - (CGFloat)defaultTabIntervalAtIndex:(NSUInteger)index { if (!kiOS7Later) return 0; ParagraphAttributeAtIndex(defaultTabInterval); } - (NSArray *)tabStopsAtIndex:(NSUInteger)index { if (!kiOS7Later) return nil; ParagraphAttributeAtIndex(tabStops); } #undef ParagraphAttribute #undef ParagraphAttributeAtIndex - (YYTextShadow *)textShadow { return [self textShadowAtIndex:0]; } - (YYTextShadow *)textShadowAtIndex:(NSUInteger)index { return [self attribute:YYTextShadowAttributeName atIndex:index]; } - (YYTextShadow *)textInnerShadow { return [self textInnerShadowAtIndex:0]; } - (YYTextShadow *)textInnerShadowAtIndex:(NSUInteger)index { return [self attribute:YYTextInnerShadowAttributeName atIndex:index]; } - (YYTextDecoration *)textUnderline { return [self textUnderlineAtIndex:0]; } - (YYTextDecoration *)textUnderlineAtIndex:(NSUInteger)index { return [self attribute:YYTextUnderlineAttributeName atIndex:index]; } - (YYTextDecoration *)textStrikethrough { return [self textStrikethroughAtIndex:0]; } - (YYTextDecoration *)textStrikethroughAtIndex:(NSUInteger)index { return [self attribute:YYTextStrikethroughAttributeName atIndex:index]; } - (YYTextBorder *)textBorder { return [self textBorderAtIndex:0]; } - (YYTextBorder *)textBorderAtIndex:(NSUInteger)index { return [self attribute:YYTextBorderAttributeName atIndex:index]; } - (YYTextBorder *)textBackgroundBorder { return [self textBackgroundBorderAtIndex:0]; } - (YYTextBorder *)textBackgroundBorderAtIndex:(NSUInteger)index { return [self attribute:YYTextBackedStringAttributeName atIndex:index]; } - (CGAffineTransform)textGlyphTransform { return [self textGlyphTransformAtIndex:0]; } - (CGAffineTransform)textGlyphTransformAtIndex:(NSUInteger)index { NSValue *value = [self attribute:YYTextGlyphTransformAttributeName atIndex:index]; if (!value) return CGAffineTransformIdentity; return [value CGAffineTransformValue]; } - (NSString *)plainTextForRange:(NSRange)range { if (range.location == NSNotFound ||range.length == NSNotFound) return nil; NSMutableString *result = [NSMutableString string]; if (range.length == 0) return result; NSString *string = self.string; [self enumerateAttribute:YYTextBackedStringAttributeName inRange:range options:kNilOptions usingBlock:^(id value, NSRange range, BOOL *stop) { YYTextBackedString *backed = value; if (backed && backed.string) { [result appendString:backed.string]; } else { [result appendString:[string substringWithRange:range]]; } }]; return result; } + (NSMutableAttributedString *)attachmentStringWithContent:(id)content contentMode:(UIViewContentMode)contentMode width:(CGFloat)width ascent:(CGFloat)ascent descent:(CGFloat)descent { NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken]; YYTextAttachment *attach = [YYTextAttachment new]; attach.content = content; attach.contentMode = contentMode; [atr setTextAttachment:attach range:NSMakeRange(0, atr.length)]; YYTextRunDelegate *delegate = [YYTextRunDelegate new]; delegate.width = width; delegate.ascent = ascent; delegate.descent = descent; CTRunDelegateRef delegateRef = delegate.CTRunDelegate; [atr setRunDelegate:delegateRef range:NSMakeRange(0, atr.length)]; if (delegate) CFRelease(delegateRef); return atr; } + (NSMutableAttributedString *)attachmentStringWithContent:(id)content contentMode:(UIViewContentMode)contentMode attachmentSize:(CGSize)attachmentSize alignToFont:(UIFont *)font alignment:(YYTextVerticalAlignment)alignment { NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken]; YYTextAttachment *attach = [YYTextAttachment new]; attach.content = content; attach.contentMode = contentMode; [atr setTextAttachment:attach range:NSMakeRange(0, atr.length)]; YYTextRunDelegate *delegate = [YYTextRunDelegate new]; delegate.width = attachmentSize.width; switch (alignment) { case YYTextVerticalAlignmentTop: { delegate.ascent = font.ascender; delegate.descent = attachmentSize.height - font.ascender; if (delegate.descent < 0) { delegate.descent = 0; delegate.ascent = attachmentSize.height; } } break; case YYTextVerticalAlignmentCenter: { CGFloat fontHeight = font.ascender - font.descender; CGFloat yOffset = font.ascender - fontHeight * 0.5; delegate.ascent = attachmentSize.height * 0.5 + yOffset; delegate.descent = attachmentSize.height - delegate.ascent; if (delegate.descent < 0) { delegate.descent = 0; delegate.ascent = attachmentSize.height; } } break; case YYTextVerticalAlignmentBottom: { delegate.ascent = attachmentSize.height + font.descender; delegate.descent = -font.descender; if (delegate.ascent < 0) { delegate.ascent = 0; delegate.descent = attachmentSize.height; } } break; default: { delegate.ascent = attachmentSize.height; delegate.descent = 0; } break; } CTRunDelegateRef delegateRef = delegate.CTRunDelegate; [atr setRunDelegate:delegateRef range:NSMakeRange(0, atr.length)]; if (delegate) CFRelease(delegateRef); return atr; } + (NSMutableAttributedString *)attachmentStringWithEmojiImage:(UIImage *)image fontSize:(CGFloat)fontSize { if (!image || fontSize <= 0) return nil; BOOL hasAnim = NO; if (image.images.count > 1) { hasAnim = YES; } else if ([image conformsToProtocol:@protocol(YYAnimatedImage)]) { id <YYAnimatedImage> ani = (id)image; if (ani.animatedImageFrameCount > 1) hasAnim = YES; } CGFloat ascent = YYEmojiGetAscentWithFontSize(fontSize); CGFloat descent = YYEmojiGetDescentWithFontSize(fontSize); CGRect bounding = YYEmojiGetGlyphBoundingRectWithFontSize(fontSize); YYTextRunDelegate *delegate = [YYTextRunDelegate new]; delegate.ascent = ascent; delegate.descent = descent; delegate.width = bounding.size.width + 2 * bounding.origin.x; YYTextAttachment *attachment = [YYTextAttachment new]; attachment.contentMode = UIViewContentModeScaleAspectFit; attachment.contentInsets = UIEdgeInsetsMake(ascent - (bounding.size.height + bounding.origin.y), bounding.origin.x, descent + bounding.origin.y, bounding.origin.x); if (hasAnim) { YYAnimatedImageView *view = [YYAnimatedImageView new]; view.frame = bounding; view.image = image; view.contentMode = UIViewContentModeScaleAspectFit; attachment.content = view; } else { attachment.content = image; } NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken]; [atr setTextAttachment:attachment range:NSMakeRange(0, atr.length)]; CTRunDelegateRef ctDelegate = delegate.CTRunDelegate; [atr setRunDelegate:ctDelegate range:NSMakeRange(0, atr.length)]; if (ctDelegate) CFRelease(ctDelegate); return atr; } - (NSRange)rangeOfAll { return NSMakeRange(0, self.length); } - (BOOL)isSharedAttributesInAllRange { __block BOOL shared = YES; __block NSDictionary *firstAttrs = nil; [self enumerateAttributesInRange:self.rangeOfAll options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) { if (range.location == 0) { firstAttrs = attrs; } else { if (firstAttrs.count != attrs.count) { shared = NO; *stop = YES; } else if (firstAttrs) { if (![firstAttrs isEqualToDictionary:attrs]) { shared = NO; *stop = YES; } } } }]; return shared; } - (BOOL)canDrawWithUIKit { static NSMutableSet *failSet; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ failSet = [NSMutableSet new]; [failSet addObject:(id)kCTGlyphInfoAttributeName]; [failSet addObject:(id)kCTCharacterShapeAttributeName]; if (kiOS7Later) { [failSet addObject:(id)kCTLanguageAttributeName]; } [failSet addObject:(id)kCTRunDelegateAttributeName]; [failSet addObject:(id)kCTBaselineClassAttributeName]; [failSet addObject:(id)kCTBaselineInfoAttributeName]; [failSet addObject:(id)kCTBaselineReferenceInfoAttributeName]; if (kiOS8Later) { [failSet addObject:(id)kCTRubyAnnotationAttributeName]; } [failSet addObject:YYTextShadowAttributeName]; [failSet addObject:YYTextInnerShadowAttributeName]; [failSet addObject:YYTextUnderlineAttributeName]; [failSet addObject:YYTextStrikethroughAttributeName]; [failSet addObject:YYTextBorderAttributeName]; [failSet addObject:YYTextBackgroundBorderAttributeName]; [failSet addObject:YYTextBlockBorderAttributeName]; [failSet addObject:YYTextAttachmentAttributeName]; [failSet addObject:YYTextHighlightAttributeName]; [failSet addObject:YYTextGlyphTransformAttributeName]; }); #define Fail { result = NO; *stop = YES; return; } __block BOOL result = YES; [self enumerateAttributesInRange:self.rangeOfAll options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) { if (attrs.count == 0) return; for (NSString *str in attrs.allKeys) { if ([failSet containsObject:str]) Fail; } if (!kiOS7Later) { UIFont *font = attrs[NSFontAttributeName]; if (CFGetTypeID((__bridge CFTypeRef)(font)) == CTFontGetTypeID()) Fail; } if (attrs[(id)kCTForegroundColorAttributeName] && !attrs[NSForegroundColorAttributeName]) Fail; if (attrs[(id)kCTStrokeColorAttributeName] && !attrs[NSStrokeColorAttributeName]) Fail; if (attrs[(id)kCTUnderlineColorAttributeName]) { if (!kiOS7Later) Fail; if (!attrs[NSUnderlineColorAttributeName]) Fail; } NSParagraphStyle *style = attrs[NSParagraphStyleAttributeName]; if (style && CFGetTypeID((__bridge CFTypeRef)(style)) == CTParagraphStyleGetTypeID()) Fail; }]; return result; #undef Fail } @end @implementation NSMutableAttributedString (YYText) - (void)setAttributes:(NSDictionary *)attributes { if (attributes == (id)[NSNull null]) attributes = nil; [self setAttributes:@{} range:NSMakeRange(0, self.length)]; [attributes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [self setAttribute:key value:obj]; }]; } - (void)setAttribute:(NSString *)name value:(id)value { [self setAttribute:name value:value range:NSMakeRange(0, self.length)]; } - (void)setAttribute:(NSString *)name value:(id)value range:(NSRange)range { if (!name || [NSNull isEqual:name]) return; if (value && ![NSNull isEqual:value]) [self addAttribute:name value:value range:range]; else [self removeAttribute:name range:range]; } - (void)removeAttributesInRange:(NSRange)range { [self setAttributes:nil range:range]; } #pragma mark - Property Setter - (void)setFont:(UIFont *)font { /* In iOS7 and later, UIFont is toll-free bridged to CTFontRef, although Apple does not mention it in documentation. In iOS6, UIFont is a wrapper for CTFontRef, so CoreText can alse use UIfont, but UILabel/UITextView cannot use CTFontRef. We use UIFont for both CoreText and UIKit. */ [self setFont:font range:NSMakeRange(0, self.length)]; } - (void)setKern:(NSNumber *)kern { [self setKern:kern range:NSMakeRange(0, self.length)]; } - (void)setColor:(UIColor *)color { [self setColor:color range:NSMakeRange(0, self.length)]; } - (void)setBackgroundColor:(UIColor *)backgroundColor { [self setBackgroundColor:backgroundColor range:NSMakeRange(0, self.length)]; } - (void)setStrokeWidth:(NSNumber *)strokeWidth { [self setStrokeWidth:strokeWidth range:NSMakeRange(0, self.length)]; } - (void)setStrokeColor:(UIColor *)strokeColor { [self setStrokeColor:strokeColor range:NSMakeRange(0, self.length)]; } - (void)setShadow:(NSShadow *)shadow { [self setShadow:shadow range:NSMakeRange(0, self.length)]; } - (void)setStrikethroughStyle:(NSUnderlineStyle)strikethroughStyle { [self setStrikethroughStyle:strikethroughStyle range:NSMakeRange(0, self.length)]; } - (void)setStrikethroughColor:(UIColor *)strikethroughColor { [self setStrikethroughColor:strikethroughColor range:NSMakeRange(0, self.length)]; } - (void)setUnderlineStyle:(NSUnderlineStyle)underlineStyle { [self setUnderlineStyle:underlineStyle range:NSMakeRange(0, self.length)]; } - (void)setUnderlineColor:(UIColor *)underlineColor { [self setUnderlineColor:underlineColor range:NSMakeRange(0, self.length)]; } - (void)setLigature:(NSNumber *)ligature { [self setLigature:ligature range:NSMakeRange(0, self.length)]; } - (void)setTextEffect:(NSString *)textEffect { [self setTextEffect:textEffect range:NSMakeRange(0, self.length)]; } - (void)setObliqueness:(NSNumber *)obliqueness { [self setObliqueness:obliqueness range:NSMakeRange(0, self.length)]; } - (void)setExpansion:(NSNumber *)expansion { [self setExpansion:expansion range:NSMakeRange(0, self.length)]; } - (void)setBaselineOffset:(NSNumber *)baselineOffset { [self setBaselineOffset:baselineOffset range:NSMakeRange(0, self.length)]; } - (void)setVerticalGlyphForm:(BOOL)verticalGlyphForm { [self setVerticalGlyphForm:verticalGlyphForm range:NSMakeRange(0, self.length)]; } - (void)setLanguage:(NSString *)language { [self setLanguage:language range:NSMakeRange(0, self.length)]; } - (void)setWritingDirection:(NSArray *)writingDirection { [self setWritingDirection:writingDirection range:NSMakeRange(0, self.length)]; } - (void)setParagraphStyle:(NSParagraphStyle *)paragraphStyle { /* NSParagraphStyle is NOT toll-free bridged to CTParagraphStyleRef. CoreText can use both NSParagraphStyle and CTParagraphStyleRef, but UILabel/UITextView can only use NSParagraphStyle. We use NSParagraphStyle in both CoreText and UIKit. */ [self setParagraphStyle:paragraphStyle range:NSMakeRange(0, self.length)]; } - (void)setAlignment:(NSTextAlignment)alignment { [self setAlignment:alignment range:NSMakeRange(0, self.length)]; } - (void)setBaseWritingDirection:(NSWritingDirection)baseWritingDirection { [self setBaseWritingDirection:baseWritingDirection range:NSMakeRange(0, self.length)]; } - (void)setLineSpacing:(CGFloat)lineSpacing { [self setLineSpacing:lineSpacing range:NSMakeRange(0, self.length)]; } - (void)setParagraphSpacing:(CGFloat)paragraphSpacing { [self setParagraphSpacing:paragraphSpacing range:NSMakeRange(0, self.length)]; } - (void)setParagraphSpacingBefore:(CGFloat)paragraphSpacingBefore { [self setParagraphSpacing:paragraphSpacingBefore range:NSMakeRange(0, self.length)]; } - (void)setFirstLineHeadIndent:(CGFloat)firstLineHeadIndent { [self setFirstLineHeadIndent:firstLineHeadIndent range:NSMakeRange(0, self.length)]; } - (void)setHeadIndent:(CGFloat)headIndent { [self setHeadIndent:headIndent range:NSMakeRange(0, self.length)]; } - (void)setTailIndent:(CGFloat)tailIndent { [self setTailIndent:tailIndent range:NSMakeRange(0, self.length)]; } - (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode { [self setLineBreakMode:lineBreakMode range:NSMakeRange(0, self.length)]; } - (void)setMinimumLineHeight:(CGFloat)minimumLineHeight { [self setMinimumLineHeight:minimumLineHeight range:NSMakeRange(0, self.length)]; } - (void)setMaximumLineHeight:(CGFloat)maximumLineHeight { [self setMaximumLineHeight:maximumLineHeight range:NSMakeRange(0, self.length)]; } - (void)setLineHeightMultiple:(CGFloat)lineHeightMultiple { [self setLineHeightMultiple:lineHeightMultiple range:NSMakeRange(0, self.length)]; } - (void)setHyphenationFactor:(float)hyphenationFactor { [self setHyphenationFactor:hyphenationFactor range:NSMakeRange(0, self.length)]; } - (void)setDefaultTabInterval:(CGFloat)defaultTabInterval { [self setDefaultTabInterval:defaultTabInterval range:NSMakeRange(0, self.length)]; } - (void)setTabStops:(NSArray *)tabStops { [self setTabStops:tabStops range:NSMakeRange(0, self.length)]; } - (void)setTextShadow:(YYTextShadow *)textShadow { [self setTextShadow:textShadow range:NSMakeRange(0, self.length)]; } - (void)setTextInnerShadow:(YYTextShadow *)textInnerShadow { [self setTextInnerShadow:textInnerShadow range:NSMakeRange(0, self.length)]; } - (void)setTextUnderline:(YYTextDecoration *)textUnderline { [self setTextUnderline:textUnderline range:NSMakeRange(0, self.length)]; } - (void)setTextStrikethrough:(YYTextDecoration *)textStrikethrough { [self setTextStrikethrough:textStrikethrough range:NSMakeRange(0, self.length)]; } - (void)setTextBorder:(YYTextBorder *)textBorder { [self setTextBorder:textBorder range:NSMakeRange(0, self.length)]; } - (void)setTextBackgroundBorder:(YYTextBorder *)textBackgroundBorder { [self setTextBackgroundBorder:textBackgroundBorder range:NSMakeRange(0, self.length)]; } - (void)setTextGlyphTransform:(CGAffineTransform)textGlyphTransform { [self setTextGlyphTransform:textGlyphTransform range:NSMakeRange(0, self.length)]; } #pragma mark - Range Setter - (void)setFont:(UIFont *)font range:(NSRange)range { /* In iOS7 and later, UIFont is toll-free bridged to CTFontRef, although Apple does not mention it in documentation. In iOS6, UIFont is a wrapper for CTFontRef, so CoreText can alse use UIfont, but UILabel/UITextView cannot use CTFontRef. We use UIFont for both CoreText and UIKit. */ [self setAttribute:NSFontAttributeName value:font range:range]; } - (void)setKern:(NSNumber *)kern range:(NSRange)range { [self setAttribute:NSKernAttributeName value:kern range:range]; } - (void)setColor:(UIColor *)color range:(NSRange)range { [self setAttribute:(id)kCTForegroundColorAttributeName value:(id)color.CGColor range:range]; [self setAttribute:NSForegroundColorAttributeName value:color range:range]; } - (void)setBackgroundColor:(UIColor *)backgroundColor range:(NSRange)range { [self setAttribute:NSBackgroundColorAttributeName value:backgroundColor range:range]; } - (void)setStrokeWidth:(NSNumber *)strokeWidth range:(NSRange)range { [self setAttribute:NSStrokeWidthAttributeName value:strokeWidth range:range]; } - (void)setStrokeColor:(UIColor *)strokeColor range:(NSRange)range { [self setAttribute:(id)kCTStrokeColorAttributeName value:(id)strokeColor.CGColor range:range]; [self setAttribute:NSStrokeColorAttributeName value:strokeColor range:range]; } - (void)setShadow:(NSShadow *)shadow range:(NSRange)range { [self setAttribute:NSShadowAttributeName value:shadow range:range]; } - (void)setStrikethroughStyle:(NSUnderlineStyle)strikethroughStyle range:(NSRange)range { NSNumber *style = strikethroughStyle == 0 ? nil : @(strikethroughStyle); [self setAttribute:NSStrikethroughStyleAttributeName value:style range:range]; } - (void)setStrikethroughColor:(UIColor *)strikethroughColor range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:NSStrikethroughColorAttributeName value:strikethroughColor range:range]; } } - (void)setUnderlineStyle:(NSUnderlineStyle)underlineStyle range:(NSRange)range { NSNumber *style = underlineStyle == 0 ? nil : @(underlineStyle); [self setAttribute:NSUnderlineStyleAttributeName value:style range:range]; } - (void)setUnderlineColor:(UIColor *)underlineColor range:(NSRange)range { [self setAttribute:(id)kCTUnderlineColorAttributeName value:(id)underlineColor.CGColor range:range]; if (kSystemVersion >= 7) { [self setAttribute:NSUnderlineColorAttributeName value:underlineColor range:range]; } } - (void)setLigature:(NSNumber *)ligature range:(NSRange)range { [self setAttribute:NSLigatureAttributeName value:ligature range:range]; } - (void)setTextEffect:(NSString *)textEffect range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:NSTextEffectAttributeName value:textEffect range:range]; } } - (void)setObliqueness:(NSNumber *)obliqueness range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:NSObliquenessAttributeName value:obliqueness range:range]; } } - (void)setExpansion:(NSNumber *)expansion range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:NSExpansionAttributeName value:expansion range:range]; } } - (void)setBaselineOffset:(NSNumber *)baselineOffset range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:NSBaselineOffsetAttributeName value:baselineOffset range:range]; } } - (void)setVerticalGlyphForm:(BOOL)verticalGlyphForm range:(NSRange)range { NSNumber *v = verticalGlyphForm ? @(YES) : nil; [self setAttribute:NSVerticalGlyphFormAttributeName value:v range:range]; } - (void)setLanguage:(NSString *)language range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:(id)kCTLanguageAttributeName value:language range:range]; } } - (void)setWritingDirection:(NSArray *)writingDirection range:(NSRange)range { [self setAttribute:(id)kCTWritingDirectionAttributeName value:writingDirection range:range]; } - (void)setParagraphStyle:(NSParagraphStyle *)paragraphStyle range:(NSRange)range { /* NSParagraphStyle is NOT toll-free bridged to CTParagraphStyleRef. CoreText can use both NSParagraphStyle and CTParagraphStyleRef, but UILabel/UITextView can only use NSParagraphStyle. We use NSParagraphStyle in both CoreText and UIKit. */ [self setAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range]; } #define ParagraphStyleSet(_attr_) \ [self enumerateAttribute:NSParagraphStyleAttributeName \ inRange:range \ options:kNilOptions \ usingBlock: ^(NSParagraphStyle *value, NSRange subRange, BOOL *stop) { \ NSMutableParagraphStyle *style = nil; \ if (value) { \ if (CFGetTypeID((__bridge CFTypeRef)(value)) == CTParagraphStyleGetTypeID()) { \ value = [NSParagraphStyle styleWithCTStyle:(__bridge CTParagraphStyleRef)(value)]; \ } \ if (value. _attr_ == _attr_) return; \ if ([value isKindOfClass:[NSMutableParagraphStyle class]]) { \ style = (id)value; \ } else { \ style = value.mutableCopy; \ } \ } else { \ if ([NSParagraphStyle defaultParagraphStyle]. _attr_ == _attr_) return; \ style = [NSParagraphStyle defaultParagraphStyle].mutableCopy; \ } \ style. _attr_ = _attr_; \ [self setParagraphStyle:style range:subRange]; \ }]; - (void)setAlignment:(NSTextAlignment)alignment range:(NSRange)range { ParagraphStyleSet(alignment); } - (void)setBaseWritingDirection:(NSWritingDirection)baseWritingDirection range:(NSRange)range { ParagraphStyleSet(baseWritingDirection); } - (void)setLineSpacing:(CGFloat)lineSpacing range:(NSRange)range { ParagraphStyleSet(lineSpacing); } - (void)setParagraphSpacing:(CGFloat)paragraphSpacing range:(NSRange)range { ParagraphStyleSet(paragraphSpacing); } - (void)setParagraphSpacingBefore:(CGFloat)paragraphSpacingBefore range:(NSRange)range { ParagraphStyleSet(paragraphSpacingBefore); } - (void)setFirstLineHeadIndent:(CGFloat)firstLineHeadIndent range:(NSRange)range { ParagraphStyleSet(firstLineHeadIndent); } - (void)setHeadIndent:(CGFloat)headIndent range:(NSRange)range { ParagraphStyleSet(headIndent); } - (void)setTailIndent:(CGFloat)tailIndent range:(NSRange)range { ParagraphStyleSet(tailIndent); } - (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode range:(NSRange)range { ParagraphStyleSet(lineBreakMode); } - (void)setMinimumLineHeight:(CGFloat)minimumLineHeight range:(NSRange)range { ParagraphStyleSet(minimumLineHeight); } - (void)setMaximumLineHeight:(CGFloat)maximumLineHeight range:(NSRange)range { ParagraphStyleSet(maximumLineHeight); } - (void)setLineHeightMultiple:(CGFloat)lineHeightMultiple range:(NSRange)range { ParagraphStyleSet(lineHeightMultiple); } - (void)setHyphenationFactor:(float)hyphenationFactor range:(NSRange)range { ParagraphStyleSet(hyphenationFactor); } - (void)setDefaultTabInterval:(CGFloat)defaultTabInterval range:(NSRange)range { if (!kiOS7Later) return; ParagraphStyleSet(defaultTabInterval); } - (void)setTabStops:(NSArray *)tabStops range:(NSRange)range { if (!kiOS7Later) return; ParagraphStyleSet(tabStops); } #undef ParagraphStyleSet - (void)setSuperscript:(NSNumber *)superscript range:(NSRange)range { if ([superscript isEqualToNumber:@(0)]) { superscript = nil; } [self setAttribute:(id)kCTSuperscriptAttributeName value:superscript range:range]; } - (void)setGlyphInfo:(CTGlyphInfoRef)glyphInfo range:(NSRange)range { [self setAttribute:(id)kCTGlyphInfoAttributeName value:(__bridge id)glyphInfo range:range]; } - (void)setCharacterShape:(NSNumber *)characterShape range:(NSRange)range { [self setAttribute:(id)kCTCharacterShapeAttributeName value:characterShape range:range]; } - (void)setRunDelegate:(CTRunDelegateRef)runDelegate range:(NSRange)range { [self setAttribute:(id)kCTRunDelegateAttributeName value:(__bridge id)runDelegate range:range]; } - (void)setBaselineClass:(CFStringRef)baselineClass range:(NSRange)range { [self setAttribute:(id)kCTBaselineClassAttributeName value:(__bridge id)baselineClass range:range]; } - (void)setBaselineInfo:(CFDictionaryRef)baselineInfo range:(NSRange)range { [self setAttribute:(id)kCTBaselineInfoAttributeName value:(__bridge id)baselineInfo range:range]; } - (void)setBaselineReferenceInfo:(CFDictionaryRef)referenceInfo range:(NSRange)range { [self setAttribute:(id)kCTBaselineReferenceInfoAttributeName value:(__bridge id)referenceInfo range:range]; } - (void)setRubyAnnotation:(CTRubyAnnotationRef)ruby range:(NSRange)range { if (kSystemVersion >= 8) { [self setAttribute:(id)kCTRubyAnnotationAttributeName value:(__bridge id)ruby range:range]; } } - (void)setAttachment:(NSTextAttachment *)attachment range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:NSAttachmentAttributeName value:attachment range:range]; } } - (void)setLink:(id)link range:(NSRange)range { if (kSystemVersion >= 7) { [self setAttribute:NSLinkAttributeName value:link range:range]; } } - (void)setTextBackedString:(YYTextBackedString *)textBackedString range:(NSRange)range { [self setAttribute:YYTextBackedStringAttributeName value:textBackedString range:range]; } - (void)setTextBinding:(YYTextBinding *)textBinding range:(NSRange)range { [self setAttribute:YYTextBindingAttributeName value:textBinding range:range]; } - (void)setTextShadow:(YYTextShadow *)textShadow range:(NSRange)range { [self setAttribute:YYTextShadowAttributeName value:textShadow range:range]; } - (void)setTextInnerShadow:(YYTextShadow *)textInnerShadow range:(NSRange)range { [self setAttribute:YYTextInnerShadowAttributeName value:textInnerShadow range:range]; } - (void)setTextUnderline:(YYTextDecoration *)textUnderline range:(NSRange)range { [self setAttribute:YYTextUnderlineAttributeName value:textUnderline range:range]; } - (void)setTextStrikethrough:(YYTextDecoration *)textStrikethrough range:(NSRange)range { [self setAttribute:YYTextStrikethroughAttributeName value:textStrikethrough range:range]; } - (void)setTextBorder:(YYTextBorder *)textBorder range:(NSRange)range { [self setAttribute:YYTextBorderAttributeName value:textBorder range:range]; } - (void)setTextBackgroundBorder:(YYTextBorder *)textBackgroundBorder range:(NSRange)range { [self setAttribute:YYTextBackgroundBorderAttributeName value:textBackgroundBorder range:range]; } - (void)setTextAttachment:(YYTextAttachment *)textAttachment range:(NSRange)range { [self setAttribute:YYTextAttachmentAttributeName value:textAttachment range:range]; } - (void)setTextHighlight:(YYTextHighlight *)textHighlight range:(NSRange)range { [self setAttribute:YYTextHighlightAttributeName value:textHighlight range:range]; } - (void)setTextBlockBorder:(YYTextBorder *)textBlockBorder range:(NSRange)range { [self setAttribute:YYTextBlockBorderAttributeName value:textBlockBorder range:range]; } - (void)setTextRubyAnnotation:(YYTextRubyAnnotation *)ruby range:(NSRange)range { if (kiOS8Later) { CTRubyAnnotationRef rubyRef = [ruby CTRubyAnnotation]; [self setRubyAnnotation:rubyRef range:range]; if (rubyRef) CFRelease(rubyRef); } } - (void)setTextGlyphTransform:(CGAffineTransform)textGlyphTransform range:(NSRange)range { NSValue *value = CGAffineTransformIsIdentity(textGlyphTransform) ? nil : [NSValue valueWithCGAffineTransform:textGlyphTransform]; [self setAttribute:YYTextGlyphTransformAttributeName value:value range:range]; } - (void)setTextHighlightRange:(NSRange)range color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor userInfo:(NSDictionary *)userInfo tapAction:(YYTextAction)tapAction longPressAction:(YYTextAction)longPressAction { YYTextHighlight *highlight = [YYTextHighlight highlightWithBackgroundColor:backgroundColor]; highlight.userInfo = userInfo; highlight.tapAction = tapAction; highlight.longPressAction = longPressAction; if (color) [self setColor:color range:range]; [self setTextHighlight:highlight range:range]; } - (void)setTextHighlightRange:(NSRange)range color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor tapAction:(YYTextAction)tapAction { [self setTextHighlightRange:range color:color backgroundColor:backgroundColor userInfo:nil tapAction:tapAction longPressAction:nil]; } - (void)setTextHighlightRange:(NSRange)range color:(UIColor *)color backgroundColor:(UIColor *)backgroundColor userInfo:(NSDictionary *)userInfo { [self setTextHighlightRange:range color:color backgroundColor:backgroundColor userInfo:userInfo tapAction:nil longPressAction:nil]; } - (void)insertString:(NSString *)string atIndex:(NSUInteger)location { [self replaceCharactersInRange:NSMakeRange(location, 0) withString:string]; [self removeDiscontinuousAttributesInRange:NSMakeRange(location, string.length)]; } - (void)appendString:(NSString *)string { NSUInteger length = self.length; [self replaceCharactersInRange:NSMakeRange(length, 0) withString:string]; [self removeDiscontinuousAttributesInRange:NSMakeRange(length, string.length)]; } - (void)setClearColorToJoinedEmoji { NSString *str = self.string; if (str.length < 8) return; // Most string do not contains the joined-emoji, test the joiner first. BOOL containsJoiner = NO; { CFStringRef cfStr = (__bridge CFStringRef)str; BOOL needFree = NO; UniChar *chars = NULL; chars = (void *)CFStringGetCharactersPtr(cfStr); if (!chars) { chars = malloc(str.length * sizeof(UniChar)); if (chars) { needFree = YES; CFStringGetCharacters(cfStr, CFRangeMake(0, str.length), chars); } } if (!chars) { // fail to get unichar.. containsJoiner = YES; } else { for (int i = 0, max = (int)str.length; i < max; i++) { if (chars[i] == 0x200D) { // 'ZERO WIDTH JOINER' (U+200D) containsJoiner = YES; break; } } if (needFree) free(chars); } } if (!containsJoiner) return; // NSRegularExpression is designed to be immutable and thread safe. static NSRegularExpression *regex; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ regex = [NSRegularExpression regularExpressionWithPattern:@"((||||||||)+|(||||))" options:kNilOptions error:nil]; }); UIColor *clear = [UIColor clearColor]; [regex enumerateMatchesInString:str options:kNilOptions range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { [self setColor:clear range:result.range]; }]; } - (void)removeDiscontinuousAttributesInRange:(NSRange)range { NSArray *keys = [NSMutableAttributedString allDiscontinuousAttributeKeys]; for (NSString *key in keys) { [self removeAttribute:key range:range]; } } + (NSArray *)allDiscontinuousAttributeKeys { static NSMutableArray *keys; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ keys = @[(id)kCTSuperscriptAttributeName, (id)kCTRunDelegateAttributeName, YYTextBackedStringAttributeName, YYTextBindingAttributeName, YYTextAttachmentAttributeName].mutableCopy; if (kiOS8Later) { [keys addObject:(id)kCTRubyAnnotationAttributeName]; } if (kiOS7Later) { [keys addObject:NSAttachmentAttributeName]; } }); return keys; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/NSAttributedString+YYText.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
10,547
```objective-c // // YYTextAttribute.h // YYKit <path_to_url // // Created by ibireme on 14/10/26. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN #pragma mark - Enum Define /// The attribute type typedef NS_OPTIONS(NSInteger, YYTextAttributeType) { YYTextAttributeTypeNone = 0, YYTextAttributeTypeUIKit = 1 << 0, ///< UIKit attributes, such as UILabel/UITextField/drawInRect. YYTextAttributeTypeCoreText = 1 << 1, ///< CoreText attributes, used by CoreText. YYTextAttributeTypeYYText = 1 << 2, ///< YYText attributes, used by YYText. }; /// Get the attribute type from an attribute name. extern YYTextAttributeType YYTextAttributeGetType(NSString *attributeName); /** Line style in YYText (similar to NSUnderlineStyle). */ typedef NS_OPTIONS (NSInteger, YYTextLineStyle) { // basic style (bitmask:0xFF) YYTextLineStyleNone = 0x00, ///< ( ) Do not draw a line (Default). YYTextLineStyleSingle = 0x01, ///< () Draw a single line. YYTextLineStyleThick = 0x02, ///< () Draw a thick line. YYTextLineStyleDouble = 0x09, ///< () Draw a double line. // style pattern (bitmask:0xF00) YYTextLineStylePatternSolid = 0x000, ///< () Draw a solid line (Default). YYTextLineStylePatternDot = 0x100, ///< ( ) Draw a line of dots. YYTextLineStylePatternDash = 0x200, ///< ( ) Draw a line of dashes. YYTextLineStylePatternDashDot = 0x300, ///< ( ) Draw a line of alternating dashes and dots. YYTextLineStylePatternDashDotDot = 0x400, ///< ( ) Draw a line of alternating dashes and two dots. YYTextLineStylePatternCircleDot = 0x900, ///< () Draw a line of small circle dots. }; /** Text vertical alignment. */ typedef NS_ENUM(NSInteger, YYTextVerticalAlignment) { YYTextVerticalAlignmentTop = 0, ///< Top alignment. YYTextVerticalAlignmentCenter = 1, ///< Center alignment. YYTextVerticalAlignmentBottom = 2, ///< Bottom alignment. }; /** The direction define in YYText. */ typedef NS_OPTIONS(NSUInteger, YYTextDirection) { YYTextDirectionNone = 0, YYTextDirectionTop = 1 << 0, YYTextDirectionRight = 1 << 1, YYTextDirectionBottom = 1 << 2, YYTextDirectionLeft = 1 << 3, }; /** The trunction type, tells the truncation engine which type of truncation is being requested. */ typedef NS_ENUM (NSUInteger, YYTextTruncationType) { /// No truncate. YYTextTruncationTypeNone = 0, /// Truncate at the beginning of the line, leaving the end portion visible. YYTextTruncationTypeStart = 1, /// Truncate at the end of the line, leaving the start portion visible. YYTextTruncationTypeEnd = 2, /// Truncate in the middle of the line, leaving both the start and the end portions visible. YYTextTruncationTypeMiddle = 3, }; #pragma mark - Attribute Name Defined in YYText /// The value of this attribute is a `YYTextBackedString` object. /// Use this attribute to store the original plain text if it is replaced by something else (such as attachment). UIKIT_EXTERN NSString *const YYTextBackedStringAttributeName; /// The value of this attribute is a `YYTextBinding` object. /// Use this attribute to bind a range of text together, as if it was a single charactor. UIKIT_EXTERN NSString *const YYTextBindingAttributeName; /// The value of this attribute is a `YYTextShadow` object. /// Use this attribute to add shadow to a range of text. /// Shadow will be drawn below text glyphs. Use YYTextShadow.subShadow to add multi-shadow. UIKIT_EXTERN NSString *const YYTextShadowAttributeName; /// The value of this attribute is a `YYTextShadow` object. /// Use this attribute to add inner shadow to a range of text. /// Inner shadow will be drawn above text glyphs. Use YYTextShadow.subShadow to add multi-shadow. UIKIT_EXTERN NSString *const YYTextInnerShadowAttributeName; /// The value of this attribute is a `YYTextDecoration` object. /// Use this attribute to add underline to a range of text. /// The underline will be drawn below text glyphs. UIKIT_EXTERN NSString *const YYTextUnderlineAttributeName; /// The value of this attribute is a `YYTextDecoration` object. /// Use this attribute to add strikethrough (delete line) to a range of text. /// The strikethrough will be drawn above text glyphs. UIKIT_EXTERN NSString *const YYTextStrikethroughAttributeName; /// The value of this attribute is a `YYTextBorder` object. /// Use this attribute to add cover border or cover color to a range of text. /// The border will be drawn above the text glyphs. UIKIT_EXTERN NSString *const YYTextBorderAttributeName; /// The value of this attribute is a `YYTextBorder` object. /// Use this attribute to add background border or background color to a range of text. /// The border will be drawn below the text glyphs. UIKIT_EXTERN NSString *const YYTextBackgroundBorderAttributeName; /// The value of this attribute is a `YYTextBorder` object. /// Use this attribute to add a code block border to one or more line of text. /// The border will be drawn below the text glyphs. UIKIT_EXTERN NSString *const YYTextBlockBorderAttributeName; /// The value of this attribute is a `YYTextAttachment` object. /// Use this attribute to add attachment to text. /// It should be used in conjunction with a CTRunDelegate. UIKIT_EXTERN NSString *const YYTextAttachmentAttributeName; /// The value of this attribute is a `YYTextHighlight` object. /// Use this attribute to add a touchable highlight state to a range of text. UIKIT_EXTERN NSString *const YYTextHighlightAttributeName; /// The value of this attribute is a `NSValue` object stores CGAffineTransform. /// Use this attribute to add transform to each glyph in a range of text. UIKIT_EXTERN NSString *const YYTextGlyphTransformAttributeName; #pragma mark - String Token Define UIKIT_EXTERN NSString *const YYTextAttachmentToken; ///< Object replacement character (U+FFFC), used for text attachment. UIKIT_EXTERN NSString *const YYTextTruncationToken; ///< Horizontal ellipsis (U+2026), used for text truncation "". #pragma mark - Attribute Value Define /** The tap/long press action callback defined in YYText. @param containerView The text container view (such as YYLabel/YYTextView). @param text The whole text. @param range The text range in `text` (if no range, the range.location is NSNotFound). @param rect The text frame in `containerView` (if no data, the rect is CGRectNull). */ typedef void(^YYTextAction)(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect); /** YYTextBackedString objects are used by the NSAttributedString class cluster as the values for text backed string attributes (stored in the attributed string under the key named YYTextBackedStringAttributeName). It may used for copy/paste plain text from attributed string. Example: If :) is replace by a custom emoji (such as), the backed string can be set to @":)". */ @interface YYTextBackedString : NSObject <NSCoding, NSCopying> + (instancetype)stringWithString:(nullable NSString *)string; @property (nullable, nonatomic, copy) NSString *string; ///< backed string @end /** YYTextBinding objects are used by the NSAttributedString class cluster as the values for shadow attributes (stored in the attributed string under the key named YYTextBindingAttributeName). Add this to a range of text will make the specified characters 'binding together'. YYTextView will treat the range of text as a single character during text selection and edit. */ @interface YYTextBinding : NSObject <NSCoding, NSCopying> + (instancetype)bindingWithDeleteConfirm:(BOOL)deleteConfirm; @property (nonatomic) BOOL deleteConfirm; ///< confirm the range when delete in YYTextView @end /** YYTextShadow objects are used by the NSAttributedString class cluster as the values for shadow attributes (stored in the attributed string under the key named YYTextShadowAttributeName or YYTextInnerShadowAttributeName). It's similar to `NSShadow`, but offers more options. */ @interface YYTextShadow : NSObject <NSCoding, NSCopying> + (instancetype)shadowWithColor:(nullable UIColor *)color offset:(CGSize)offset radius:(CGFloat)radius; @property (nullable, nonatomic, strong) UIColor *color; ///< shadow color @property (nonatomic) CGSize offset; ///< shadow offset @property (nonatomic) CGFloat radius; ///< shadow blur radius @property (nonatomic) CGBlendMode blendMode; ///< shadow blend mode @property (nullable, nonatomic, strong) YYTextShadow *subShadow; ///< a sub shadow which will be added above the parent shadow + (instancetype)shadowWithNSShadow:(NSShadow *)nsShadow; ///< convert NSShadow to YYTextShadow - (NSShadow *)nsShadow; ///< convert YYTextShadow to NSShadow @end /** YYTextDecorationLine objects are used by the NSAttributedString class cluster as the values for decoration line attributes (stored in the attributed string under the key named YYTextUnderlineAttributeName or YYTextStrikethroughAttributeName). When it's used as underline, the line is drawn below text glyphs; when it's used as strikethrough, the line is drawn above text glyphs. */ @interface YYTextDecoration : NSObject <NSCoding, NSCopying> + (instancetype)decorationWithStyle:(YYTextLineStyle)style; + (instancetype)decorationWithStyle:(YYTextLineStyle)style width:(nullable NSNumber *)width color:(nullable UIColor *)color; @property (nonatomic) YYTextLineStyle style; ///< line style @property (nullable, nonatomic, strong) NSNumber *width; ///< line width (nil means automatic width) @property (nullable, nonatomic, strong) UIColor *color; ///< line color (nil means automatic color) @property (nullable, nonatomic, strong) YYTextShadow *shadow; ///< line shadow @end /** YYTextBorder objects are used by the NSAttributedString class cluster as the values for border attributes (stored in the attributed string under the key named YYTextBorderAttributeName or YYTextBackgroundBorderAttributeName). It can be used to draw a border around a range of text, or draw a background to a range of text. Example: Text */ @interface YYTextBorder : NSObject <NSCoding, NSCopying> + (instancetype)borderWithLineStyle:(YYTextLineStyle)lineStyle lineWidth:(CGFloat)width strokeColor:(nullable UIColor *)color; + (instancetype)borderWithFillColor:(nullable UIColor *)color cornerRadius:(CGFloat)cornerRadius; @property (nonatomic) YYTextLineStyle lineStyle; ///< border line style @property (nonatomic) CGFloat strokeWidth; ///< border line width @property (nullable, nonatomic, strong) UIColor *strokeColor; ///< border line color @property (nonatomic) CGLineJoin lineJoin; ///< border line join @property (nonatomic) UIEdgeInsets insets; ///< border insets for text bounds @property (nonatomic) CGFloat cornerRadius; ///< border corder radius @property (nullable, nonatomic, strong) YYTextShadow *shadow; ///< border shadow @property (nullable, nonatomic, strong) UIColor *fillColor; ///< inner fill color @end /** YYTextAttachment objects are used by the NSAttributedString class cluster as the values for attachment attributes (stored in the attributed string under the key named YYTextAttachmentAttributeName). When display an attributed string which contains `YYTextAttachment` object, the content will be placed in text metric. If the content is `UIImage`, then it will be drawn to CGContext; if the content is `UIView` or `CALayer`, then it will be added to the text container's view or layer. */ @interface YYTextAttachment : NSObject<NSCoding, NSCopying> + (instancetype)attachmentWithContent:(nullable id)content; @property (nullable, nonatomic, strong) id content; ///< Supported type: UIImage, UIView, CALayer @property (nonatomic) UIViewContentMode contentMode; ///< Content display mode. @property (nonatomic) UIEdgeInsets contentInsets; ///< The insets when drawing content. @property (nullable, nonatomic, strong) NSDictionary *userInfo; ///< The user information dictionary. @end /** YYTextHighlight objects are used by the NSAttributedString class cluster as the values for touchable highlight attributes (stored in the attributed string under the key named YYTextHighlightAttributeName). When display an attributed string in `YYLabel` or `YYTextView`, the range of highlight text can be toucheds down by users. If a range of text is turned into highlighted state, the `attributes` in `YYTextHighlight` will be used to modify (set or remove) the original attributes in the range for display. */ @interface YYTextHighlight : NSObject <NSCoding, NSCopying> /** Attributes that you can apply to text in an attributed string when highlight. Key: Same as CoreText/YYText Attribute Name. Value: Modify attribute value when highlight (NSNull for remove attribute). */ @property (nullable, nonatomic, copy) NSDictionary<NSString *, id> *attributes; /** Creates a highlight object with specified attributes. @param attributes The attributes which will replace original attributes when highlight, If the value is NSNull, it will removed when highlight. */ + (instancetype)highlightWithAttributes:(nullable NSDictionary<NSString *, id> *)attributes; /** Convenience methods to create a default highlight with the specifeid background color. @param color The background border color. */ + (instancetype)highlightWithBackgroundColor:(nullable UIColor *)color; // Convenience methods below to set the `attributes`. - (void)setFont:(nullable UIFont *)font; - (void)setColor:(nullable UIColor *)color; - (void)setStrokeWidth:(nullable NSNumber *)width; - (void)setStrokeColor:(nullable UIColor *)color; - (void)setShadow:(nullable YYTextShadow *)shadow; - (void)setInnerShadow:(nullable YYTextShadow *)shadow; - (void)setUnderline:(nullable YYTextDecoration *)underline; - (void)setStrikethrough:(nullable YYTextDecoration *)strikethrough; - (void)setBackgroundBorder:(nullable YYTextBorder *)border; - (void)setBorder:(nullable YYTextBorder *)border; - (void)setAttachment:(nullable YYTextAttachment *)attachment; /** The user information dictionary, default is nil. */ @property (nullable, nonatomic, copy) NSDictionary *userInfo; /** Tap action when user tap the highlight, default is nil. If the value is nil, YYTextView or YYLabel will ask it's delegate to handle the tap action. */ @property (nullable, nonatomic, copy) YYTextAction tapAction; /** Long press action when user long press the highlight, default is nil. If the value is nil, YYTextView or YYLabel will ask it's delegate to handle the long press action. */ @property (nullable, nonatomic, copy) YYTextAction longPressAction; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextAttribute.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
3,334
```objective-c // // YYTextArchiver.h // YYKit <path_to_url // // Created by ibireme on 15/3/16. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** A subclass of `NSKeyedArchiver` which implement `NSKeyedArchiverDelegate` protocol. The archiver can encode the object which contains CGColor/CGImage/CTRunDelegateRef/.. (such as NSAttributedString). */ @interface YYTextArchiver : NSKeyedArchiver <NSKeyedArchiverDelegate> @end /** A subclass of `NSKeyedUnarchiver` which implement `NSKeyedUnarchiverDelegate` protocol. The unarchiver can decode the data which is encoded by `YYTextArchiver` or `NSKeyedArchiver`. */ @interface YYTextUnarchiver : NSKeyedUnarchiver <NSKeyedUnarchiverDelegate> @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextArchiver.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
233
```objective-c // // YYTextParser.h // YYKit <path_to_url // // Created by ibireme on 15/3/6. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** The YYTextParser protocol declares the required method for YYTextView and YYLabel to modify the text during editing. You can implement this protocol to add code highlighting or emoticon replacement for YYTextView and YYLabel. See `YYTextSimpleMarkdownParser` and `YYTextSimpleEmoticonParser` for example. */ @protocol YYTextParser <NSObject> @required /** When text is changed in YYTextView or YYLabel, this method will be called. @param text The original attributed string. This method may parse the text and change the text attributes or content. @param selectedRange Current selected range in `text`. This method should correct the range if the text content is changed. If there's no selected range (such as YYLabel), this value is NULL. @return If the 'text' is modified in this method, returns `YES`, otherwise returns `NO`. */ - (BOOL)parseText:(nullable NSMutableAttributedString *)text selectedRange:(nullable NSRangePointer)selectedRange; @end /** A simple markdown parser. It'a very simple markdown parser, you can use this parser to highlight some small piece of markdown text. This markdown parser use regular expression to parse text, slow and weak. If you want to write a better parser, try these projests: path_to_url path_to_url path_to_url Or you can use lex/yacc to generate your custom parser. */ @interface YYTextSimpleMarkdownParser : NSObject <YYTextParser> @property (nonatomic) CGFloat fontSize; ///< default is 14 @property (nonatomic) CGFloat headerFontSize; ///< default is 20 @property (nullable, nonatomic, strong) UIColor *textColor; @property (nullable, nonatomic, strong) UIColor *controlTextColor; @property (nullable, nonatomic, strong) UIColor *headerTextColor; @property (nullable, nonatomic, strong) UIColor *inlineTextColor; @property (nullable, nonatomic, strong) UIColor *codeTextColor; @property (nullable, nonatomic, strong) UIColor *linkTextColor; - (void)setColorWithBrightTheme; ///< reset the color properties to pre-defined value. - (void)setColorWithDarkTheme; ///< reset the color properties to pre-defined value. @end /** A simple emoticon parser. Use this parser to map some specified piece of string to image emoticon. Example: "Hello :smile:" -> "Hello " It can also be used to extend the "unicode emoticon". */ @interface YYTextSimpleEmoticonParser : NSObject <YYTextParser> /** The custom emoticon mapper. The key is a specified plain string, such as @":smile:". The value is a UIImage which will replace the specified plain string in text. */ @property (nullable, copy) NSDictionary<NSString *, __kindof UIImage *> *emoticonMapper; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextParser.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
668
```objective-c // // NSParagraphStyle+YYText.h // YYKit <path_to_url // // Created by ibireme on 14/10/7. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** Provides extensions for `NSParagraphStyle` to work with CoreText. */ @interface NSParagraphStyle (YYText) /** Creates a new NSParagraphStyle object from the CoreText Style. @param CTStyle CoreText Paragraph Style. @return a new NSParagraphStyle */ + (nullable NSParagraphStyle *)styleWithCTStyle:(CTParagraphStyleRef)CTStyle; /** Creates and returns a CoreText Paragraph Style. (need call CFRelease() after used) */ - (nullable CTParagraphStyleRef)CTStyle CF_RETURNS_RETAINED; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/NSParagraphStyle+YYText.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
202
```objective-c // // NSParagraphStyle+YYText.m // YYKit <path_to_url // // Created by ibireme on 14/10/7. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "NSParagraphStyle+YYText.h" #import "YYKitMacro.h" #import "YYTextAttribute.h" #import <CoreText/CoreText.h> YYSYNTH_DUMMY_CLASS(NSParagraphStyle_YYText) @implementation NSParagraphStyle (YYText) + (NSParagraphStyle *)styleWithCTStyle:(CTParagraphStyleRef)CTStyle { if (CTStyle == NULL) return nil; NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CGFloat lineSpacing; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierLineSpacing, sizeof(CGFloat), &lineSpacing)) { style.lineSpacing = lineSpacing; } #pragma clang diagnostic pop CGFloat paragraphSpacing; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierParagraphSpacing, sizeof(CGFloat), &paragraphSpacing)) { style.paragraphSpacing = paragraphSpacing; } CTTextAlignment alignment; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &alignment)) { style.alignment = NSTextAlignmentFromCTTextAlignment(alignment); } CGFloat firstLineHeadIndent; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(CGFloat), &firstLineHeadIndent)) { style.firstLineHeadIndent = firstLineHeadIndent; } CGFloat headIndent; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierHeadIndent, sizeof(CGFloat), &headIndent)) { style.headIndent = headIndent; } CGFloat tailIndent; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierTailIndent, sizeof(CGFloat), &tailIndent)) { style.tailIndent = tailIndent; } CTLineBreakMode lineBreakMode; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierLineBreakMode, sizeof(CTLineBreakMode), &lineBreakMode)) { style.lineBreakMode = (NSLineBreakMode)lineBreakMode; } CGFloat minimumLineHeight; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(CGFloat), &minimumLineHeight)) { style.minimumLineHeight = minimumLineHeight; } CGFloat maximumLineHeight; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(CGFloat), &maximumLineHeight)) { style.maximumLineHeight = maximumLineHeight; } CTWritingDirection baseWritingDirection; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierBaseWritingDirection, sizeof(CTWritingDirection), &baseWritingDirection)) { style.baseWritingDirection = (NSWritingDirection)baseWritingDirection; } CGFloat lineHeightMultiple; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierLineHeightMultiple, sizeof(CGFloat), &lineHeightMultiple)) { style.lineHeightMultiple = lineHeightMultiple; } CGFloat paragraphSpacingBefore; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(CGFloat), &paragraphSpacingBefore)) { style.paragraphSpacingBefore = paragraphSpacingBefore; } if ([style respondsToSelector:@selector(tabStops)]) { CFArrayRef tabStops; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierTabStops, sizeof(CFArrayRef), &tabStops)) { if ([style respondsToSelector:@selector(setTabStops:)]) { NSMutableArray *tabs = [NSMutableArray new]; [((__bridge NSArray *)(tabStops))enumerateObjectsUsingBlock : ^(id obj, NSUInteger idx, BOOL *stop) { CTTextTabRef ctTab = (__bridge CFTypeRef)obj; NSTextTab *tab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentFromCTTextAlignment(CTTextTabGetAlignment(ctTab)) location:CTTextTabGetLocation(ctTab) options:(__bridge id)CTTextTabGetOptions(ctTab)]; [tabs addObject:tab]; }]; if (tabs.count) { style.tabStops = tabs; } } } CGFloat defaultTabInterval; if (CTParagraphStyleGetValueForSpecifier(CTStyle, kCTParagraphStyleSpecifierDefaultTabInterval, sizeof(CGFloat), &defaultTabInterval)) { if ([style respondsToSelector:@selector(setDefaultTabInterval:)]) { style.defaultTabInterval = defaultTabInterval; } } } return style; } - (CTParagraphStyleRef)CTStyle CF_RETURNS_RETAINED { CTParagraphStyleSetting set[kCTParagraphStyleSpecifierCount] = { 0 }; int count = 0; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CGFloat lineSpacing = self.lineSpacing; set[count].spec = kCTParagraphStyleSpecifierLineSpacing; set[count].valueSize = sizeof(CGFloat); set[count].value = &lineSpacing; count++; #pragma clang diagnostic pop CGFloat paragraphSpacing = self.paragraphSpacing; set[count].spec = kCTParagraphStyleSpecifierParagraphSpacing; set[count].valueSize = sizeof(CGFloat); set[count].value = &paragraphSpacing; count++; CTTextAlignment alignment = NSTextAlignmentToCTTextAlignment(self.alignment); set[count].spec = kCTParagraphStyleSpecifierAlignment; set[count].valueSize = sizeof(CTTextAlignment); set[count].value = &alignment; count++; CGFloat firstLineHeadIndent = self.firstLineHeadIndent; set[count].spec = kCTParagraphStyleSpecifierFirstLineHeadIndent; set[count].valueSize = sizeof(CGFloat); set[count].value = &firstLineHeadIndent; count++; CGFloat headIndent = self.headIndent; set[count].spec = kCTParagraphStyleSpecifierHeadIndent; set[count].valueSize = sizeof(CGFloat); set[count].value = &headIndent; count++; CGFloat tailIndent = self.tailIndent; set[count].spec = kCTParagraphStyleSpecifierTailIndent; set[count].valueSize = sizeof(CGFloat); set[count].value = &tailIndent; count++; CTLineBreakMode paraLineBreak = (CTLineBreakMode)self.lineBreakMode; set[count].spec = kCTParagraphStyleSpecifierLineBreakMode; set[count].valueSize = sizeof(CTLineBreakMode); set[count].value = &paraLineBreak; count++; CGFloat minimumLineHeight = self.minimumLineHeight; set[count].spec = kCTParagraphStyleSpecifierMinimumLineHeight; set[count].valueSize = sizeof(CGFloat); set[count].value = &minimumLineHeight; count++; CGFloat maximumLineHeight = self.maximumLineHeight; set[count].spec = kCTParagraphStyleSpecifierMaximumLineHeight; set[count].valueSize = sizeof(CGFloat); set[count].value = &maximumLineHeight; count++; CTWritingDirection paraWritingDirection = (CTWritingDirection)self.baseWritingDirection; set[count].spec = kCTParagraphStyleSpecifierBaseWritingDirection; set[count].valueSize = sizeof(CTWritingDirection); set[count].value = &paraWritingDirection; count++; CGFloat lineHeightMultiple = self.lineHeightMultiple; set[count].spec = kCTParagraphStyleSpecifierLineHeightMultiple; set[count].valueSize = sizeof(CGFloat); set[count].value = &lineHeightMultiple; count++; CGFloat paragraphSpacingBefore = self.paragraphSpacingBefore; set[count].spec = kCTParagraphStyleSpecifierParagraphSpacingBefore; set[count].valueSize = sizeof(CGFloat); set[count].value = &paragraphSpacingBefore; count++; if([self respondsToSelector:@selector(tabStops)]) { NSMutableArray *tabs = [NSMutableArray array]; if ([self respondsToSelector:@selector(tabStops)]) { NSInteger numTabs = self.tabStops.count; if (numTabs) { [self.tabStops enumerateObjectsUsingBlock: ^(NSTextTab *tab, NSUInteger idx, BOOL *stop) { CTTextTabRef ctTab = CTTextTabCreate(NSTextAlignmentToCTTextAlignment(tab.alignment), tab.location, (__bridge CFTypeRef)tab.options); [tabs addObject:(__bridge id)ctTab]; CFRelease(ctTab); }]; CFArrayRef tabStops = (__bridge CFArrayRef)(tabs); set[count].spec = kCTParagraphStyleSpecifierTabStops; set[count].valueSize = sizeof(CFArrayRef); set[count].value = &tabStops; count++; } } if ([self respondsToSelector:@selector(defaultTabInterval)]) { CGFloat defaultTabInterval = self.defaultTabInterval; set[count].spec = kCTParagraphStyleSpecifierDefaultTabInterval; set[count].valueSize = sizeof(CGFloat); set[count].value = &defaultTabInterval; count++; } } CTParagraphStyleRef style = CTParagraphStyleCreate(set, count); return style; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/NSParagraphStyle+YYText.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,074
```objective-c // // YYTextRunDelegate.h // YYKit <path_to_url // // Created by ibireme on 14/10/14. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> NS_ASSUME_NONNULL_BEGIN /** Wrapper for CTRunDelegateRef. Example: YYTextRunDelegate *delegate = [YYTextRunDelegate new]; delegate.ascent = 20; delegate.descent = 4; delegate.width = 20; CTRunDelegateRef ctRunDelegate = delegate.CTRunDelegate; if (ctRunDelegate) { /// add to attributed string CFRelease(ctRunDelegate); } */ @interface YYTextRunDelegate : NSObject <NSCopying, NSCoding> /** Creates and returns the CTRunDelegate. @discussion You need call CFRelease() after used. The CTRunDelegateRef has a strong reference to this YYTextRunDelegate object. In CoreText, use CTRunDelegateGetRefCon() to get this YYTextRunDelegate object. @return The CTRunDelegate object. */ - (nullable CTRunDelegateRef)CTRunDelegate CF_RETURNS_RETAINED; /** Additional information about the the run delegate. */ @property (nullable, nonatomic, strong) NSDictionary *userInfo; /** The typographic ascent of glyphs in the run. */ @property (nonatomic) CGFloat ascent; /** The typographic descent of glyphs in the run. */ @property (nonatomic) CGFloat descent; /** The typographic width of glyphs in the run. */ @property (nonatomic) CGFloat width; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextRunDelegate.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
369
```objective-c // // YYTextRunDelegate.m // YYKit <path_to_url // // Created by ibireme on 14/10/14. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextRunDelegate.h" static void DeallocCallback(void *ref) { YYTextRunDelegate *self = (__bridge_transfer YYTextRunDelegate *)(ref); self = nil; // release } static CGFloat GetAscentCallback(void *ref) { YYTextRunDelegate *self = (__bridge YYTextRunDelegate *)(ref); return self.ascent; } static CGFloat GetDecentCallback(void *ref) { YYTextRunDelegate *self = (__bridge YYTextRunDelegate *)(ref); return self.descent; } static CGFloat GetWidthCallback(void *ref) { YYTextRunDelegate *self = (__bridge YYTextRunDelegate *)(ref); return self.width; } @implementation YYTextRunDelegate - (CTRunDelegateRef)CTRunDelegate CF_RETURNS_RETAINED { CTRunDelegateCallbacks callbacks; callbacks.version = kCTRunDelegateCurrentVersion; callbacks.dealloc = DeallocCallback; callbacks.getAscent = GetAscentCallback; callbacks.getDescent = GetDecentCallback; callbacks.getWidth = GetWidthCallback; return CTRunDelegateCreate(&callbacks, (__bridge_retained void *)(self.copy)); } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:@(_ascent) forKey:@"ascent"]; [aCoder encodeObject:@(_descent) forKey:@"descent"]; [aCoder encodeObject:@(_width) forKey:@"width"]; [aCoder encodeObject:_userInfo forKey:@"userInfo"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; _ascent = ((NSNumber *)[aDecoder decodeObjectForKey:@"ascent"]).floatValue; _descent = ((NSNumber *)[aDecoder decodeObjectForKey:@"descent"]).floatValue; _width = ((NSNumber *)[aDecoder decodeObjectForKey:@"width"]).floatValue; _userInfo = [aDecoder decodeObjectForKey:@"userInfo"]; return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; one.ascent = self.ascent; one.descent = self.descent; one.width = self.width; one.userInfo = self.userInfo; return one; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextRunDelegate.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
544
```objective-c // // YYTextParser.m // YYKit <path_to_url // // Created by ibireme on 15/3/6. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextParser.h" #import "YYCGUtilities.h" #import "YYTextUtilities.h" #import "YYTextAttribute.h" #import "NSAttributedString+YYText.h" #import "NSParagraphStyle+YYText.h" #import "UIFont+YYAdd.h" #pragma mark - Markdown Parser @implementation YYTextSimpleMarkdownParser { UIFont *_font; NSMutableArray *_headerFonts; ///< h1~h6 UIFont *_boldFont; UIFont *_italicFont; UIFont *_boldItalicFont; UIFont *_monospaceFont; YYTextBorder *_border; NSRegularExpression *_regexEscape; ///< escape NSRegularExpression *_regexHeader; ///< #header NSRegularExpression *_regexH1; ///< header\n==== NSRegularExpression *_regexH2; ///< header\n---- NSRegularExpression *_regexBreakline; ///< ****** NSRegularExpression *_regexEmphasis; ///< *text* _text_ NSRegularExpression *_regexStrong; ///< **text** NSRegularExpression *_regexStrongEmphasis; ///< ***text*** ___text___ NSRegularExpression *_regexUnderline; ///< __text__ NSRegularExpression *_regexStrikethrough; ///< ~~text~~ NSRegularExpression *_regexInlineCode; ///< `text` NSRegularExpression *_regexLink; ///< [name](link) NSRegularExpression *_regexLinkRefer; ///< [ref]: NSRegularExpression *_regexList; ///< 1.text 2.text 3.text NSRegularExpression *_regexBlockQuote; ///< > quote NSRegularExpression *_regexCodeBlock; ///< \tcode \tcode NSRegularExpression *_regexNotEmptyLine; } - (void)initRegex { #define regexp(reg, option) [NSRegularExpression regularExpressionWithPattern : @reg options : option error : NULL] _regexEscape = regexp("(\\\\\\\\|\\\\\\`|\\\\\\*|\\\\\\_|\\\\\\(|\\\\\\)|\\\\\\[|\\\\\\]|\\\\#|\\\\\\+|\\\\\\-|\\\\\\!)", 0); _regexHeader = regexp("^((\\#{1,6}[^#].*)|(\\#{6}.+))$", NSRegularExpressionAnchorsMatchLines); _regexH1 = regexp("^[^=\\n][^\\n]*\\n=+$", NSRegularExpressionAnchorsMatchLines); _regexH2 = regexp("^[^-\\n][^\\n]*\\n-+$", NSRegularExpressionAnchorsMatchLines); _regexBreakline = regexp("^[ \\t]*([*-])[ \\t]*((\\1)[ \\t]*){2,}[ \\t]*$", NSRegularExpressionAnchorsMatchLines); _regexEmphasis = regexp("((?<!\\*)\\*(?=[^ \\t*])(.+?)(?<=[^ \\t*])\\*(?!\\*)|(?<!_)_(?=[^ \\t_])(.+?)(?<=[^ \\t_])_(?!_))", 0); _regexStrong = regexp("(?<!\\*)\\*{2}(?=[^ \\t*])(.+?)(?<=[^ \\t*])\\*{2}(?!\\*)", 0); _regexStrongEmphasis = regexp("((?<!\\*)\\*{3}(?=[^ \\t*])(.+?)(?<=[^ \\t*])\\*{3}(?!\\*)|(?<!_)_{3}(?=[^ \\t_])(.+?)(?<=[^ \\t_])_{3}(?!_))", 0); _regexUnderline = regexp("(?<!_)__(?=[^ \\t_])(.+?)(?<=[^ \\t_])\\__(?!_)", 0); _regexStrikethrough = regexp("(?<!~)~~(?=[^ \\t~])(.+?)(?<=[^ \\t~])\\~~(?!~)", 0); _regexInlineCode = regexp("(?<!`)(`{1,3})([^`\n]+?)\\1(?!`)", 0); _regexLink = regexp("!?\\[([^\\[\\]]+)\\](\\(([^\\(\\)]+)\\)|\\[([^\\[\\]]+)\\])", 0); _regexLinkRefer = regexp("^[ \\t]*\\[[^\\[\\]]\\]:", NSRegularExpressionAnchorsMatchLines); _regexList = regexp("^[ \\t]*([*+-]|\\d+[.])[ \\t]+", NSRegularExpressionAnchorsMatchLines); _regexBlockQuote = regexp("^[ \\t]*>[ \\t>]*", NSRegularExpressionAnchorsMatchLines); _regexCodeBlock = regexp("(^\\s*$\\n)((( {4}|\\t).*(\\n|\\z))|(^\\s*$\\n))+", NSRegularExpressionAnchorsMatchLines); _regexNotEmptyLine = regexp("^[ \\t]*[^ \\t]+[ \\t]*$", NSRegularExpressionAnchorsMatchLines); #undef regexp } - (instancetype)init { self = [super init]; _fontSize = 14; _headerFontSize = 20; [self _updateFonts]; [self setColorWithBrightTheme]; [self initRegex]; return self; } - (void)setFontSize:(CGFloat)fontSize { if (fontSize < 1) fontSize = 12; _fontSize = fontSize; [self _updateFonts]; } - (void)setHeaderFontSize:(CGFloat)headerFontSize { if (headerFontSize < 1) headerFontSize = 20; _headerFontSize = headerFontSize; [self _updateFonts]; } - (void)_updateFonts { _font = [UIFont systemFontOfSize:_fontSize]; _headerFonts = [NSMutableArray new]; for (int i = 0; i < 6; i++) { CGFloat size = _headerFontSize - (_headerFontSize - _fontSize) / 5.0 * i; [_headerFonts addObject:[UIFont systemFontOfSize:size]]; } _boldFont = [_font fontWithBold]; _italicFont = [_font fontWithItalic]; _boldItalicFont = [_font fontWithBoldItalic]; _monospaceFont = [UIFont fontWithName:@"Menlo" size:_fontSize]; // Since iOS 7 if (!_monospaceFont) _monospaceFont = [UIFont fontWithName:@"Courier" size:_fontSize]; // Since iOS 3 } - (void)setColorWithBrightTheme { _textColor = [UIColor blackColor]; _controlTextColor = [UIColor colorWithWhite:0.749 alpha:1.000]; _headerTextColor = [UIColor colorWithRed:1.000 green:0.502 blue:0.000 alpha:1.000]; _inlineTextColor = [UIColor colorWithWhite:0.150 alpha:1.000]; _codeTextColor = [UIColor colorWithWhite:0.150 alpha:1.000]; _linkTextColor = [UIColor colorWithRed:0.000 green:0.478 blue:0.962 alpha:1.000]; _border = [YYTextBorder new]; _border.lineStyle = YYTextLineStyleSingle; _border.fillColor = [UIColor colorWithWhite:0.184 alpha:0.090]; _border.strokeColor = [UIColor colorWithWhite:0.546 alpha:0.650]; _border.insets = UIEdgeInsetsMake(-1, 0, -1, 0); _border.cornerRadius = 2; _border.strokeWidth = CGFloatFromPixel(1); } - (void)setColorWithDarkTheme { _textColor = [UIColor whiteColor]; _controlTextColor = [UIColor colorWithWhite:0.604 alpha:1.000]; _headerTextColor = [UIColor colorWithRed:0.558 green:1.000 blue:0.502 alpha:1.000]; _inlineTextColor = [UIColor colorWithRed:1.000 green:0.862 blue:0.387 alpha:1.000]; _codeTextColor = [UIColor colorWithWhite:0.906 alpha:1.000]; _linkTextColor = [UIColor colorWithRed:0.000 green:0.646 blue:1.000 alpha:1.000]; _border = [YYTextBorder new]; _border.lineStyle = YYTextLineStyleSingle; _border.fillColor = [UIColor colorWithWhite:0.820 alpha:0.130]; _border.strokeColor = [UIColor colorWithWhite:1.000 alpha:0.280]; _border.insets = UIEdgeInsetsMake(-1, 0, -1, 0); _border.cornerRadius = 2; _border.strokeWidth = CGFloatFromPixel(1); } - (NSUInteger)lenghOfBeginWhiteInString:(NSString *)str withRange:(NSRange)range{ for (NSUInteger i = 0; i < range.length; i++) { unichar c = [str characterAtIndex:i + range.location]; if (c != ' ' && c != '\t' && c != '\n') return i; } return str.length; } - (NSUInteger)lenghOfEndWhiteInString:(NSString *)str withRange:(NSRange)range{ for (NSInteger i = range.length - 1; i >= 0; i--) { unichar c = [str characterAtIndex:i + range.location]; if (c != ' ' && c != '\t' && c != '\n') return range.length - i; } return str.length; } - (NSUInteger)lenghOfBeginChar:(unichar)c inString:(NSString *)str withRange:(NSRange)range{ for (NSUInteger i = 0; i < range.length; i++) { if ([str characterAtIndex:i + range.location] != c) return i; } return str.length; } - (BOOL)parseText:(NSMutableAttributedString *)text selectedRange:(NSRangePointer)range { if (text.length == 0) return NO; [text removeAttributesInRange:NSMakeRange(0, text.length)]; text.font = _font; text.color = _textColor; NSMutableString *str = text.string.mutableCopy; [_regexEscape replaceMatchesInString:str options:kNilOptions range:NSMakeRange(0, str.length) withTemplate:@"@@"]; [_regexHeader enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; NSUInteger whiteLen = [self lenghOfBeginWhiteInString:str withRange:r]; NSUInteger sharpLen = [self lenghOfBeginChar:'#' inString:str withRange:NSMakeRange(r.location + whiteLen, r.length - whiteLen)]; if (sharpLen > 6) sharpLen = 6; [text setColor:_controlTextColor range:NSMakeRange(r.location, whiteLen + sharpLen)]; [text setColor:_headerTextColor range:NSMakeRange(r.location + whiteLen + sharpLen, r.length - whiteLen - sharpLen)]; [text setFont:_headerFonts[sharpLen - 1] range:result.range]; }]; [_regexH1 enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; NSRange linebreak = [str rangeOfString:@"\n" options:0 range:result.range locale:nil]; if (linebreak.location != NSNotFound) { [text setColor:_headerTextColor range:NSMakeRange(r.location, linebreak.location - r.location)]; [text setFont:_headerFonts[0] range:NSMakeRange(r.location, linebreak.location - r.location + 1)]; [text setColor:_controlTextColor range:NSMakeRange(linebreak.location + linebreak.length, r.location + r.length - linebreak.location - linebreak.length)]; } }]; [_regexH2 enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; NSRange linebreak = [str rangeOfString:@"\n" options:0 range:result.range locale:nil]; if (linebreak.location != NSNotFound) { [text setColor:_headerTextColor range:NSMakeRange(r.location, linebreak.location - r.location)]; [text setFont:_headerFonts[1] range:NSMakeRange(r.location, linebreak.location - r.location + 1)]; [text setColor:_controlTextColor range:NSMakeRange(linebreak.location + linebreak.length, r.location + r.length - linebreak.location - linebreak.length)]; } }]; [_regexBreakline enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { [text setColor:_controlTextColor range:result.range]; }]; [_regexEmphasis enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:NSMakeRange(r.location, 1)]; [text setColor:_controlTextColor range:NSMakeRange(r.location + r.length - 1, 1)]; [text setFont:_italicFont range:NSMakeRange(r.location + 1, r.length - 2)]; }]; [_regexStrong enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:NSMakeRange(r.location, 2)]; [text setColor:_controlTextColor range:NSMakeRange(r.location + r.length - 2, 2)]; [text setFont:_boldFont range:NSMakeRange(r.location + 2, r.length - 4)]; }]; [_regexStrongEmphasis enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:NSMakeRange(r.location, 3)]; [text setColor:_controlTextColor range:NSMakeRange(r.location + r.length - 3, 3)]; [text setFont:_boldItalicFont range:NSMakeRange(r.location + 3, r.length - 6)]; }]; [_regexUnderline enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:NSMakeRange(r.location, 2)]; [text setColor:_controlTextColor range:NSMakeRange(r.location + r.length - 2, 2)]; [text setTextUnderline:[YYTextDecoration decorationWithStyle:YYTextLineStyleSingle width:@1 color:nil] range:NSMakeRange(r.location + 2, r.length - 4)]; }]; [_regexStrikethrough enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:NSMakeRange(r.location, 2)]; [text setColor:_controlTextColor range:NSMakeRange(r.location + r.length - 2, 2)]; [text setTextStrikethrough:[YYTextDecoration decorationWithStyle:YYTextLineStyleSingle width:@1 color:nil] range:NSMakeRange(r.location + 2, r.length - 4)]; }]; [_regexInlineCode enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; NSUInteger len = [self lenghOfBeginChar:'`' inString:str withRange:r]; [text setColor:_controlTextColor range:NSMakeRange(r.location, len)]; [text setColor:_controlTextColor range:NSMakeRange(r.location + r.length - len, len)]; [text setColor:_inlineTextColor range:NSMakeRange(r.location + len, r.length - 2 * len)]; [text setFont:_monospaceFont range:r]; [text setTextBorder:_border.copy range:r]; }]; [_regexLink enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_linkTextColor range:r]; }]; [_regexLinkRefer enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:r]; }]; [_regexList enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:r]; }]; [_regexBlockQuote enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; [text setColor:_controlTextColor range:r]; }]; [_regexCodeBlock enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange r = result.range; NSRange firstLineRange = [_regexNotEmptyLine rangeOfFirstMatchInString:str options:kNilOptions range:r]; NSUInteger lenStart = (firstLineRange.location != NSNotFound) ? firstLineRange.location - r.location : 0; NSUInteger lenEnd = [self lenghOfEndWhiteInString:str withRange:r]; if (lenStart + lenEnd < r.length) { NSRange codeR = NSMakeRange(r.location + lenStart, r.length - lenStart - lenEnd); [text setColor:_codeTextColor range:codeR]; [text setFont:_monospaceFont range:codeR]; YYTextBorder *border = [YYTextBorder new]; border.lineStyle = YYTextLineStyleSingle; border.fillColor = [UIColor colorWithWhite:0.184 alpha:0.090]; border.strokeColor = [UIColor colorWithWhite:0.200 alpha:0.300]; border.insets = UIEdgeInsetsMake(-1, 0, -1, 0); border.cornerRadius = 3; border.strokeWidth = CGFloatFromPixel(2); [text setTextBlockBorder:_border.copy range:codeR]; } }]; return YES; } @end #pragma mark - Emoticon Parser #define LOCK(...) dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \ __VA_ARGS__; \ dispatch_semaphore_signal(_lock); @implementation YYTextSimpleEmoticonParser { NSRegularExpression *_regex; NSDictionary *_mapper; dispatch_semaphore_t _lock; } - (instancetype)init { self = [super init]; _lock = dispatch_semaphore_create(1); return self; } - (NSDictionary *)emoticonMapper { LOCK(NSDictionary *mapper = _mapper); return mapper; } - (void)setEmoticonMapper:(NSDictionary *)emoticonMapper { LOCK( _mapper = emoticonMapper.copy; if (_mapper.count == 0) { _regex = nil; } else { NSMutableString *pattern = @"(".mutableCopy; NSArray *allKeys = _mapper.allKeys; NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@"$^?+*.,#|{}[]()\\"]; for (NSUInteger i = 0, max = allKeys.count; i < max; i++) { NSMutableString *one = [allKeys[i] mutableCopy]; // escape regex characters for (NSUInteger ci = 0, cmax = one.length; ci < cmax; ci++) { unichar c = [one characterAtIndex:ci]; if ([charset characterIsMember:c]) { [one insertString:@"\\" atIndex:ci]; ci++; cmax++; } } [pattern appendString:one]; if (i != max - 1) [pattern appendString:@"|"]; } [pattern appendString:@")"]; _regex = [[NSRegularExpression alloc] initWithPattern:pattern options:kNilOptions error:nil]; } ); } // correct the selected range during text replacement - (NSRange)_replaceTextInRange:(NSRange)range withLength:(NSUInteger)length selectedRange:(NSRange)selectedRange { // no change if (range.length == length) return selectedRange; // right if (range.location >= selectedRange.location + selectedRange.length) return selectedRange; // left if (selectedRange.location >= range.location + range.length) { selectedRange.location = selectedRange.location + length - range.length; return selectedRange; } // same if (NSEqualRanges(range, selectedRange)) { selectedRange.length = length; return selectedRange; } // one edge same if ((range.location == selectedRange.location && range.length < selectedRange.length) || (range.location + range.length == selectedRange.location + selectedRange.length && range.length < selectedRange.length)) { selectedRange.length = selectedRange.length + length - range.length; return selectedRange; } selectedRange.location = range.location + length; selectedRange.length = 0; return selectedRange; } - (BOOL)parseText:(NSMutableAttributedString *)text selectedRange:(NSRangePointer)range { if (text.length == 0) return NO; NSDictionary *mapper; NSRegularExpression *regex; LOCK(mapper = _mapper; regex = _regex;); if (mapper.count == 0 || regex == nil) return NO; NSArray *matches = [regex matchesInString:text.string options:kNilOptions range:NSMakeRange(0, text.length)]; if (matches.count == 0) return NO; NSRange selectedRange = range ? *range : NSMakeRange(0, 0); NSUInteger cutLength = 0; for (NSUInteger i = 0, max = matches.count; i < max; i++) { NSTextCheckingResult *one = matches[i]; NSRange oneRange = one.range; if (oneRange.length == 0) continue; oneRange.location -= cutLength; NSString *subStr = [text.string substringWithRange:oneRange]; UIImage *emoticon = mapper[subStr]; if (!emoticon) continue; CGFloat fontSize = 12; // CoreText default value CTFontRef font = (__bridge CTFontRef)([text attribute:NSFontAttributeName atIndex:oneRange.location]); if (font) fontSize = CTFontGetSize(font); NSMutableAttributedString *atr = [NSAttributedString attachmentStringWithEmojiImage:emoticon fontSize:fontSize]; [atr setTextBackedString:[YYTextBackedString stringWithString:subStr] range:NSMakeRange(0, atr.length)]; [text replaceCharactersInRange:oneRange withString:atr.string]; [text removeDiscontinuousAttributesInRange:NSMakeRange(oneRange.location, atr.length)]; [text addAttributes:atr.attributes range:NSMakeRange(oneRange.location, atr.length)]; selectedRange = [self _replaceTextInRange:oneRange withLength:atr.length selectedRange:selectedRange]; cutLength += oneRange.length - 1; } if (range) *range = selectedRange; return YES; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextParser.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
5,155
```objective-c // // YYTextAttribute.m // YYKit <path_to_url // // Created by ibireme on 14/10/26. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextAttribute.h" #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> #import "NSObject+YYAdd.h" #import "NSAttributedString+YYText.h" #import "YYAnimatedImageView.h" #import "YYTextArchiver.h" #import "UIFont+YYAdd.h" #import "UIDevice+YYAdd.h" NSString *const YYTextBackedStringAttributeName = @"YYTextBackedString"; NSString *const YYTextBindingAttributeName = @"YYTextBinding"; NSString *const YYTextShadowAttributeName = @"YYTextShadow"; NSString *const YYTextInnerShadowAttributeName = @"YYTextInnerShadow"; NSString *const YYTextUnderlineAttributeName = @"YYTextUnderline"; NSString *const YYTextStrikethroughAttributeName = @"YYTextStrikethrough"; NSString *const YYTextBorderAttributeName = @"YYTextBorder"; NSString *const YYTextBackgroundBorderAttributeName = @"YYTextBackgroundBorder"; NSString *const YYTextBlockBorderAttributeName = @"YYTextBlockBorder"; NSString *const YYTextAttachmentAttributeName = @"YYTextAttachment"; NSString *const YYTextHighlightAttributeName = @"YYTextHighlight"; NSString *const YYTextGlyphTransformAttributeName = @"YYTextGlyphTransform"; NSString *const YYTextAttachmentToken = @"\uFFFC"; NSString *const YYTextTruncationToken = @"\u2026"; YYTextAttributeType YYTextAttributeGetType(NSString *name){ if (name.length == 0) return YYTextAttributeTypeNone; static NSMutableDictionary *dic; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ dic = [NSMutableDictionary new]; NSNumber *All = @(YYTextAttributeTypeUIKit | YYTextAttributeTypeCoreText | YYTextAttributeTypeYYText); NSNumber *CoreText_YYText = @(YYTextAttributeTypeCoreText | YYTextAttributeTypeYYText); NSNumber *UIKit_YYText = @(YYTextAttributeTypeUIKit | YYTextAttributeTypeYYText); NSNumber *UIKit_CoreText = @(YYTextAttributeTypeUIKit | YYTextAttributeTypeCoreText); NSNumber *UIKit = @(YYTextAttributeTypeUIKit); NSNumber *CoreText = @(YYTextAttributeTypeCoreText); NSNumber *YYText = @(YYTextAttributeTypeYYText); dic[NSFontAttributeName] = All; dic[NSKernAttributeName] = All; dic[NSForegroundColorAttributeName] = UIKit; dic[(id)kCTForegroundColorAttributeName] = CoreText; dic[(id)kCTForegroundColorFromContextAttributeName] = CoreText; dic[NSBackgroundColorAttributeName] = UIKit; dic[NSStrokeWidthAttributeName] = All; dic[NSStrokeColorAttributeName] = UIKit; dic[(id)kCTStrokeColorAttributeName] = CoreText_YYText; dic[NSShadowAttributeName] = UIKit_YYText; dic[NSStrikethroughStyleAttributeName] = UIKit; dic[NSUnderlineStyleAttributeName] = UIKit_CoreText; dic[(id)kCTUnderlineColorAttributeName] = CoreText; dic[NSLigatureAttributeName] = All; dic[(id)kCTSuperscriptAttributeName] = UIKit; //it's a CoreText attrubite, but only supported by UIKit... dic[NSVerticalGlyphFormAttributeName] = All; dic[(id)kCTGlyphInfoAttributeName] = CoreText_YYText; dic[(id)kCTCharacterShapeAttributeName] = CoreText_YYText; dic[(id)kCTRunDelegateAttributeName] = CoreText_YYText; dic[(id)kCTBaselineClassAttributeName] = CoreText_YYText; dic[(id)kCTBaselineInfoAttributeName] = CoreText_YYText; dic[(id)kCTBaselineReferenceInfoAttributeName] = CoreText_YYText; dic[(id)kCTWritingDirectionAttributeName] = CoreText_YYText; dic[NSParagraphStyleAttributeName] = All; if (kiOS7Later) { dic[NSStrikethroughColorAttributeName] = UIKit; dic[NSUnderlineColorAttributeName] = UIKit; dic[NSTextEffectAttributeName] = UIKit; dic[NSObliquenessAttributeName] = UIKit; dic[NSExpansionAttributeName] = UIKit; dic[(id)kCTLanguageAttributeName] = CoreText_YYText; dic[NSBaselineOffsetAttributeName] = UIKit; dic[NSWritingDirectionAttributeName] = All; dic[NSAttachmentAttributeName] = UIKit; dic[NSLinkAttributeName] = UIKit; } if (kiOS8Later) { dic[(id)kCTRubyAnnotationAttributeName] = CoreText; } dic[YYTextBackedStringAttributeName] = YYText; dic[YYTextBindingAttributeName] = YYText; dic[YYTextShadowAttributeName] = YYText; dic[YYTextInnerShadowAttributeName] = YYText; dic[YYTextUnderlineAttributeName] = YYText; dic[YYTextStrikethroughAttributeName] = YYText; dic[YYTextBorderAttributeName] = YYText; dic[YYTextBackgroundBorderAttributeName] = YYText; dic[YYTextBlockBorderAttributeName] = YYText; dic[YYTextAttachmentAttributeName] = YYText; dic[YYTextHighlightAttributeName] = YYText; dic[YYTextGlyphTransformAttributeName] = YYText; }); NSNumber *num = dic[name]; if (num) return num.integerValue; return YYTextAttributeTypeNone; } @implementation YYTextBackedString + (instancetype)stringWithString:(NSString *)string { YYTextBackedString *one = [self new]; one.string = string; return one; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.string forKey:@"string"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; _string = [aDecoder decodeObjectForKey:@"string"]; return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; one.string = self.string; return one; } @end @implementation YYTextBinding + (instancetype)bindingWithDeleteConfirm:(BOOL)deleteConfirm { YYTextBinding *one = [self new]; one.deleteConfirm = deleteConfirm; return one; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:@(self.deleteConfirm) forKey:@"deleteConfirm"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; _deleteConfirm = ((NSNumber *)[aDecoder decodeObjectForKey:@"deleteConfirm"]).boolValue; return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; one.deleteConfirm = self.deleteConfirm; return one; } @end @implementation YYTextShadow + (instancetype)shadowWithColor:(UIColor *)color offset:(CGSize)offset radius:(CGFloat)radius { YYTextShadow *one = [self new]; one.color = color; one.offset = offset; one.radius = radius; return one; } + (instancetype)shadowWithNSShadow:(NSShadow *)nsShadow { if (!nsShadow) return nil; YYTextShadow *shadow = [self new]; shadow.offset = nsShadow.shadowOffset; shadow.radius = nsShadow.shadowBlurRadius; id color = nsShadow.shadowColor; if (color) { if (CGColorGetTypeID() == CFGetTypeID((__bridge CFTypeRef)(color))) { color = [UIColor colorWithCGColor:(__bridge CGColorRef)(color)]; } if ([color isKindOfClass:[UIColor class]]) { shadow.color = color; } } return shadow; } - (NSShadow *)nsShadow { NSShadow *shadow = [NSShadow new]; shadow.shadowOffset = self.offset; shadow.shadowBlurRadius = self.radius; shadow.shadowColor = self.color; return shadow; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.color forKey:@"color"]; [aCoder encodeObject:@(self.radius) forKey:@"radius"]; [aCoder encodeObject:[NSValue valueWithCGSize:self.offset] forKey:@"offset"]; [aCoder encodeObject:self.subShadow forKey:@"subShadow"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; _color = [aDecoder decodeObjectForKey:@"color"]; _radius = ((NSNumber *)[aDecoder decodeObjectForKey:@"radius"]).floatValue; _offset = ((NSValue *)[aDecoder decodeObjectForKey:@"offset"]).CGSizeValue; _subShadow = [aDecoder decodeObjectForKey:@"subShadow"]; return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; one.color = self.color; one.radius = self.radius; one.offset = self.offset; one.subShadow = self.subShadow.copy; return one; } @end @implementation YYTextDecoration - (instancetype)init { self = [super init]; _style = YYTextLineStyleSingle; return self; } + (instancetype)decorationWithStyle:(YYTextLineStyle)style { YYTextDecoration *one = [self new]; one.style = style; return one; } + (instancetype)decorationWithStyle:(YYTextLineStyle)style width:(NSNumber *)width color:(UIColor *)color { YYTextDecoration *one = [self new]; one.style = style; one.width = width; one.color = color; return one; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:@(self.style) forKey:@"style"]; [aCoder encodeObject:self.width forKey:@"width"]; [aCoder encodeObject:self.color forKey:@"color"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; self.style = ((NSNumber *)[aDecoder decodeObjectForKey:@"style"]).unsignedIntegerValue; self.width = [aDecoder decodeObjectForKey:@"width"]; self.color = [aDecoder decodeObjectForKey:@"color"]; return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; one.style = self.style; one.width = self.width; one.color = self.color; return one; } @end @implementation YYTextBorder + (instancetype)borderWithLineStyle:(YYTextLineStyle)lineStyle lineWidth:(CGFloat)width strokeColor:(UIColor *)color { YYTextBorder *one = [self new]; one.lineStyle = lineStyle; one.strokeWidth = width; one.strokeColor = color; return one; } + (instancetype)borderWithFillColor:(UIColor *)color cornerRadius:(CGFloat)cornerRadius { YYTextBorder *one = [self new]; one.fillColor = color; one.cornerRadius = cornerRadius; one.insets = UIEdgeInsetsMake(-2, 0, 0, -2); return one; } - (instancetype)init { self = [super init]; self.lineStyle = YYTextLineStyleSingle; return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:@(self.lineStyle) forKey:@"lineStyle"]; [aCoder encodeObject:@(self.strokeWidth) forKey:@"strokeWidth"]; [aCoder encodeObject:self.strokeColor forKey:@"strokeColor"]; [aCoder encodeObject:@(self.lineJoin) forKey:@"lineJoin"]; [aCoder encodeObject:[NSValue valueWithUIEdgeInsets:self.insets] forKey:@"insets"]; [aCoder encodeObject:@(self.cornerRadius) forKey:@"cornerRadius"]; [aCoder encodeObject:self.shadow forKey:@"shadow"]; [aCoder encodeObject:self.fillColor forKey:@"fillColor"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; _lineStyle = ((NSNumber *)[aDecoder decodeObjectForKey:@"lineStyle"]).unsignedIntegerValue; _strokeWidth = ((NSNumber *)[aDecoder decodeObjectForKey:@"strokeWidth"]).doubleValue; _strokeColor = [aDecoder decodeObjectForKey:@"strokeColor"]; _lineJoin = (CGLineJoin)((NSNumber *)[aDecoder decodeObjectForKey:@"join"]).unsignedIntegerValue; _insets = ((NSValue *)[aDecoder decodeObjectForKey:@"insets"]).UIEdgeInsetsValue; _cornerRadius = ((NSNumber *)[aDecoder decodeObjectForKey:@"cornerRadius"]).doubleValue; _shadow = [aDecoder decodeObjectForKey:@"shadow"]; _fillColor = [aDecoder decodeObjectForKey:@"fillColor"]; return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; one.lineStyle = self.lineStyle; one.strokeWidth = self.strokeWidth; one.strokeColor = self.strokeColor; one.lineJoin = self.lineJoin; one.insets = self.insets; one.cornerRadius = self.cornerRadius; one.shadow = self.shadow.copy; one.fillColor = self.fillColor; return one; } @end @implementation YYTextAttachment + (instancetype)attachmentWithContent:(id)content { YYTextAttachment *one = [self new]; one.content = content; return one; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.content forKey:@"content"]; [aCoder encodeObject:[NSValue valueWithUIEdgeInsets:self.contentInsets] forKey:@"contentInsets"]; [aCoder encodeObject:self.userInfo forKey:@"userInfo"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; _content = [aDecoder decodeObjectForKey:@"content"]; _contentInsets = ((NSValue *)[aDecoder decodeObjectForKey:@"contentInsets"]).UIEdgeInsetsValue; _userInfo = [aDecoder decodeObjectForKey:@"userInfo"]; return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; if ([self.content respondsToSelector:@selector(copy)]) { one.content = [self.content copy]; } else { one.content = self.content; } one.contentInsets = self.contentInsets; one.userInfo = self.userInfo.copy; return one; } @end @implementation YYTextHighlight + (instancetype)highlightWithAttributes:(NSDictionary *)attributes { YYTextHighlight *one = [self new]; one.attributes = attributes; return one; } + (instancetype)highlightWithBackgroundColor:(UIColor *)color { YYTextBorder *highlightBorder = [YYTextBorder new]; highlightBorder.insets = UIEdgeInsetsMake(-2, -1, -2, -1); highlightBorder.cornerRadius = 3; highlightBorder.fillColor = color; YYTextHighlight *one = [self new]; [one setBackgroundBorder:highlightBorder]; return one; } - (void)setAttributes:(NSDictionary *)attributes { _attributes = attributes.mutableCopy; } - (void)encodeWithCoder:(NSCoder *)aCoder { NSData *data = nil; @try { data = [YYTextArchiver archivedDataWithRootObject:self.attributes]; } @catch (NSException *exception) { NSLog(@"%@",exception); } [aCoder encodeObject:data forKey:@"attributes"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; NSData *data = [aDecoder decodeObjectForKey:@"attributes"]; @try { _attributes = [YYTextUnarchiver unarchiveObjectWithData:data]; } @catch (NSException *exception) { NSLog(@"%@",exception); } return self; } - (id)copyWithZone:(NSZone *)zone { typeof(self) one = [self.class new]; one.attributes = self.attributes.mutableCopy; return one; } - (void)_makeMutableAttributes { if (!_attributes) { _attributes = [NSMutableDictionary new]; } else if (![_attributes isKindOfClass:[NSMutableDictionary class]]) { _attributes = _attributes.mutableCopy; } } - (void)setFont:(UIFont *)font { [self _makeMutableAttributes]; if (font == (id)[NSNull null] || font == nil) { ((NSMutableDictionary *)_attributes)[(id)kCTFontAttributeName] = [NSNull null]; } else { CTFontRef ctFont = [font CTFontRef]; if (ctFont) { ((NSMutableDictionary *)_attributes)[(id)kCTFontAttributeName] = (__bridge id)(ctFont); CFRelease(ctFont); } } } - (void)setColor:(UIColor *)color { [self _makeMutableAttributes]; if (color == (id)[NSNull null] || color == nil) { ((NSMutableDictionary *)_attributes)[(id)kCTForegroundColorAttributeName] = [NSNull null]; ((NSMutableDictionary *)_attributes)[NSForegroundColorAttributeName] = [NSNull null]; } else { ((NSMutableDictionary *)_attributes)[(id)kCTForegroundColorAttributeName] = (__bridge id)(color.CGColor); ((NSMutableDictionary *)_attributes)[NSForegroundColorAttributeName] = color; } } - (void)setStrokeWidth:(NSNumber *)width { [self _makeMutableAttributes]; if (width == (id)[NSNull null] || width == nil) { ((NSMutableDictionary *)_attributes)[(id)kCTStrokeWidthAttributeName] = [NSNull null]; } else { ((NSMutableDictionary *)_attributes)[(id)kCTStrokeWidthAttributeName] = width; } } - (void)setStrokeColor:(UIColor *)color { [self _makeMutableAttributes]; if (color == (id)[NSNull null] || color == nil) { ((NSMutableDictionary *)_attributes)[(id)kCTStrokeColorAttributeName] = [NSNull null]; ((NSMutableDictionary *)_attributes)[NSStrokeColorAttributeName] = [NSNull null]; } else { ((NSMutableDictionary *)_attributes)[(id)kCTStrokeColorAttributeName] = (__bridge id)(color.CGColor); ((NSMutableDictionary *)_attributes)[NSStrokeColorAttributeName] = color; } } - (void)setTextAttribute:(NSString *)attribute value:(id)value { [self _makeMutableAttributes]; if (value == nil) value = [NSNull null]; ((NSMutableDictionary *)_attributes)[attribute] = value; } - (void)setShadow:(YYTextShadow *)shadow { [self setTextAttribute:YYTextShadowAttributeName value:shadow]; } - (void)setInnerShadow:(YYTextShadow *)shadow { [self setTextAttribute:YYTextInnerShadowAttributeName value:shadow]; } - (void)setUnderline:(YYTextDecoration *)underline { [self setTextAttribute:YYTextUnderlineAttributeName value:underline]; } - (void)setStrikethrough:(YYTextDecoration *)strikethrough { [self setTextAttribute:YYTextStrikethroughAttributeName value:strikethrough]; } - (void)setBackgroundBorder:(YYTextBorder *)border { [self setTextAttribute:YYTextBackgroundBorderAttributeName value:border]; } - (void)setBorder:(YYTextBorder *)border { [self setTextAttribute:YYTextBorderAttributeName value:border]; } - (void)setAttachment:(YYTextAttachment *)attachment { [self setTextAttribute:YYTextAttachmentAttributeName value:attachment]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextAttribute.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
4,223
```objective-c // // UIPasteboard+YYText.m // YYKit <path_to_url // // Created by ibireme on 15/4/2. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "UIPasteboard+YYText.h" #import "YYKitMacro.h" #import "YYImage.h" #import "NSAttributedString+YYText.h" #import <MobileCoreServices/MobileCoreServices.h> YYSYNTH_DUMMY_CLASS(UIPasteboard_YYText) NSString *const YYPasteboardTypeAttributedString = @"com.ibireme.NSAttributedString"; NSString *const YYUTTypeWEBP = @"com.google.webp"; @implementation UIPasteboard (YYText) - (void)setPNGData:(NSData *)PNGData { [self setData:PNGData forPasteboardType:(id)kUTTypePNG]; } - (NSData *)PNGData { return [self dataForPasteboardType:(id)kUTTypePNG]; } - (void)setJPEGData:(NSData *)JPEGData { [self setData:JPEGData forPasteboardType:(id)kUTTypeJPEG]; } - (NSData *)JPEGData { return [self dataForPasteboardType:(id)kUTTypeJPEG]; } - (void)setGIFData:(NSData *)GIFData { [self setData:GIFData forPasteboardType:(id)kUTTypeGIF]; } - (NSData *)GIFData { return [self dataForPasteboardType:(id)kUTTypeGIF]; } - (void)setWEBPData:(NSData *)WEBPData { [self setData:WEBPData forPasteboardType:YYUTTypeWEBP]; } - (NSData *)WEBPData { return [self dataForPasteboardType:YYUTTypeWEBP]; } - (void)setImageData:(NSData *)imageData { [self setData:imageData forPasteboardType:(id)kUTTypeImage]; } - (NSData *)imageData { return [self dataForPasteboardType:(id)kUTTypeImage]; } - (void)setAttributedString:(NSAttributedString *)attributedString { self.string = [attributedString plainTextForRange:NSMakeRange(0, attributedString.length)]; NSData *data = [attributedString archiveToData]; if (data) { NSDictionary *item = @{YYPasteboardTypeAttributedString : data}; [self addItems:@[item]]; } [attributedString enumerateAttribute:YYTextAttachmentAttributeName inRange:NSMakeRange(0, attributedString.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(YYTextAttachment *attachment, NSRange range, BOOL *stop) { UIImage *img = attachment.content; if ([img isKindOfClass:[UIImage class]]) { NSDictionary *item = @{@"com.apple.uikit.image" : img}; [self addItems:@[item]]; if ([img isKindOfClass:[YYImage class]] && ((YYImage *)img).animatedImageData) { if (((YYImage *)img).animatedImageType == YYImageTypeGIF) { NSDictionary *item = @{(id)kUTTypeGIF : ((YYImage *)img).animatedImageData}; [self addItems:@[item]]; } else if (((YYImage *)img).animatedImageType == YYImageTypePNG) { NSDictionary *item = @{(id)kUTTypePNG : ((YYImage *)img).animatedImageData}; [self addItems:@[item]]; } else if (((YYImage *)img).animatedImageType == YYImageTypeWebP) { NSDictionary *item = @{(id)YYUTTypeWEBP : ((YYImage *)img).animatedImageData}; [self addItems:@[item]]; } } // save image UIImage *simpleImage = nil; if ([attachment.content isKindOfClass:[UIImage class]]) { simpleImage = attachment.content; } else if ([attachment.content isKindOfClass:[UIImageView class]]) { simpleImage = ((UIImageView *)attachment.content).image; } if (simpleImage) { NSDictionary *item = @{@"com.apple.uikit.image" : simpleImage}; [self addItems:@[item]]; } // save animated image if ([attachment.content isKindOfClass:[UIImageView class]]) { UIImageView *imageView = attachment.content; YYImage *image = (id)imageView.image; if ([image isKindOfClass:[YYImage class]]) { NSData *data = image.animatedImageData; YYImageType type = image.animatedImageType; if (data) { switch (type) { case YYImageTypeGIF: { NSDictionary *item = @{(id)kUTTypeGIF : data}; [self addItems:@[item]]; } break; case YYImageTypePNG: { // APNG NSDictionary *item = @{(id)kUTTypePNG : data}; [self addItems:@[item]]; } break; case YYImageTypeWebP: { NSDictionary *item = @{(id)YYUTTypeWEBP : data}; [self addItems:@[item]]; } break; default: break; } } } } } }]; } - (NSAttributedString *)attributedString { for (NSDictionary *items in self.items) { NSData *data = items[YYPasteboardTypeAttributedString]; if (data) { return [NSAttributedString unarchiveFromData:data]; } } return nil; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/UIPasteboard+YYText.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,177
```objective-c // // YYTextRubyAnnotation.h // YYKit <path_to_url // // Created by ibireme on 15/4/24. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> NS_ASSUME_NONNULL_BEGIN /** Wrapper for CTRubyAnnotationRef. Example: YYTextRubyAnnotation *ruby = [YYTextRubyAnnotation new]; ruby.textBefore = @"zh yn"; CTRubyAnnotationRef ctRuby = ruby.CTRubyAnnotation; if (ctRuby) { /// add to attributed string CFRelease(ctRuby); } */ @interface YYTextRubyAnnotation : NSObject <NSCopying, NSCoding> /// Specifies how the ruby text and the base text should be aligned relative to each other. @property (nonatomic) CTRubyAlignment alignment; /// Specifies how the ruby text can overhang adjacent characters. @property (nonatomic) CTRubyOverhang overhang; /// Specifies the size of the annotation text as a percent of the size of the base text. @property (nonatomic) CGFloat sizeFactor; /// The ruby text is positioned before the base text; /// i.e. above horizontal text and to the right of vertical text. @property (nullable, nonatomic, copy) NSString *textBefore; /// The ruby text is positioned after the base text; /// i.e. below horizontal text and to the left of vertical text. @property (nullable, nonatomic, copy) NSString *textAfter; /// The ruby text is positioned to the right of the base text whether it is horizontal or vertical. /// This is the way that Bopomofo annotations are attached to Chinese text in Taiwan. @property (nullable, nonatomic, copy) NSString *textInterCharacter; /// The ruby text follows the base text with no special styling. @property (nullable, nonatomic, copy) NSString *textInline; /** Create a ruby object from CTRuby object. @param ctRuby A CTRuby object. @return A ruby object, or nil when an error occurs. */ + (instancetype)rubyWithCTRubyRef:(CTRubyAnnotationRef)ctRuby NS_AVAILABLE_IOS(8_0); /** Create a CTRuby object from the instance. @return A new CTRuby object, or NULL when an error occurs. The returned value should be release after used. */ - (nullable CTRubyAnnotationRef)CTRubyAnnotation CF_RETURNS_RETAINED NS_AVAILABLE_IOS(8_0); @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextRubyAnnotation.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
544
```objective-c // // UIPasteboard+YYText.h // YYKit <path_to_url // // Created by ibireme on 15/4/2. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** Extend UIPasteboard to support image and attributed string. */ @interface UIPasteboard (YYText) @property (nullable, nonatomic, copy) NSData *PNGData; ///< PNG file data @property (nullable, nonatomic, copy) NSData *JPEGData; ///< JPEG file data @property (nullable, nonatomic, copy) NSData *GIFData; ///< GIF file data @property (nullable, nonatomic, copy) NSData *WEBPData; ///< WebP file data @property (nullable, nonatomic, copy) NSData *imageData; ///< image file data /// Attributed string, /// Set this attributed will also set the string property which is copy from the attributed string. /// If the attributed string contains one or more image, it will also set the `images` property. @property (nullable, nonatomic, copy) NSAttributedString *attributedString; @end /// The name identifying the attributed string in pasteboard. UIKIT_EXTERN NSString *const YYPasteboardTypeAttributedString; /// The UTI Type identifying WebP data in pasteboard. UIKIT_EXTERN NSString *const YYUTTypeWEBP; NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/UIPasteboard+YYText.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
312
```objective-c // // YYTextArchiver.m // YYKit <path_to_url // // Created by ibireme on 15/3/16. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextArchiver.h" #import "YYTextRunDelegate.h" #import "YYTextRubyAnnotation.h" #import "UIDevice+YYAdd.h" /** When call CTRunDelegateGetTypeID() on some devices (runs iOS6), I got the error: "dyld: lazy symbol binding failed: Symbol not found: _CTRunDelegateGetTypeID" Here's a workaround for this issue. */ static CFTypeID CTRunDelegateTypeID() { static CFTypeID typeID; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ /* if ((long)CTRunDelegateGetTypeID + 1 > 1) { //avoid compiler optimization typeID = CTRunDelegateGetTypeID(); } */ YYTextRunDelegate *delegate = [YYTextRunDelegate new]; CTRunDelegateRef ref = delegate.CTRunDelegate; typeID = CFGetTypeID(ref); CFRelease(ref); }); return typeID; } static CFTypeID CTRubyAnnotationTypeID() { static CFTypeID typeID; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if ((long)CTRubyAnnotationGetTypeID + 1 > 1) { //avoid compiler optimization typeID = CTRunDelegateGetTypeID(); } else { typeID = kCFNotFound; } }); return typeID; } /** A wrapper for CGColorRef. Used for Archive/Unarchive/Copy. */ @interface _YYCGColor : NSObject <NSCopying, NSCoding> @property (nonatomic, assign) CGColorRef CGColor; + (instancetype)colorWithCGColor:(CGColorRef)CGColor; @end @implementation _YYCGColor + (instancetype)colorWithCGColor:(CGColorRef)CGColor { _YYCGColor *color = [self new]; color.CGColor = CGColor; return color; } - (void)setCGColor:(CGColorRef)CGColor { if (_CGColor != CGColor) { if (CGColor) CGColor = (CGColorRef)CFRetain(CGColor); if (_CGColor) CFRelease(_CGColor); _CGColor = CGColor; } } - (void)dealloc { if (_CGColor) CFRelease(_CGColor); _CGColor = NULL; } - (id)copyWithZone:(NSZone *)zone { _YYCGColor *color = [self.class new]; color.CGColor = self.CGColor; return color; } - (void)encodeWithCoder:(NSCoder *)aCoder { UIColor *color = [UIColor colorWithCGColor:_CGColor]; [aCoder encodeObject:color forKey:@"color"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [self init]; UIColor *color = [aDecoder decodeObjectForKey:@"color"]; self.CGColor = color.CGColor; return self; } @end /** A wrapper for CGImageRef. Used for Archive/Unarchive/Copy. */ @interface _YYCGImage : NSObject <NSCoding, NSCopying> @property (nonatomic, assign) CGImageRef CGImage; + (instancetype)imageWithCGImage:(CGImageRef)CGImage; @end @implementation _YYCGImage + (instancetype)imageWithCGImage:(CGImageRef)CGImage { _YYCGImage *image = [self new]; image.CGImage = CGImage; return image; } - (void)setCGImage:(CGImageRef)CGImage { if (_CGImage != CGImage) { if (CGImage) CGImage = (CGImageRef)CFRetain(CGImage); if (_CGImage) CFRelease(_CGImage); _CGImage = CGImage; } } - (void)dealloc { if (_CGImage) CFRelease(_CGImage); } - (id)copyWithZone:(NSZone *)zone { _YYCGImage *image = [self.class new]; image.CGImage = self.CGImage; return image; } - (void)encodeWithCoder:(NSCoder *)aCoder { UIImage *image = [UIImage imageWithCGImage:_CGImage]; [aCoder encodeObject:image forKey:@"image"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [self init]; UIImage *image = [aDecoder decodeObjectForKey:@"image"]; self.CGImage = image.CGImage; return self; } @end @implementation YYTextArchiver + (NSData *)archivedDataWithRootObject:(id)rootObject { if (!rootObject) return nil; NSMutableData *data = [NSMutableData data]; YYTextArchiver *archiver = [[[self class] alloc] initForWritingWithMutableData:data]; [archiver encodeRootObject:rootObject]; [archiver finishEncoding]; return data; } + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path { NSData *data = [self archivedDataWithRootObject:rootObject]; if (!data) return NO; return [data writeToFile:path atomically:YES]; } - (instancetype)init { self = [super init]; self.delegate = self; return self; } - (instancetype)initForWritingWithMutableData:(NSMutableData *)data { self = [super initForWritingWithMutableData:data]; self.delegate = self; return self; } - (id)archiver:(NSKeyedArchiver *)archiver willEncodeObject:(id)object { CFTypeID typeID = CFGetTypeID((CFTypeRef)object); if (typeID == CTRunDelegateTypeID()) { CTRunDelegateRef runDelegate = (__bridge CFTypeRef)(object); id ref = CTRunDelegateGetRefCon(runDelegate); if (ref) return ref; } else if (typeID == CTRubyAnnotationTypeID()) { CTRubyAnnotationRef ctRuby = (__bridge CFTypeRef)(object); YYTextRubyAnnotation *ruby = [YYTextRubyAnnotation rubyWithCTRubyRef:ctRuby]; if (ruby) return ruby; } else if (typeID == CGColorGetTypeID()) { return [_YYCGColor colorWithCGColor:(CGColorRef)object]; } else if (typeID == CGImageGetTypeID()) { return [_YYCGImage imageWithCGImage:(CGImageRef)object]; } return object; } @end @implementation YYTextUnarchiver + (id)unarchiveObjectWithData:(NSData *)data { if (data.length == 0) return nil; YYTextUnarchiver *unarchiver = [[self alloc] initForReadingWithData:data]; return [unarchiver decodeObject]; } + (id)unarchiveObjectWithFile:(NSString *)path { NSData *data = [NSData dataWithContentsOfFile:path]; return [self unarchiveObjectWithData:data]; } - (instancetype)init { self = [super init]; self.delegate = self; return self; } - (instancetype)initForReadingWithData:(NSData *)data { self = [super initForReadingWithData:data]; self.delegate = self; return self; } - (id)unarchiver:(NSKeyedUnarchiver *)unarchiver didDecodeObject:(id) NS_RELEASES_ARGUMENT object NS_RETURNS_RETAINED { if ([object class] == [YYTextRunDelegate class]) { YYTextRunDelegate *runDelegate = object; CTRunDelegateRef ct = runDelegate.CTRunDelegate; id ctObj = (__bridge id)ct; if (ct) CFRelease(ct); return ctObj; } else if ([object class] == [YYTextRubyAnnotation class]) { YYTextRubyAnnotation *ruby = object; if (kiOS8Later) { CTRubyAnnotationRef ct = ruby.CTRubyAnnotation; id ctObj = (__bridge id)(ct); if (ct) CFRelease(ct); return ctObj; } else { return object; } } else if ([object class] == [_YYCGColor class]) { _YYCGColor *color = object; return (id)color.CGColor; } else if ([object class] == [_YYCGImage class]) { _YYCGImage *image = object; return (id)image.CGImage; } return object; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextArchiver.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,838
```objective-c // // NSAttributedString+YYText.h // YYKit <path_to_url // // Created by ibireme on 14/10/7. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextAttribute.h> #import <YYKit/YYTextRubyAnnotation.h> #else #import "YYTextAttribute.h" #import "YYTextRubyAnnotation.h" #endif NS_ASSUME_NONNULL_BEGIN /** Get pre-defined attributes from attributed string. All properties defined in UIKit, CoreText and YYText are included. */ @interface NSAttributedString (YYText) /** Archive the string to data. @return Returns nil if an error occurs. */ - (nullable NSData *)archiveToData; /** Unarchive string from data. @param data The archived attributed string data. @return Returns nil if an error occurs. */ + (nullable instancetype)unarchiveFromData:(NSData *)data; #pragma mark - Retrieving character attribute information ///============================================================================= /// @name Retrieving character attribute information ///============================================================================= /** Returns the attributes at first charactor. */ @property (nullable, nonatomic, copy, readonly) NSDictionary<NSString *, id> *attributes; /** Returns the attributes for the character at a given index. @discussion Raises an `NSRangeException` if index lies beyond the end of the receiver's characters. @param index The index for which to return attributes. This value must lie within the bounds of the receiver. @return The attributes for the character at index. */ - (nullable NSDictionary<NSString *, id> *)attributesAtIndex:(NSUInteger)index; /** Returns the value for an attribute with a given name of the character at a given index. @discussion Raises an `NSRangeException` if index lies beyond the end of the receiver's characters. @param attributeName The name of an attribute. @param index The index for which to return attributes. This value must not exceed the bounds of the receiver. @return The value for the attribute named `attributeName` of the character at index `index`, or nil if there is no such attribute. */ - (nullable id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index; #pragma mark - Get character attribute as property ///============================================================================= /// @name Get character attribute as property ///============================================================================= /** The font of the text. (read-only) @discussion Default is Helvetica (Neue) 12. @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) UIFont *font; - (nullable UIFont *)fontAtIndex:(NSUInteger)index; /** A kerning adjustment. (read-only) @discussion Default is standard kerning. The kerning attribute indicate how many points the following character should be shifted from its default offset as defined by the current character's font in points; a positive kern indicates a shift farther along and a negative kern indicates a shift closer to the current character. If this attribute is not present, standard kerning will be used. If this attribute is set to 0.0, no kerning will be done at all. @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) NSNumber *kern; - (nullable NSNumber *)kernAtIndex:(NSUInteger)index; /** The foreground color. (read-only) @discussion Default is Black. @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) UIColor *color; - (nullable UIColor *)colorAtIndex:(NSUInteger)index; /** The background color. (read-only) @discussion Default is nil (or no background). @discussion Get this property returns the first character's attribute. @since UIKit:6.0 */ @property (nullable, nonatomic, strong, readonly) UIColor *backgroundColor; - (nullable UIColor *)backgroundColorAtIndex:(NSUInteger)index; /** The stroke width. (read-only) @discussion Default value is 0.0 (no stroke). This attribute, interpreted as a percentage of font point size, controls the text drawing mode: positive values effect drawing with stroke only; negative values are for stroke and fill. A typical value for outlined text is 3.0. @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 */ @property (nullable, nonatomic, strong, readonly) NSNumber *strokeWidth; - (nullable NSNumber *)strokeWidthAtIndex:(NSUInteger)index; /** The stroke color. (read-only) @discussion Default value is nil (same as foreground color). @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 */ @property (nullable, nonatomic, strong, readonly) UIColor *strokeColor; - (nullable UIColor *)strokeColorAtIndex:(NSUInteger)index; /** The text shadow. (read-only) @discussion Default value is nil (no shadow). @discussion Get this property returns the first character's attribute. @since UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) NSShadow *shadow; - (nullable NSShadow *)shadowAtIndex:(NSUInteger)index; /** The strikethrough style. (read-only) @discussion Default value is NSUnderlineStyleNone (no strikethrough). @discussion Get this property returns the first character's attribute. @since UIKit:6.0 */ @property (nonatomic, readonly) NSUnderlineStyle strikethroughStyle; - (NSUnderlineStyle)strikethroughStyleAtIndex:(NSUInteger)index; /** The strikethrough color. (read-only) @discussion Default value is nil (same as foreground color). @discussion Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readonly) UIColor *strikethroughColor; - (nullable UIColor *)strikethroughColorAtIndex:(NSUInteger)index; /** The underline style. (read-only) @discussion Default value is NSUnderlineStyleNone (no underline). @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 */ @property (nonatomic, readonly) NSUnderlineStyle underlineStyle; - (NSUnderlineStyle)underlineStyleAtIndex:(NSUInteger)index; /** The underline color. (read-only) @discussion Default value is nil (same as foreground color). @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:7.0 */ @property (nullable, nonatomic, strong, readonly) UIColor *underlineColor; - (nullable UIColor *)underlineColorAtIndex:(NSUInteger)index; /** Ligature formation control. (read-only) @discussion Default is int value 1. The ligature attribute determines what kinds of ligatures should be used when displaying the string. A value of 0 indicates that only ligatures essential for proper rendering of text should be used, 1 indicates that standard ligatures should be used, and 2 indicates that all available ligatures should be used. Which ligatures are standard depends on the script and possibly the font. @discussion Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) NSNumber *ligature; - (nullable NSNumber *)ligatureAtIndex:(NSUInteger)index; /** The text effect. (read-only) @discussion Default is nil (no effect). The only currently supported value is NSTextEffectLetterpressStyle. @discussion Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readonly) NSString *textEffect; - (nullable NSString *)textEffectAtIndex:(NSUInteger)index; /** The skew to be applied to glyphs. (read-only) @discussion Default is 0 (no skew). @discussion Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readonly) NSNumber *obliqueness; - (nullable NSNumber *)obliquenessAtIndex:(NSUInteger)index; /** The log of the expansion factor to be applied to glyphs. (read-only) @discussion Default is 0 (no expansion). @discussion Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readonly) NSNumber *expansion; - (nullable NSNumber *)expansionAtIndex:(NSUInteger)index; /** The character's offset from the baseline, in points. (read-only) @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readonly) NSNumber *baselineOffset; - (nullable NSNumber *)baselineOffsetAtIndex:(NSUInteger)index; /** Glyph orientation control. (read-only) @discussion Default is NO. A value of NO indicates that horizontal glyph forms are to be used, YES indicates that vertical glyph forms are to be used. @discussion Get this property returns the first character's attribute. @since CoreText:4.3 YYKit:6.0 */ @property (nonatomic, readonly) BOOL verticalGlyphForm; - (BOOL)verticalGlyphFormAtIndex:(NSUInteger)index; /** Specifies text language. (read-only) @discussion Value must be a NSString containing a locale identifier. Default is unset. When this attribute is set to a valid identifier, it will be used to select localized glyphs (if supported by the font) and locale-specific line breaking rules. @discussion Get this property returns the first character's attribute. @since CoreText:7.0 YYKit:7.0 */ @property (nullable, nonatomic, strong, readonly) NSString *language; - (nullable NSString *)languageAtIndex:(NSUInteger)index; /** Specifies a bidirectional override or embedding. (read-only) @discussion See alse NSWritingDirection and NSWritingDirectionAttributeName. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:7.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) NSArray<NSNumber *> *writingDirection; - (nullable NSArray<NSNumber *> *)writingDirectionAtIndex:(NSUInteger)index; /** An NSParagraphStyle object which is used to specify things like line alignment, tab rulers, writing direction, etc. (read-only) @discussion Default is nil ([NSParagraphStyle defaultParagraphStyle]). @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) NSParagraphStyle *paragraphStyle; - (nullable NSParagraphStyle *)paragraphStyleAtIndex:(NSUInteger)index; #pragma mark - Get paragraph attribute as property ///============================================================================= /// @name Get paragraph attribute as property ///============================================================================= /** The text alignment (A wrapper for NSParagraphStyle). (read-only) @discussion Natural text alignment is realized as left or right alignment depending on the line sweep direction of the first script contained in the paragraph. @discussion Default is NSTextAlignmentNatural. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) NSTextAlignment alignment; - (NSTextAlignment)alignmentAtIndex:(NSUInteger)index; /** The mode that should be used to break lines (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the line break mode to be used laying out the paragraph's text. @discussion Default is NSLineBreakByWordWrapping. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) NSLineBreakMode lineBreakMode; - (NSLineBreakMode)lineBreakModeAtIndex:(NSUInteger)index; /** The distance in points between the bottom of one line fragment and the top of the next. (A wrapper for NSParagraphStyle) (read-only) @discussion This value is always nonnegative. This value is included in the line fragment heights in the layout manager. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat lineSpacing; - (CGFloat)lineSpacingAtIndex:(NSUInteger)index; /** The space after the end of the paragraph (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the space (measured in points) added at the end of the paragraph to separate it from the following paragraph. This value must be nonnegative. The space between paragraphs is determined by adding the previous paragraph's paragraphSpacing and the current paragraph's paragraphSpacingBefore. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat paragraphSpacing; - (CGFloat)paragraphSpacingAtIndex:(NSUInteger)index; /** The distance between the paragraph's top and the beginning of its text content. (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the space (measured in points) between the paragraph's top and the beginning of its text content. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat paragraphSpacingBefore; - (CGFloat)paragraphSpacingBeforeAtIndex:(NSUInteger)index; /** The indentation of the first line (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the distance (in points) from the leading margin of a text container to the beginning of the paragraph's first line. This value is always nonnegative. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat firstLineHeadIndent; - (CGFloat)firstLineHeadIndentAtIndex:(NSUInteger)index; /** The indentation of the receiver's lines other than the first. (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the distance (in points) from the leading margin of a text container to the beginning of lines other than the first. This value is always nonnegative. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat headIndent; - (CGFloat)headIndentAtIndex:(NSUInteger)index; /** The trailing indentation (A wrapper for NSParagraphStyle). (read-only) @discussion If positive, this value is the distance from the leading margin (for example, the left margin in left-to-right text). If 0 or negative, it's the distance from the trailing margin. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat tailIndent; - (CGFloat)tailIndentAtIndex:(NSUInteger)index; /** The receiver's minimum height (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the minimum height in points that any line in the receiver will occupy, regardless of the font size or size of any attached graphic. This value must be nonnegative. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat minimumLineHeight; - (CGFloat)minimumLineHeightAtIndex:(NSUInteger)index; /** The receiver's maximum line height (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the maximum height in points that any line in the receiver will occupy, regardless of the font size or size of any attached graphic. This value is always nonnegative. Glyphs and graphics exceeding this height will overlap neighboring lines; however, a maximum height of 0 implies no line height limit. Although this limit applies to the line itself, line spacing adds extra space between adjacent lines. @discussion Default is 0 (no limit). @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat maximumLineHeight; - (CGFloat)maximumLineHeightAtIndex:(NSUInteger)index; /** The line height multiple (A wrapper for NSParagraphStyle). (read-only) @discussion This property contains the line break mode to be used laying out the paragraph's text. @discussion Default is 0 (no multiple). @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) CGFloat lineHeightMultiple; - (CGFloat)lineHeightMultipleAtIndex:(NSUInteger)index; /** The base writing direction (A wrapper for NSParagraphStyle). (read-only) @discussion If you specify NSWritingDirectionNaturalDirection, the receiver resolves the writing direction to either NSWritingDirectionLeftToRight or NSWritingDirectionRightToLeft, depending on the direction for the user's `language` preference setting. @discussion Default is NSWritingDirectionNatural. @discussion Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readonly) NSWritingDirection baseWritingDirection; - (NSWritingDirection)baseWritingDirectionAtIndex:(NSUInteger)index; /** The paragraph's threshold for hyphenation. (A wrapper for NSParagraphStyle). (read-only) @discussion Valid values lie between 0.0 and 1.0 inclusive. Hyphenation is attempted when the ratio of the text width (as broken without hyphenation) to the width of the line fragment is less than the hyphenation factor. When the paragraph's hyphenation factor is 0.0, the layout manager's hyphenation factor is used instead. When both are 0.0, hyphenation is disabled. @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since UIKit:6.0 */ @property (nonatomic, readonly) float hyphenationFactor; - (float)hyphenationFactorAtIndex:(NSUInteger)index; /** The document-wide default tab interval (A wrapper for NSParagraphStyle). (read-only) @discussion This property represents the default tab interval in points. Tabs after the last specified in tabStops are placed at integer multiples of this distance (if positive). @discussion Default is 0. @discussion Get this property returns the first character's attribute. @since CoreText:7.0 UIKit:7.0 YYKit:7.0 */ @property (nonatomic, readonly) CGFloat defaultTabInterval; - (CGFloat)defaultTabIntervalAtIndex:(NSUInteger)index; /** An array of NSTextTab objects representing the receiver's tab stops. (A wrapper for NSParagraphStyle). (read-only) @discussion The NSTextTab objects, sorted by location, define the tab stops for the paragraph style. @discussion Default is 12 TabStops with 28.0 tab interval. @discussion Get this property returns the first character's attribute. @since CoreText:7.0 UIKit:7.0 YYKit:7.0 */ @property (nullable, nonatomic, copy, readonly) NSArray<NSTextTab *> *tabStops; - (nullable NSArray<NSTextTab *> *)tabStopsAtIndex:(NSUInteger)index; #pragma mark - Get YYText attribute as property ///============================================================================= /// @name Get YYText attribute as property ///============================================================================= /** The text shadow. (read-only) @discussion Default value is nil (no shadow). @discussion Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) YYTextShadow *textShadow; - (nullable YYTextShadow *)textShadowAtIndex:(NSUInteger)index; /** The text inner shadow. (read-only) @discussion Default value is nil (no shadow). @discussion Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) YYTextShadow *textInnerShadow; - (nullable YYTextShadow *)textInnerShadowAtIndex:(NSUInteger)index; /** The text underline. (read-only) @discussion Default value is nil (no underline). @discussion Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) YYTextDecoration *textUnderline; - (nullable YYTextDecoration *)textUnderlineAtIndex:(NSUInteger)index; /** The text strikethrough. (read-only) @discussion Default value is nil (no strikethrough). @discussion Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) YYTextDecoration *textStrikethrough; - (nullable YYTextDecoration *)textStrikethroughAtIndex:(NSUInteger)index; /** The text border. (read-only) @discussion Default value is nil (no border). @discussion Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) YYTextBorder *textBorder; - (nullable YYTextBorder *)textBorderAtIndex:(NSUInteger)index; /** The text background border. (read-only) @discussion Default value is nil (no background border). @discussion Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readonly) YYTextBorder *textBackgroundBorder; - (nullable YYTextBorder *)textBackgroundBorderAtIndex:(NSUInteger)index; /** The glyph transform. (read-only) @discussion Default value is CGAffineTransformIdentity (no transform). @discussion Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nonatomic, readonly) CGAffineTransform textGlyphTransform; - (CGAffineTransform)textGlyphTransformAtIndex:(NSUInteger)index; #pragma mark - Query for YYText ///============================================================================= /// @name Query for YYText ///============================================================================= /** Returns the plain text from a range. If there's `YYTextBackedStringAttributeName` attribute, the backed string will replace the attributed string range. @param range A range in receiver. @return The plain text. */ - (nullable NSString *)plainTextForRange:(NSRange)range; #pragma mark - Create attachment string for YYText ///============================================================================= /// @name Create attachment string for YYText ///============================================================================= /** Creates and returns an attachment. @param content The attachment (UIImage/UIView/CALayer). @param contentMode The attachment's content mode. @param width The attachment's container width in layout. @param ascent The attachment's container ascent in layout. @param descent The attachment's container descent in layout. @return An attributed string, or nil if an error occurs. @since YYKit:6.0 */ + (NSMutableAttributedString *)attachmentStringWithContent:(nullable id)content contentMode:(UIViewContentMode)contentMode width:(CGFloat)width ascent:(CGFloat)ascent descent:(CGFloat)descent; /** Creates and returns an attachment. Example: ContentMode:bottom Alignment:Top. The text The attachment holder / \ / ___| / _ \ | | / ___ \ | |___ The text line /_/ \_\ \____| The attachment content @param content The attachment (UIImage/UIView/CALayer). @param contentMode The attachment's content mode in attachment holder @param attachmentSize The attachment holder's size in text layout. @param fontSize The attachment will align to this font. @param alignment The attachment holder's alignment to text line. @return An attributed string, or nil if an error occurs. @since YYKit:6.0 */ + (NSMutableAttributedString *)attachmentStringWithContent:(nullable id)content contentMode:(UIViewContentMode)contentMode attachmentSize:(CGSize)attachmentSize alignToFont:(UIFont *)font alignment:(YYTextVerticalAlignment)alignment; /** Creates and returns an attahment from a fourquare image as if it was an emoji. @param image A fourquare image. @param fontSize The font size. @return An attributed string, or nil if an error occurs. @since YYKit:6.0 */ + (nullable NSMutableAttributedString *)attachmentStringWithEmojiImage:(UIImage *)image fontSize:(CGFloat)fontSize; #pragma mark - Utility ///============================================================================= /// @name Utility ///============================================================================= /** Returns NSMakeRange(0, self.length). */ - (NSRange)rangeOfAll; /** If YES, it share the same attribute in entire text range. */ - (BOOL)isSharedAttributesInAllRange; /** If YES, it can be drawn with the [drawWithRect:options:context:] method or displayed with UIKit. If NO, it should be drawn with CoreText or YYText. @discussion If the method returns NO, it means that there's at least one attribute which is not supported by UIKit (such as CTParagraphStyleRef). If display this string in UIKit, it may lose some attribute, or even crash the app. */ - (BOOL)canDrawWithUIKit; @end /** Set pre-defined attributes to attributed string. All properties defined in UIKit, CoreText and YYText are included. */ @interface NSMutableAttributedString (YYText) #pragma mark - Set character attribute ///============================================================================= /// @name Set character attribute ///============================================================================= /** Sets the attributes to the entire text string. @discussion The old attributes will be removed. @param attributes A dictionary containing the attributes to set, or nil to remove all attributes. */ - (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attributes; /** Sets an attribute with the given name and value to the entire text string. @param name A string specifying the attribute name. @param value The attribute value associated with name. Pass `nil` or `NSNull` to remove the attribute. */ - (void)setAttribute:(NSString *)name value:(nullable id)value; /** Sets an attribute with the given name and value to the characters in the specified range. @param name A string specifying the attribute name. @param value The attribute value associated with name. Pass `nil` or `NSNull` to remove the attribute. @param range The range of characters to which the specified attribute/value pair applies. */ - (void)setAttribute:(NSString *)name value:(nullable id)value range:(NSRange)range; /** Removes all attributes in the specified range. @param range The range of characters. */ - (void)removeAttributesInRange:(NSRange)range; #pragma mark - Set character attribute as property ///============================================================================= /// @name Set character attribute as property ///============================================================================= /** The font of the text. @discussion Default is Helvetica (Neue) 12. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) UIFont *font; - (void)setFont:(nullable UIFont *)font range:(NSRange)range; /** A kerning adjustment. @discussion Default is standard kerning. The kerning attribute indicate how many points the following character should be shifted from its default offset as defined by the current character's font in points; a positive kern indicates a shift farther along and a negative kern indicates a shift closer to the current character. If this attribute is not present, standard kerning will be used. If this attribute is set to 0.0, no kerning will be done at all. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) NSNumber *kern; - (void)setKern:(nullable NSNumber *)kern range:(NSRange)range; /** The foreground color. @discussion Default is Black. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) UIColor *color; - (void)setColor:(nullable UIColor *)color range:(NSRange)range; /** The background color. @discussion Default is nil (or no background). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) UIColor *backgroundColor; - (void)setBackgroundColor:(nullable UIColor *)backgroundColor range:(NSRange)range; /** The stroke width. @discussion Default value is 0.0 (no stroke). This attribute, interpreted as a percentage of font point size, controls the text drawing mode: positive values effect drawing with stroke only; negative values are for stroke and fill. A typical value for outlined text is 3.0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) NSNumber *strokeWidth; - (void)setStrokeWidth:(nullable NSNumber *)strokeWidth range:(NSRange)range; /** The stroke color. @discussion Default value is nil (same as foreground color). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) UIColor *strokeColor; - (void)setStrokeColor:(nullable UIColor *)strokeColor range:(NSRange)range; /** The text shadow. @discussion Default value is nil (no shadow). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) NSShadow *shadow; - (void)setShadow:(nullable NSShadow *)shadow range:(NSRange)range; /** The strikethrough style. @discussion Default value is NSUnderlineStyleNone (no strikethrough). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:6.0 */ @property (nonatomic, readwrite) NSUnderlineStyle strikethroughStyle; - (void)setStrikethroughStyle:(NSUnderlineStyle)strikethroughStyle range:(NSRange)range; /** The strikethrough color. @discussion Default value is nil (same as foreground color). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readwrite) UIColor *strikethroughColor; - (void)setStrikethroughColor:(nullable UIColor *)strikethroughColor range:(NSRange)range NS_AVAILABLE_IOS(7_0); /** The underline style. @discussion Default value is NSUnderlineStyleNone (no underline). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 */ @property (nonatomic, readwrite) NSUnderlineStyle underlineStyle; - (void)setUnderlineStyle:(NSUnderlineStyle)underlineStyle range:(NSRange)range; /** The underline color. @discussion Default value is nil (same as foreground color). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:7.0 */ @property (nullable, nonatomic, strong, readwrite) UIColor *underlineColor; - (void)setUnderlineColor:(nullable UIColor *)underlineColor range:(NSRange)range; /** Ligature formation control. @discussion Default is int value 1. The ligature attribute determines what kinds of ligatures should be used when displaying the string. A value of 0 indicates that only ligatures essential for proper rendering of text should be used, 1 indicates that standard ligatures should be used, and 2 indicates that all available ligatures should be used. Which ligatures are standard depends on the script and possibly the font. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:3.2 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) NSNumber *ligature; - (void)setLigature:(nullable NSNumber *)ligature range:(NSRange)range; /** The text effect. @discussion Default is nil (no effect). The only currently supported value is NSTextEffectLetterpressStyle. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readwrite) NSString *textEffect; - (void)setTextEffect:(nullable NSString *)textEffect range:(NSRange)range NS_AVAILABLE_IOS(7_0); /** The skew to be applied to glyphs. @discussion Default is 0 (no skew). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readwrite) NSNumber *obliqueness; - (void)setObliqueness:(nullable NSNumber *)obliqueness range:(NSRange)range NS_AVAILABLE_IOS(7_0); /** The log of the expansion factor to be applied to glyphs. @discussion Default is 0 (no expansion). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readwrite) NSNumber *expansion; - (void)setExpansion:(nullable NSNumber *)expansion range:(NSRange)range NS_AVAILABLE_IOS(7_0); /** The character's offset from the baseline, in points. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:7.0 */ @property (nullable, nonatomic, strong, readwrite) NSNumber *baselineOffset; - (void)setBaselineOffset:(nullable NSNumber *)baselineOffset range:(NSRange)range NS_AVAILABLE_IOS(7_0); /** Glyph orientation control. @discussion Default is NO. A value of NO indicates that horizontal glyph forms are to be used, YES indicates that vertical glyph forms are to be used. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:4.3 YYKit:6.0 */ @property (nonatomic, readwrite) BOOL verticalGlyphForm; - (void)setVerticalGlyphForm:(BOOL)verticalGlyphForm range:(NSRange)range; /** Specifies text language. @discussion Value must be a NSString containing a locale identifier. Default is unset. When this attribute is set to a valid identifier, it will be used to select localized glyphs (if supported by the font) and locale-specific line breaking rules. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:7.0 YYKit:7.0 */ @property (nullable, nonatomic, strong, readwrite) NSString *language; - (void)setLanguage:(nullable NSString *)language range:(NSRange)range NS_AVAILABLE_IOS(7_0); /** Specifies a bidirectional override or embedding. @discussion See alse NSWritingDirection and NSWritingDirectionAttributeName. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:7.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) NSArray<NSNumber *> *writingDirection; - (void)setWritingDirection:(nullable NSArray<NSNumber *> *)writingDirection range:(NSRange)range; /** An NSParagraphStyle object which is used to specify things like line alignment, tab rulers, writing direction, etc. @discussion Default is nil ([NSParagraphStyle defaultParagraphStyle]). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) NSParagraphStyle *paragraphStyle; - (void)setParagraphStyle:(nullable NSParagraphStyle *)paragraphStyle range:(NSRange)range; #pragma mark - Set paragraph attribute as property ///============================================================================= /// @name Set paragraph attribute as property ///============================================================================= /** The text alignment (A wrapper for NSParagraphStyle). @discussion Natural text alignment is realized as left or right alignment depending on the line sweep direction of the first script contained in the paragraph. @discussion Default is NSTextAlignmentNatural. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) NSTextAlignment alignment; - (void)setAlignment:(NSTextAlignment)alignment range:(NSRange)range; /** The mode that should be used to break lines (A wrapper for NSParagraphStyle). @discussion This property contains the line break mode to be used laying out the paragraph's text. @discussion Default is NSLineBreakByWordWrapping. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) NSLineBreakMode lineBreakMode; - (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode range:(NSRange)range; /** The distance in points between the bottom of one line fragment and the top of the next. (A wrapper for NSParagraphStyle) @discussion This value is always nonnegative. This value is included in the line fragment heights in the layout manager. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat lineSpacing; - (void)setLineSpacing:(CGFloat)lineSpacing range:(NSRange)range; /** The space after the end of the paragraph (A wrapper for NSParagraphStyle). @discussion This property contains the space (measured in points) added at the end of the paragraph to separate it from the following paragraph. This value must be nonnegative. The space between paragraphs is determined by adding the previous paragraph's paragraphSpacing and the current paragraph's paragraphSpacingBefore. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat paragraphSpacing; - (void)setParagraphSpacing:(CGFloat)paragraphSpacing range:(NSRange)range; /** The distance between the paragraph's top and the beginning of its text content. (A wrapper for NSParagraphStyle). @discussion This property contains the space (measured in points) between the paragraph's top and the beginning of its text content. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat paragraphSpacingBefore; - (void)setParagraphSpacingBefore:(CGFloat)paragraphSpacingBefore range:(NSRange)range; /** The indentation of the first line (A wrapper for NSParagraphStyle). @discussion This property contains the distance (in points) from the leading margin of a text container to the beginning of the paragraph's first line. This value is always nonnegative. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat firstLineHeadIndent; - (void)setFirstLineHeadIndent:(CGFloat)firstLineHeadIndent range:(NSRange)range; /** The indentation of the receiver's lines other than the first. (A wrapper for NSParagraphStyle). @discussion This property contains the distance (in points) from the leading margin of a text container to the beginning of lines other than the first. This value is always nonnegative. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat headIndent; - (void)setHeadIndent:(CGFloat)headIndent range:(NSRange)range; /** The trailing indentation (A wrapper for NSParagraphStyle). @discussion If positive, this value is the distance from the leading margin (for example, the left margin in left-to-right text). If 0 or negative, it's the distance from the trailing margin. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat tailIndent; - (void)setTailIndent:(CGFloat)tailIndent range:(NSRange)range; /** The receiver's minimum height (A wrapper for NSParagraphStyle). @discussion This property contains the minimum height in points that any line in the receiver will occupy, regardless of the font size or size of any attached graphic. This value must be nonnegative. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat minimumLineHeight; - (void)setMinimumLineHeight:(CGFloat)minimumLineHeight range:(NSRange)range; /** The receiver's maximum line height (A wrapper for NSParagraphStyle). @discussion This property contains the maximum height in points that any line in the receiver will occupy, regardless of the font size or size of any attached graphic. This value is always nonnegative. Glyphs and graphics exceeding this height will overlap neighboring lines; however, a maximum height of 0 implies no line height limit. Although this limit applies to the line itself, line spacing adds extra space between adjacent lines. @discussion Default is 0 (no limit). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat maximumLineHeight; - (void)setMaximumLineHeight:(CGFloat)maximumLineHeight range:(NSRange)range; /** The line height multiple (A wrapper for NSParagraphStyle). @discussion This property contains the line break mode to be used laying out the paragraph's text. @discussion Default is 0 (no multiple). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) CGFloat lineHeightMultiple; - (void)setLineHeightMultiple:(CGFloat)lineHeightMultiple range:(NSRange)range; /** The base writing direction (A wrapper for NSParagraphStyle). @discussion If you specify NSWritingDirectionNaturalDirection, the receiver resolves the writing direction to either NSWritingDirectionLeftToRight or NSWritingDirectionRightToLeft, depending on the direction for the user's `language` preference setting. @discussion Default is NSWritingDirectionNatural. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:6.0 UIKit:6.0 YYKit:6.0 */ @property (nonatomic, readwrite) NSWritingDirection baseWritingDirection; - (void)setBaseWritingDirection:(NSWritingDirection)baseWritingDirection range:(NSRange)range; /** The paragraph's threshold for hyphenation. (A wrapper for NSParagraphStyle). @discussion Valid values lie between 0.0 and 1.0 inclusive. Hyphenation is attempted when the ratio of the text width (as broken without hyphenation) to the width of the line fragment is less than the hyphenation factor. When the paragraph's hyphenation factor is 0.0, the layout manager's hyphenation factor is used instead. When both are 0.0, hyphenation is disabled. @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since UIKit:6.0 */ @property (nonatomic, readwrite) float hyphenationFactor; - (void)setHyphenationFactor:(float)hyphenationFactor range:(NSRange)range; /** The document-wide default tab interval (A wrapper for NSParagraphStyle). @discussion This property represents the default tab interval in points. Tabs after the last specified in tabStops are placed at integer multiples of this distance (if positive). @discussion Default is 0. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:7.0 UIKit:7.0 YYKit:7.0 */ @property (nonatomic, readwrite) CGFloat defaultTabInterval; - (void)setDefaultTabInterval:(CGFloat)defaultTabInterval range:(NSRange)range NS_AVAILABLE_IOS(7_0); /** An array of NSTextTab objects representing the receiver's tab stops. (A wrapper for NSParagraphStyle). @discussion The NSTextTab objects, sorted by location, define the tab stops for the paragraph style. @discussion Default is 12 TabStops with 28.0 tab interval. @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since CoreText:7.0 UIKit:7.0 YYKit:7.0 */ @property (nullable, nonatomic, copy, readwrite) NSArray<NSTextTab *> *tabStops; - (void)setTabStops:(nullable NSArray<NSTextTab *> *)tabStops range:(NSRange)range NS_AVAILABLE_IOS(7_0); #pragma mark - Set YYText attribute as property ///============================================================================= /// @name Set YYText attribute as property ///============================================================================= /** The text shadow. @discussion Default value is nil (no shadow). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) YYTextShadow *textShadow; - (void)setTextShadow:(nullable YYTextShadow *)textShadow range:(NSRange)range; /** The text inner shadow. @discussion Default value is nil (no shadow). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) YYTextShadow *textInnerShadow; - (void)setTextInnerShadow:(nullable YYTextShadow *)textInnerShadow range:(NSRange)range; /** The text underline. @discussion Default value is nil (no underline). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) YYTextDecoration *textUnderline; - (void)setTextUnderline:(nullable YYTextDecoration *)textUnderline range:(NSRange)range; /** The text strikethrough. @discussion Default value is nil (no strikethrough). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) YYTextDecoration *textStrikethrough; - (void)setTextStrikethrough:(nullable YYTextDecoration *)textStrikethrough range:(NSRange)range; /** The text border. @discussion Default value is nil (no border). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) YYTextBorder *textBorder; - (void)setTextBorder:(nullable YYTextBorder *)textBorder range:(NSRange)range; /** The text background border. @discussion Default value is nil (no background border). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nullable, nonatomic, strong, readwrite) YYTextBorder *textBackgroundBorder; - (void)setTextBackgroundBorder:(nullable YYTextBorder *)textBackgroundBorder range:(NSRange)range; /** The glyph transform. @discussion Default value is CGAffineTransformIdentity (no transform). @discussion Set this property applies to the entire text string. Get this property returns the first character's attribute. @since YYKit:6.0 */ @property (nonatomic, readwrite) CGAffineTransform textGlyphTransform; - (void)setTextGlyphTransform:(CGAffineTransform)textGlyphTransform range:(NSRange)range; #pragma mark - Set discontinuous attribute for range ///============================================================================= /// @name Set discontinuous attribute for range ///============================================================================= - (void)setSuperscript:(nullable NSNumber *)superscript range:(NSRange)range; - (void)setGlyphInfo:(nullable CTGlyphInfoRef)glyphInfo range:(NSRange)range; - (void)setCharacterShape:(nullable NSNumber *)characterShape range:(NSRange)range; - (void)setRunDelegate:(nullable CTRunDelegateRef)runDelegate range:(NSRange)range; - (void)setBaselineClass:(nullable CFStringRef)baselineClass range:(NSRange)range; - (void)setBaselineInfo:(nullable CFDictionaryRef)baselineInfo range:(NSRange)range; - (void)setBaselineReferenceInfo:(nullable CFDictionaryRef)referenceInfo range:(NSRange)range; - (void)setRubyAnnotation:(nullable CTRubyAnnotationRef)ruby range:(NSRange)range NS_AVAILABLE_IOS(8_0); - (void)setAttachment:(nullable NSTextAttachment *)attachment range:(NSRange)range NS_AVAILABLE_IOS(7_0); - (void)setLink:(nullable id)link range:(NSRange)range NS_AVAILABLE_IOS(7_0); - (void)setTextBackedString:(nullable YYTextBackedString *)textBackedString range:(NSRange)range; - (void)setTextBinding:(nullable YYTextBinding *)textBinding range:(NSRange)range; - (void)setTextAttachment:(nullable YYTextAttachment *)textAttachment range:(NSRange)range; - (void)setTextHighlight:(nullable YYTextHighlight *)textHighlight range:(NSRange)range; - (void)setTextBlockBorder:(nullable YYTextBorder *)textBlockBorder range:(NSRange)range; - (void)setTextRubyAnnotation:(nullable YYTextRubyAnnotation *)ruby range:(NSRange)range NS_AVAILABLE_IOS(8_0); #pragma mark - Convenience methods for text highlight ///============================================================================= /// @name Convenience methods for text highlight ///============================================================================= /** Convenience method to set text highlight @param range text range @param color text color (pass nil to ignore) @param backgroundColor text background color when highlight @param userInfo user information dictionary (pass nil to ignore) @param tapAction tap action when user tap the highlight (pass nil to ignore) @param longPressAction long press action when user long press the highlight (pass nil to ignore) */ - (void)setTextHighlightRange:(NSRange)range color:(nullable UIColor *)color backgroundColor:(nullable UIColor *)backgroundColor userInfo:(nullable NSDictionary *)userInfo tapAction:(nullable YYTextAction)tapAction longPressAction:(nullable YYTextAction)longPressAction; /** Convenience method to set text highlight @param range text range @param color text color (pass nil to ignore) @param backgroundColor text background color when highlight @param tapAction tap action when user tap the highlight (pass nil to ignore) */ - (void)setTextHighlightRange:(NSRange)range color:(nullable UIColor *)color backgroundColor:(nullable UIColor *)backgroundColor tapAction:(nullable YYTextAction)tapAction; /** Convenience method to set text highlight @param range text range @param color text color (pass nil to ignore) @param backgroundColor text background color when highlight @param userInfo tap action when user tap the highlight (pass nil to ignore) */ - (void)setTextHighlightRange:(NSRange)range color:(nullable UIColor *)color backgroundColor:(nullable UIColor *)backgroundColor userInfo:(nullable NSDictionary *)userInfo; #pragma mark - Utilities ///============================================================================= /// @name Utilities ///============================================================================= /** Inserts into the receiver the characters of a given string at a given location. The new string inherit the attributes of the first replaced character from location. @param string The string to insert into the receiver, must not be nil. @param location The location at which string is inserted. The location must not exceed the bounds of the receiver. @throw Raises an NSRangeException if the location out of bounds. */ - (void)insertString:(NSString *)string atIndex:(NSUInteger)location; /** Adds to the end of the receiver the characters of a given string. The new string inherit the attributes of the receiver's tail. @param string The string to append to the receiver, must not be nil. */ - (void)appendString:(NSString *)string; /** Set foreground color with [UIColor clearColor] in joined-emoji range. Emoji drawing will not be affected by the foreground color. @discussion In iOS 8.3, Apple releases some new diversified emojis. There's some single emoji which can be assembled to a new 'joined-emoji'. The joiner is unicode character 'ZERO WIDTH JOINER' (U+200D). For example: -> . When there are more than 5 'joined-emoji' in a same CTLine, CoreText may render some extra glyphs above the emoji. It's a bug in CoreText, try this method to avoid. This bug is fixed in iOS 9. */ - (void)setClearColorToJoinedEmoji; /** Removes all discontinuous attributes in a specified range. See `allDiscontinuousAttributeKeys`. @param range A text range. */ - (void)removeDiscontinuousAttributesInRange:(NSRange)range; /** Returns all discontinuous attribute keys, such as RunDelegate/Attachment/Ruby. @discussion These attributes can only set to a specified range of text, and should not extend to other range when editing text. */ + (NSArray<NSString *> *)allDiscontinuousAttributeKeys; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/NSAttributedString+YYText.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
12,323
```objective-c // // YYTextUtilities.m // YYKit <path_to_url // // Created by ibireme on 15/4/6. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextUtilities.h" NSCharacterSet *YYTextVerticalFormRotateCharacterSet() { static NSMutableCharacterSet *set; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ set = [NSMutableCharacterSet new]; [set addCharactersInRange:NSMakeRange(0x1100, 256)]; // Hangul Jamo [set addCharactersInRange:NSMakeRange(0x2460, 160)]; // Enclosed Alphanumerics [set addCharactersInRange:NSMakeRange(0x2600, 256)]; // Miscellaneous Symbols [set addCharactersInRange:NSMakeRange(0x2700, 192)]; // Dingbats [set addCharactersInRange:NSMakeRange(0x2E80, 128)]; // CJK Radicals Supplement [set addCharactersInRange:NSMakeRange(0x2F00, 224)]; // Kangxi Radicals [set addCharactersInRange:NSMakeRange(0x2FF0, 16)]; // Ideographic Description Characters [set addCharactersInRange:NSMakeRange(0x3000, 64)]; // CJK Symbols and Punctuation [set removeCharactersInRange:NSMakeRange(0x3008, 10)]; [set removeCharactersInRange:NSMakeRange(0x3014, 12)]; [set addCharactersInRange:NSMakeRange(0x3040, 96)]; // Hiragana [set addCharactersInRange:NSMakeRange(0x30A0, 96)]; // Katakana [set addCharactersInRange:NSMakeRange(0x3100, 48)]; // Bopomofo [set addCharactersInRange:NSMakeRange(0x3130, 96)]; // Hangul Compatibility Jamo [set addCharactersInRange:NSMakeRange(0x3190, 16)]; // Kanbun [set addCharactersInRange:NSMakeRange(0x31A0, 32)]; // Bopomofo Extended [set addCharactersInRange:NSMakeRange(0x31C0, 48)]; // CJK Strokes [set addCharactersInRange:NSMakeRange(0x31F0, 16)]; // Katakana Phonetic Extensions [set addCharactersInRange:NSMakeRange(0x3200, 256)]; // Enclosed CJK Letters and Months [set addCharactersInRange:NSMakeRange(0x3300, 256)]; // CJK Compatibility [set addCharactersInRange:NSMakeRange(0x3400, 2582)]; // CJK Unified Ideographs Extension A [set addCharactersInRange:NSMakeRange(0x4E00, 20941)]; // CJK Unified Ideographs [set addCharactersInRange:NSMakeRange(0xAC00, 11172)]; // Hangul Syllables [set addCharactersInRange:NSMakeRange(0xD7B0, 80)]; // Hangul Jamo Extended-B [set addCharactersInString:@""]; // U+F8FF (Private Use Area) [set addCharactersInRange:NSMakeRange(0xF900, 512)]; // CJK Compatibility Ideographs [set addCharactersInRange:NSMakeRange(0xFE10, 16)]; // Vertical Forms [set addCharactersInRange:NSMakeRange(0xFF00, 240)]; // Halfwidth and Fullwidth Forms [set addCharactersInRange:NSMakeRange(0x1F200, 256)]; // Enclosed Ideographic Supplement [set addCharactersInRange:NSMakeRange(0x1F300, 768)]; // Enclosed Ideographic Supplement [set addCharactersInRange:NSMakeRange(0x1F600, 80)]; // Emoticons (Emoji) [set addCharactersInRange:NSMakeRange(0x1F680, 128)]; // Transport and Map Symbols // See path_to_url for more information. }); return set; } NSCharacterSet *YYTextVerticalFormRotateAndMoveCharacterSet() { static NSMutableCharacterSet *set; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ set = [NSMutableCharacterSet new]; [set addCharactersInString:@""]; }); return set; } ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/String/YYTextUtilities.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
907
```objective-c // // YYTextLayout.h // YYKit <path_to_url // // Created by ibireme on 15/3/3. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextDebugOption.h> #import <YYKit/YYTextLine.h> #import <YYKit/YYTextInput.h> #else #import "YYTextDebugOption.h" #import "YYTextLine.h" #import "YYTextInput.h" #endif @protocol YYTextLinePositionModifier; NS_ASSUME_NONNULL_BEGIN /** The max text container size in layout. */ extern const CGSize YYTextContainerMaxSize; /** The YYTextContainer class defines a region in which text is laid out. YYTextLayout class uses one or more YYTextContainer objects to generate layouts. A YYTextContainer defines rectangular regions (`size` and `insets`) or nonrectangular shapes (`path`), and you can define exclusion paths inside the text container's bounding rectangle so that text flows around the exclusion path as it is laid out. All methods in this class is thread-safe. Example: <------- container asdfasdfasdfasdfasdfa <------------ container insets asdfasdfa asdfasdfa asdfas asdasd asdfa <----------------------- container exclusion path asdfas adfasd asdfasdfa asdfasdfa asdfasdfasdfasdfasdfa */ @interface YYTextContainer : NSObject <NSCoding, NSCopying> /// Creates a container with the specified size. @param size The size. + (instancetype)containerWithSize:(CGSize)size; /// Creates a container with the specified size and insets. @param size The size. @param insets The text insets. + (instancetype)containerWithSize:(CGSize)size insets:(UIEdgeInsets)insets; /// Creates a container with the specified path. @param size The path. + (instancetype)containerWithPath:(nullable UIBezierPath *)path; /// The constrained size. (if the size is larger than YYTextContainerMaxSize, it will be clipped) @property CGSize size; /// The insets for constrained size. The inset value should not be negative. Default is UIEdgeInsetsZero. @property UIEdgeInsets insets; /// Custom constrained path. Set this property to ignore `size` and `insets`. Default is nil. @property (nullable, copy) UIBezierPath *path; /// An array of `UIBezierPath` for path exclusion. Default is nil. @property (nullable, copy) NSArray<UIBezierPath *> *exclusionPaths; /// Path line width. Default is 0; @property CGFloat pathLineWidth; /// YES:(PathFillEvenOdd) Text is filled in the area that would be painted if the path were given to CGContextEOFillPath. /// NO: (PathFillWindingNumber) Text is fill in the area that would be painted if the path were given to CGContextFillPath. /// Default is YES; @property (getter=isPathFillEvenOdd) BOOL pathFillEvenOdd; /// Whether the text is vertical form (may used for CJK text layout). Default is NO. @property (getter=isVerticalForm) BOOL verticalForm; /// Maximum number of rows, 0 means no limit. Default is 0. @property NSUInteger maximumNumberOfRows; /// The line truncation type, default is none. @property YYTextTruncationType truncationType; /// The truncation token. If nil, the layout will use "" instead. Default is nil. @property (nullable, copy) NSAttributedString *truncationToken; /// This modifier is applied to the lines before the layout is completed, /// give you a chance to modify the line position. Default is nil. @property (nullable, copy) id<YYTextLinePositionModifier> linePositionModifier; @end /** The YYTextLinePositionModifier protocol declares the required method to modify the line position in text layout progress. See `YYTextLinePositionSimpleModifier` for example. */ @protocol YYTextLinePositionModifier <NSObject, NSCopying> @required /** This method will called before layout is completed. The method should be thread-safe. @param lines An array of YYTextLine. @param text The full text. @param container The layout container. */ - (void)modifyLines:(NSArray<YYTextLine *> *)lines fromText:(NSAttributedString *)text inContainer:(YYTextContainer *)container; @end /** A simple implementation of `YYTextLinePositionModifier`. It can fix each line's position to a specified value, lets each line of height be the same. */ @interface YYTextLinePositionSimpleModifier : NSObject <YYTextLinePositionModifier> @property (assign) CGFloat fixedLineHeight; ///< The fixed line height (distance between two baseline). @end /** YYTextLayout class is a readonly class stores text layout result. All the property in this class is readonly, and should not be changed. The methods in this class is thread-safe (except some of the draw methods). example: (layout with a circle exclusion path) <------ container [--------Line0--------] <- Row0 [--------Line1--------] <- Row1 [-Line2-] [-Line3-] <- Row2 [-Line4] [Line5-] <- Row3 [-Line6-] [-Line7-] <- Row4 [--------Line8--------] <- Row5 [--------Line9--------] <- Row6 */ @interface YYTextLayout : NSObject <NSCoding> #pragma mark - Generate text layout ///============================================================================= /// @name Generate text layout ///============================================================================= /** Generate a layout with the given container size and text. @param size The text container's size @param text The text (if nil, returns nil). @return A new layout, or nil when an error occurs. */ + (nullable YYTextLayout *)layoutWithContainerSize:(CGSize)size text:(NSAttributedString *)text; /** Generate a layout with the given container and text. @param container The text container (if nil, returns nil). @param text The text (if nil, returns nil). @return A new layout, or nil when an error occurs. */ + (nullable YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text; /** Generate a layout with the given container and text. @param container The text container (if nil, returns nil). @param text The text (if nil, returns nil). @param range The text range (if out of range, returns nil). If the length of the range is 0, it means the length is no limit. @return A new layout, or nil when an error occurs. */ + (nullable YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text range:(NSRange)range; /** Generate layouts with the given containers and text. @param containers An array of YYTextContainer object (if nil, returns nil). @param text The text (if nil, returns nil). @return An array of YYTextLayout object (the count is same as containers), or nil when an error occurs. */ + (nullable NSArray<YYTextLayout *> *)layoutWithContainers:(NSArray<YYTextContainer *> *)containers text:(NSAttributedString *)text; /** Generate layouts with the given containers and text. @param containers An array of YYTextContainer object (if nil, returns nil). @param text The text (if nil, returns nil). @param range The text range (if out of range, returns nil). If the length of the range is 0, it means the length is no limit. @return An array of YYTextLayout object (the count is same as containers), or nil when an error occurs. */ + (nullable NSArray<YYTextLayout *> *)layoutWithContainers:(NSArray<YYTextContainer *> *)containers text:(NSAttributedString *)text range:(NSRange)range; - (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)new UNAVAILABLE_ATTRIBUTE; #pragma mark - Text layout attributes ///============================================================================= /// @name Text layout attributes ///============================================================================= ///< The text container @property (nonatomic, strong, readonly) YYTextContainer *container; ///< The full text @property (nonatomic, strong, readonly) NSAttributedString *text; ///< The text range in full text @property (nonatomic, readonly) NSRange range; ///< CTFrameSetter @property (nonatomic, readonly) CTFramesetterRef frameSetter; ///< CTFrame @property (nonatomic, readonly) CTFrameRef frame; ///< Array of `YYTextLine`, no truncated @property (nonatomic, strong, readonly) NSArray<YYTextLine *> *lines; ///< YYTextLine with truncated token, or nil @property (nullable, nonatomic, strong, readonly) YYTextLine *truncatedLine; ///< Array of `YYTextAttachment` @property (nullable, nonatomic, strong, readonly) NSArray<YYTextAttachment *> *attachments; ///< Array of NSRange(wrapped by NSValue) in text @property (nullable, nonatomic, strong, readonly) NSArray<NSValue *> *attachmentRanges; ///< Array of CGRect(wrapped by NSValue) in container @property (nullable, nonatomic, strong, readonly) NSArray<NSValue *> *attachmentRects; ///< Set of Attachment (UIImage/UIView/CALayer) @property (nullable, nonatomic, strong, readonly) NSSet *attachmentContentsSet; ///< Number of rows @property (nonatomic, readonly) NSUInteger rowCount; ///< Visible text range @property (nonatomic, readonly) NSRange visibleRange; ///< Bounding rect (glyphs) @property (nonatomic, readonly) CGRect textBoundingRect; ///< Bounding size (glyphs and insets, ceil to pixel) @property (nonatomic, readonly) CGSize textBoundingSize; ///< Has highlight attribute @property (nonatomic, readonly) BOOL containsHighlight; ///< Has block border attribute @property (nonatomic, readonly) BOOL needDrawBlockBorder; ///< Has background border attribute @property (nonatomic, readonly) BOOL needDrawBackgroundBorder; ///< Has shadow attribute @property (nonatomic, readonly) BOOL needDrawShadow; ///< Has underline attribute @property (nonatomic, readonly) BOOL needDrawUnderline; ///< Has visible text @property (nonatomic, readonly) BOOL needDrawText; ///< Has attachment attribute @property (nonatomic, readonly) BOOL needDrawAttachment; ///< Has inner shadow attribute @property (nonatomic, readonly) BOOL needDrawInnerShadow; ///< Has strickthrough attribute @property (nonatomic, readonly) BOOL needDrawStrikethrough; ///< Has border attribute @property (nonatomic, readonly) BOOL needDrawBorder; #pragma mark - Query information from text layout ///============================================================================= /// @name Query information from text layout ///============================================================================= /** The first line index for row. @param row A row index. @return The line index, or NSNotFound if not found. */ - (NSUInteger)lineIndexForRow:(NSUInteger)row; /** The number of lines for row. @param row A row index. @return The number of lines, or NSNotFound when an error occurs. */ - (NSUInteger)lineCountForRow:(NSUInteger)row; /** The row index for line. @param line A row index. @return The row index, or NSNotFound if not found. */ - (NSUInteger)rowIndexForLine:(NSUInteger)line; /** The line index for a specified point. @discussion It returns NSNotFound if there's no text at the point. @param point A point in the container. @return The line index, or NSNotFound if not found. */ - (NSUInteger)lineIndexForPoint:(CGPoint)point; /** The line index closest to a specified point. @param point A point in the container. @return The line index, or NSNotFound if no line exist in layout. */ - (NSUInteger)closestLineIndexForPoint:(CGPoint)point; /** The offset in container for a text position in a specified line. @discussion The offset is the text position's baseline point.x. If the container is vertical form, the offset is the baseline point.y; @param position The text position in string. @param lineIndex The line index. @return The offset in container, or CGFLOAT_MAX if not found. */ - (CGFloat)offsetForTextPosition:(NSUInteger)position lineIndex:(NSUInteger)lineIndex; /** The text position for a point in a specified line. @discussion This method just call CTLineGetStringIndexForPosition() and does NOT consider the emoji, line break character, binding text... @param point A point in the container. @param lineIndex The line index. @return The text position, or NSNotFound if not found. */ - (NSUInteger)textPositionForPoint:(CGPoint)point lineIndex:(NSUInteger)lineIndex; /** The closest text position to a specified point. @discussion This method takes into account the restrict of emoji, line break character, binding text and text affinity. @param point A point in the container. @return A text position, or nil if not found. */ - (nullable YYTextPosition *)closestPositionToPoint:(CGPoint)point; /** Returns the new position when moving selection grabber in text view. @discussion There are two grabber in the text selection period, user can only move one grabber at the same time. @param point A point in the container. @param oldPosition The old text position for the moving grabber. @param otherPosition The other position in text selection view. @return A text position, or nil if not found. */ - (nullable YYTextPosition *)positionForPoint:(CGPoint)point oldPosition:(YYTextPosition *)oldPosition otherPosition:(YYTextPosition *)otherPosition; /** Returns the character or range of characters that is at a given point in the container. If there is no text at the point, returns nil. @discussion This method takes into account the restrict of emoji, line break character, binding text and text affinity. @param point A point in the container. @return An object representing a range that encloses a character (or characters) at point. Or nil if not found. */ - (nullable YYTextRange *)textRangeAtPoint:(CGPoint)point; /** Returns the closest character or range of characters that is at a given point in the container. @discussion This method takes into account the restrict of emoji, line break character, binding text and text affinity. @param point A point in the container. @return An object representing a range that encloses a character (or characters) at point. Or nil if not found. */ - (nullable YYTextRange *)closestTextRangeAtPoint:(CGPoint)point; /** If the position is inside an emoji, composed character sequences, line break '\\r\\n' or custom binding range, then returns the range by extend the position. Otherwise, returns a zero length range from the position. @param position A text-position object that identifies a location in layout. @return A text-range object that extend the position. Or nil if an error occurs */ - (nullable YYTextRange *)textRangeByExtendingPosition:(YYTextPosition *)position; /** Returns a text range at a given offset in a specified direction from another text position to its farthest extent in a certain direction of layout. @param position A text-position object that identifies a location in layout. @param direction A constant that indicates a direction of layout (right, left, up, down). @param offset A character offset from position. @return A text-range object that represents the distance from position to the farthest extent in direction. Or nil if an error occurs. */ - (nullable YYTextRange *)textRangeByExtendingPosition:(YYTextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset; /** Returns the line index for a given text position. @discussion This method takes into account the text affinity. @param position A text-position object that identifies a location in layout. @return The line index, or NSNotFound if not found. */ - (NSUInteger)lineIndexForPosition:(YYTextPosition *)position; /** Returns the baseline position for a given text position. @param position An object that identifies a location in the layout. @return The baseline position for text, or CGPointZero if not found. */ - (CGPoint)linePositionForPosition:(YYTextPosition *)position; /** Returns a rectangle used to draw the caret at a given insertion point. @param position An object that identifies a location in the layout. @return A rectangle that defines the area for drawing the caret. The width is always zero in normal container, the height is always zero in vertical form container. If not found, it returns CGRectNull. */ - (CGRect)caretRectForPosition:(YYTextPosition *)position; /** Returns the first rectangle that encloses a range of text in the layout. @param range An object that represents a range of text in layout. @return The first rectangle in a range of text. You might use this rectangle to draw a correction rectangle. The "first" in the name refers the rectangle enclosing the first line when the range encompasses multiple lines of text. If not found, it returns CGRectNull. */ - (CGRect)firstRectForRange:(YYTextRange *)range; /** Returns the rectangle union that encloses a range of text in the layout. @param range An object that represents a range of text in layout. @return A rectangle that defines the area than encloses the range. If not found, it returns CGRectNull. */ - (CGRect)rectForRange:(YYTextRange *)range; /** Returns an array of selection rects corresponding to the range of text. The start and end rect can be used to show grabber. @param range An object representing a range in text. @return An array of `YYTextSelectionRect` objects that encompass the selection. If not found, the array is empty. */ - (NSArray<YYTextSelectionRect *> *)selectionRectsForRange:(YYTextRange *)range; /** Returns an array of selection rects corresponding to the range of text. @param range An object representing a range in text. @return An array of `YYTextSelectionRect` objects that encompass the selection. If not found, the array is empty. */ - (NSArray<YYTextSelectionRect *> *)selectionRectsWithoutStartAndEndForRange:(YYTextRange *)range; /** Returns the start and end selection rects corresponding to the range of text. The start and end rect can be used to show grabber. @param range An object representing a range in text. @return An array of `YYTextSelectionRect` objects contains the start and end to the selection. If not found, the array is empty. */ - (NSArray<YYTextSelectionRect *> *)selectionRectsWithOnlyStartAndEndForRange:(YYTextRange *)range; #pragma mark - Draw text layout ///============================================================================= /// @name Draw text layout ///============================================================================= /** Draw the layout and show the attachments. @discussion If the `view` parameter is not nil, then the attachment views will add to this `view`, and if the `layer` parameter is not nil, then the attachment layers will add to this `layer`. @warning This method should be called on main thread if `view` or `layer` parameter is not nil and there's UIView or CALayer attachments in layout. Otherwise, it can be called on any thread. @param context The draw context. Pass nil to avoid text and image drawing. @param size The context size. @param point The point at which to draw the layout. @param view The attachment views will add to this view. @param layer The attachment layers will add to this layer. @param debug The debug option. Pass nil to avoid debug drawing. @param cancel The cancel checker block. It will be called in drawing progress. If it returns YES, the further draw progress will be canceled. Pass nil to ignore this feature. */ - (void)drawInContext:(nullable CGContextRef)context size:(CGSize)size point:(CGPoint)point view:(nullable UIView *)view layer:(nullable CALayer *)layer debug:(nullable YYTextDebugOption *)debug cancel:(nullable BOOL (^)(void))cancel; /** Draw the layout text and image (without view or layer attachments). @discussion This method is thread safe and can be called on any thread. @param context The draw context. Pass nil to avoid text and image drawing. @param size The context size. @param debug The debug option. Pass nil to avoid debug drawing. */ - (void)drawInContext:(nullable CGContextRef)context size:(CGSize)size debug:(nullable YYTextDebugOption *)debug; /** Show view and layer attachments. @warning This method must be called on main thread. @param view The attachment views will add to this view. @param layer The attachment layers will add to this layer. */ - (void)addAttachmentToView:(nullable UIView *)view layer:(nullable CALayer *)layer; /** Remove attachment views and layers from their super container. @warning This method must be called on main thread. */ - (void)removeAttachmentFromViewAndLayer; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextLayout.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
4,568
```objective-c // // YYTextEffectWindow.h // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextMagnifier.h> #import <YYKit/YYTextSelectionView.h> #else #import "YYTextMagnifier.h" #import "YYTextSelectionView.h" #endif NS_ASSUME_NONNULL_BEGIN /** A window to display magnifier and extra contents for text view. @discussion Use `sharedWindow` to get the instance, don't create your own instance. Typically, you should not use this class directly. */ @interface YYTextEffectWindow : UIWindow /// Returns the shared instance (returns nil in App Extension). + (nullable instancetype)sharedWindow; /// Show the magnifier in this window with a 'popup' animation. @param mag A magnifier. - (void)showMagnifier:(YYTextMagnifier *)mag; /// Update the magnifier content and position. @param mag A magnifier. - (void)moveMagnifier:(YYTextMagnifier *)mag; /// Remove the magnifier from this window with a 'shrink' animation. @param mag A magnifier. - (void)hideMagnifier:(YYTextMagnifier *)mag; /// Show the selection dot in this window if the dot is clipped by the selection view. /// @param selection A selection view. - (void)showSelectionDot:(YYTextSelectionView *)selection; /// Remove the selection dot from this window. /// @param selection A selection view. - (void)hideSelectionDot:(YYTextSelectionView *)selection; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextEffectWindow.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
392
```objective-c // // YYTextEffectWindow.m // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextEffectWindow.h" #import "YYTextKeyboardManager.h" #import "YYKitMacro.h" #import "YYCGUtilities.h" #import "UIView+YYAdd.h" #import "UIApplication+YYAdd.h" @implementation YYTextEffectWindow + (instancetype)sharedWindow { static YYTextEffectWindow *one = nil; if (one == nil) { // iOS 9 compatible NSString *mode = [NSRunLoop currentRunLoop].currentMode; if (mode.length == 27 && [mode hasPrefix:@"UI"] && [mode hasSuffix:@"InitializationRunLoopMode"]) { return nil; } } static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (![UIApplication isAppExtension]) { one = [self new]; one.frame = (CGRect){.size = kScreenSize}; one.userInteractionEnabled = NO; one.windowLevel = UIWindowLevelStatusBar + 1; one.hidden = NO; // for iOS 9: one.opaque = NO; one.backgroundColor = [UIColor clearColor]; one.layer.backgroundColor = [UIColor clearColor].CGColor; } }); return one; } // stop self from becoming the KeyWindow - (void)becomeKeyWindow { [[[UIApplication sharedExtensionApplication].delegate window] makeKeyWindow]; } - (UIViewController *)rootViewController { for (UIWindow *window in [[UIApplication sharedExtensionApplication] windows]) { if (self == window) continue; if (window.hidden) continue; UIViewController *topViewController = window.rootViewController; if (topViewController) return topViewController; } UIViewController *viewController = [super rootViewController]; if (!viewController) { viewController = [UIViewController new]; [super setRootViewController:viewController]; } return viewController; } // Bring self to front - (void)_updateWindowLevel { UIApplication *app = [UIApplication sharedExtensionApplication]; if (!app) return; UIWindow *top = app.windows.lastObject; UIWindow *key = app.keyWindow; if (key && key.windowLevel > top.windowLevel) top = key; if (top == self) return; self.windowLevel = top.windowLevel + 1; } - (YYTextDirection)_keyboardDirection { CGRect keyboardFrame = [YYTextKeyboardManager defaultManager].keyboardFrame; keyboardFrame = [[YYTextKeyboardManager defaultManager] convertRect:keyboardFrame toView:self]; if (CGRectIsNull(keyboardFrame) || CGRectIsEmpty(keyboardFrame)) return YYTextDirectionNone; if (CGRectGetMinY(keyboardFrame) == 0 && CGRectGetMinX(keyboardFrame) == 0 && CGRectGetMaxX(keyboardFrame) == CGRectGetWidth(self.frame)) return YYTextDirectionTop; if (CGRectGetMaxX(keyboardFrame) == CGRectGetWidth(self.frame) && CGRectGetMinY(keyboardFrame) == 0 && CGRectGetMaxY(keyboardFrame) == CGRectGetHeight(self.frame)) return YYTextDirectionRight; if (CGRectGetMaxY(keyboardFrame) == CGRectGetHeight(self.frame) && CGRectGetMinX(keyboardFrame) == 0 && CGRectGetMaxX(keyboardFrame) == CGRectGetWidth(self.frame)) return YYTextDirectionBottom; if (CGRectGetMinX(keyboardFrame) == 0 && CGRectGetMinY(keyboardFrame) == 0 && CGRectGetMaxY(keyboardFrame) == CGRectGetHeight(self.frame)) return YYTextDirectionLeft; return YYTextDirectionNone; } - (CGPoint)_correctedCaptureCenter:(CGPoint)center{ CGRect keyboardFrame = [YYTextKeyboardManager defaultManager].keyboardFrame; keyboardFrame = [[YYTextKeyboardManager defaultManager] convertRect:keyboardFrame toView:self]; if (!CGRectIsNull(keyboardFrame) && !CGRectIsEmpty(keyboardFrame)) { YYTextDirection direction = [self _keyboardDirection]; switch (direction) { case YYTextDirectionTop: { if (center.y < CGRectGetMaxY(keyboardFrame)) center.y = CGRectGetMaxY(keyboardFrame); } break; case YYTextDirectionRight: { if (center.x > CGRectGetMinX(keyboardFrame)) center.x = CGRectGetMinX(keyboardFrame); } break; case YYTextDirectionBottom: { if (center.y > CGRectGetMinY(keyboardFrame)) center.y = CGRectGetMinY(keyboardFrame); } break; case YYTextDirectionLeft: { if (center.x < CGRectGetMaxX(keyboardFrame)) center.x = CGRectGetMaxX(keyboardFrame); } break; default: break; } } return center; } - (CGPoint)_correctedCenter:(CGPoint)center forMagnifier:(YYTextMagnifier *)mag rotation:(CGFloat)rotation { CGFloat degree = RadiansToDegrees(rotation); degree /= 45.0; if (degree < 0) degree += (int)(-degree/8.0 + 1) * 8; if (degree > 8) degree -= (int)(degree/8.0) * 8; CGFloat caretExt = 10; if (degree <= 1 || degree >= 7) { //top if (mag.type == YYTextMagnifierTypeCaret) { if (center.y < caretExt) center.y = caretExt; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.y < mag.bounds.size.height) center.y = mag.bounds.size.height; } } else if (1 < degree && degree < 3) { // right if (mag.type == YYTextMagnifierTypeCaret) { if (center.x > self.bounds.size.width - caretExt) center.x = self.bounds.size.width - caretExt; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.x > self.bounds.size.width - mag.bounds.size.height) center.x = self.bounds.size.width - mag.bounds.size.height; } } else if (3 <= degree && degree <= 5) { // bottom if (mag.type == YYTextMagnifierTypeCaret) { if (center.y > self.bounds.size.height - caretExt) center.y = self.bounds.size.height - caretExt; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.y > mag.bounds.size.height) center.y = mag.bounds.size.height; } } else if (5 < degree && degree < 7) { // left if (mag.type == YYTextMagnifierTypeCaret) { if (center.x < caretExt) center.x = caretExt; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.x < mag.bounds.size.height) center.x = mag.bounds.size.height; } } CGRect keyboardFrame = [YYTextKeyboardManager defaultManager].keyboardFrame; keyboardFrame = [[YYTextKeyboardManager defaultManager] convertRect:keyboardFrame toView:self]; if (!CGRectIsNull(keyboardFrame) && !CGRectIsEmpty(keyboardFrame)) { YYTextDirection direction = [self _keyboardDirection]; switch (direction) { case YYTextDirectionTop: { if (mag.type == YYTextMagnifierTypeCaret) { if (center.y - mag.bounds.size.height / 2 < CGRectGetMaxY(keyboardFrame)) center.y = CGRectGetMaxY(keyboardFrame) + mag.bounds.size.height / 2; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.y < CGRectGetMaxY(keyboardFrame)) center.y = CGRectGetMaxY(keyboardFrame); } } break; case YYTextDirectionRight: { if (mag.type == YYTextMagnifierTypeCaret) { if (center.x + mag.bounds.size.height / 2 > CGRectGetMinX(keyboardFrame)) center.x = CGRectGetMinX(keyboardFrame) - mag.bounds.size.width / 2; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.x > CGRectGetMinX(keyboardFrame)) center.x = CGRectGetMinX(keyboardFrame); } } break; case YYTextDirectionBottom: { if (mag.type == YYTextMagnifierTypeCaret) { if (center.y + mag.bounds.size.height / 2 > CGRectGetMinY(keyboardFrame)) center.y = CGRectGetMinY(keyboardFrame) - mag.bounds.size.height / 2; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.y > CGRectGetMinY(keyboardFrame)) center.y = CGRectGetMinY(keyboardFrame); } } break; case YYTextDirectionLeft: { if (mag.type == YYTextMagnifierTypeCaret) { if (center.x - mag.bounds.size.height / 2 < CGRectGetMaxX(keyboardFrame)) center.x = CGRectGetMaxX(keyboardFrame) + mag.bounds.size.width / 2; } else if (mag.type == YYTextMagnifierTypeRanged) { if (center.x < CGRectGetMaxX(keyboardFrame)) center.x = CGRectGetMaxX(keyboardFrame); } } break; default: break; } } return center; } /** Capture screen snapshot and set it to magnifier. @return Magnifier rotation radius. */ - (CGFloat)_updateMagnifier:(YYTextMagnifier *)mag { UIApplication *app = [UIApplication sharedExtensionApplication]; if (!app) return 0; UIView *hostView = mag.hostView; UIWindow *hostWindow = [hostView isKindOfClass:[UIWindow class]] ? (id)hostView : hostView.window; if (!hostView || !hostWindow) return 0; CGPoint captureCenter = [self convertPoint:mag.hostCaptureCenter fromViewOrWindow:hostView]; captureCenter = [self _correctedCaptureCenter:captureCenter]; CGRect captureRect = {.size = mag.snapshotSize}; captureRect.origin.x = captureCenter.x - captureRect.size.width / 2; captureRect.origin.y = captureCenter.y - captureRect.size.height / 2; CGAffineTransform trans = YYCGAffineTransformGetFromViews(hostView, self); CGFloat rotation = CGAffineTransformGetRotation(trans); if (mag.captureDisabled) { if (!mag.snapshot || mag.snapshot.size.width > 1) { static UIImage *placeholder; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ CGRect rect = CGRectMake(0, 0, mag.width, mag.height); UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor colorWithWhite:1 alpha:0.8] set]; CGContextFillRect(context, rect); placeholder = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }); mag.captureFadeAnimation = YES; mag.snapshot = placeholder; mag.captureFadeAnimation = NO; } return rotation; } UIGraphicsBeginImageContextWithOptions(captureRect.size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); if (!context) return rotation; CGPoint tp = CGPointMake(captureRect.size.width / 2, captureRect.size.height / 2); tp = CGPointApplyAffineTransform(tp, CGAffineTransformMakeRotation(rotation)); CGContextRotateCTM(context, -rotation); CGContextTranslateCTM(context, tp.x - captureCenter.x, tp.y - captureCenter.y); NSMutableArray *windows = app.windows.mutableCopy; UIWindow *keyWindow = app.keyWindow; if (![windows containsObject:keyWindow]) [windows addObject:keyWindow]; [windows sortUsingComparator:^NSComparisonResult(UIWindow *w1, UIWindow *w2) { if (w1.windowLevel < w2.windowLevel) return NSOrderedAscending; else if (w1.windowLevel > w2.windowLevel) return NSOrderedDescending; return NSOrderedSame; }]; UIScreen *mainScreen = [UIScreen mainScreen]; for (UIWindow *window in windows) { if (window.hidden || window.alpha <= 0.01) continue; if (window.screen != mainScreen) continue; if ([window isKindOfClass:self.class]) break; //don't capture window above self CGContextSaveGState(context); CGContextConcatCTM(context, YYCGAffineTransformGetFromViews(window, self)); [window.layer renderInContext:context]; //render //[window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO]; //slower when capture whole window CGContextRestoreGState(context); } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if (mag.snapshot.size.width == 1) { mag.captureFadeAnimation = YES; } mag.snapshot = image; mag.captureFadeAnimation = NO; return rotation; } - (void)showMagnifier:(YYTextMagnifier *)mag { if (!mag) return; if (mag.superview != self) [self addSubview:mag]; [self _updateWindowLevel]; CGFloat rotation = [self _updateMagnifier:mag]; CGPoint center = [self convertPoint:mag.hostPopoverCenter fromViewOrWindow:mag.hostView]; CGAffineTransform trans = CGAffineTransformMakeRotation(rotation); trans = CGAffineTransformScale(trans, 0.3, 0.3); mag.transform = trans; mag.center = center; if (mag.type == YYTextMagnifierTypeRanged) { mag.alpha = 0; } NSTimeInterval time = mag.type == YYTextMagnifierTypeCaret ? 0.08 : 0.1; [UIView animateWithDuration:time delay:0 options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState animations:^{ if (mag.type == YYTextMagnifierTypeCaret) { CGPoint newCenter = CGPointMake(0, -mag.fitSize.height / 2); newCenter = CGPointApplyAffineTransform(newCenter, CGAffineTransformMakeRotation(rotation)); newCenter.x += center.x; newCenter.y += center.y; mag.center = [self _correctedCenter:newCenter forMagnifier:mag rotation:rotation]; } else { mag.center = [self _correctedCenter:center forMagnifier:mag rotation:rotation]; } mag.transform = CGAffineTransformMakeRotation(rotation); mag.alpha = 1; } completion:^(BOOL finished) { }]; } - (void)moveMagnifier:(YYTextMagnifier *)mag { if (!mag) return; [self _updateWindowLevel]; CGFloat rotation = [self _updateMagnifier:mag]; CGPoint center = [self convertPoint:mag.hostPopoverCenter fromViewOrWindow:mag.hostView]; if (mag.type == YYTextMagnifierTypeCaret) { CGPoint newCenter = CGPointMake(0, -mag.fitSize.height / 2); newCenter = CGPointApplyAffineTransform(newCenter, CGAffineTransformMakeRotation(rotation)); newCenter.x += center.x; newCenter.y += center.y; mag.center = [self _correctedCenter:newCenter forMagnifier:mag rotation:rotation]; } else { mag.center = [self _correctedCenter:center forMagnifier:mag rotation:rotation]; } mag.transform = CGAffineTransformMakeRotation(rotation); } - (void)hideMagnifier:(YYTextMagnifier *)mag { if (!mag) return; if (mag.superview != self) return; CGFloat rotation = [self _updateMagnifier:mag]; CGPoint center = [self convertPoint:mag.hostPopoverCenter fromViewOrWindow:mag.hostView]; NSTimeInterval time = mag.type == YYTextMagnifierTypeCaret ? 0.20 : 0.15; [UIView animateWithDuration:time delay:0 options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState animations:^{ CGAffineTransform trans = CGAffineTransformMakeRotation(rotation); trans = CGAffineTransformScale(trans, 0.01, 0.01); mag.transform = trans; if (mag.type == YYTextMagnifierTypeCaret) { CGPoint newCenter = CGPointMake(0, -mag.fitSize.height / 2); newCenter = CGPointApplyAffineTransform(newCenter, CGAffineTransformMakeRotation(rotation)); newCenter.x += center.x; newCenter.y += center.y; mag.center = [self _correctedCenter:newCenter forMagnifier:mag rotation:rotation]; } else { mag.center = [self _correctedCenter:center forMagnifier:mag rotation:rotation]; mag.alpha = 0; } } completion:^(BOOL finished) { if (finished) { [mag removeFromSuperview]; mag.transform = CGAffineTransformIdentity; mag.alpha = 1; } }]; } - (void)_updateSelectionGrabberDot:(YYSelectionGrabberDot *)dot selection:(YYTextSelectionView *)selection{ dot.mirror.hidden = YES; if (selection.hostView.clipsToBounds == YES && dot.visibleAlpha > 0.1) { CGRect dotRect = [dot convertRect:dot.bounds toViewOrWindow:self]; BOOL dotInKeyboard = NO; CGRect keyboardFrame = [YYTextKeyboardManager defaultManager].keyboardFrame; keyboardFrame = [[YYTextKeyboardManager defaultManager] convertRect:keyboardFrame toView:self]; if (!CGRectIsNull(keyboardFrame) && !CGRectIsEmpty(keyboardFrame)) { CGRect inter = CGRectIntersection(dotRect, keyboardFrame); if (!CGRectIsNull(inter) && (inter.size.width > 1 || inter.size.height > 1)) { dotInKeyboard = YES; } } if (!dotInKeyboard) { CGRect hostRect = [selection.hostView convertRect:selection.hostView.bounds toView:self]; CGRect intersection = CGRectIntersection(dotRect, hostRect); if (CGRectGetArea(intersection) < CGRectGetArea(dotRect)) { CGFloat dist = CGPointGetDistanceToRect(CGRectGetCenter(dotRect), hostRect); if (dist < CGRectGetWidth(dot.frame) * 0.55) { dot.mirror.hidden = NO; } } } } CGPoint center = [dot convertPoint:CGPointMake(CGRectGetWidth(dot.frame) / 2, CGRectGetHeight(dot.frame) / 2) toViewOrWindow:self]; if (isnan(center.x) || isnan(center.y) || isinf(center.x) || isinf(center.y)) { dot.mirror.hidden = YES; } else { dot.mirror.center = center; } } - (void)showSelectionDot:(YYTextSelectionView *)selection { if (!selection) return; [self _updateWindowLevel]; [self insertSubview:selection.startGrabber.dot.mirror atIndex:0]; [self insertSubview:selection.endGrabber.dot.mirror atIndex:0]; [self _updateSelectionGrabberDot:selection.startGrabber.dot selection:selection]; [self _updateSelectionGrabberDot:selection.endGrabber.dot selection:selection]; } - (void)hideSelectionDot:(YYTextSelectionView *)selection { if (!selection) return; [selection.startGrabber.dot.mirror removeFromSuperview]; [selection.endGrabber.dot.mirror removeFromSuperview]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextEffectWindow.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
4,198
```objective-c // // YYTextLine.h // YYKit <path_to_url // // Created by ibireme on 15/3/10. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextAttribute.h> #else #import "YYTextAttribute.h" #endif @class YYTextRunGlyphRange; NS_ASSUME_NONNULL_BEGIN /** A text line object wrapped `CTLineRef`, see `YYTextLayout` for more. */ @interface YYTextLine : NSObject + (instancetype)lineWithCTLine:(CTLineRef)CTLine position:(CGPoint)position vertical:(BOOL)isVertical; @property (nonatomic) NSUInteger index; ///< line index @property (nonatomic) NSUInteger row; ///< line row @property (nullable, nonatomic, strong) NSArray<NSArray<YYTextRunGlyphRange *> *> *verticalRotateRange; ///< Run rotate range @property (nonatomic, readonly) CTLineRef CTLine; ///< CoreText line @property (nonatomic, readonly) NSRange range; ///< string range @property (nonatomic, readonly) BOOL vertical; ///< vertical form @property (nonatomic, readonly) CGRect bounds; ///< bounds (ascent + descent) @property (nonatomic, readonly) CGSize size; ///< bounds.size @property (nonatomic, readonly) CGFloat width; ///< bounds.size.width @property (nonatomic, readonly) CGFloat height; ///< bounds.size.height @property (nonatomic, readonly) CGFloat top; ///< bounds.origin.y @property (nonatomic, readonly) CGFloat bottom; ///< bounds.origin.y + bounds.size.height @property (nonatomic, readonly) CGFloat left; ///< bounds.origin.x @property (nonatomic, readonly) CGFloat right; ///< bounds.origin.x + bounds.size.width @property (nonatomic) CGPoint position; ///< baseline position @property (nonatomic, readonly) CGFloat ascent; ///< line ascent @property (nonatomic, readonly) CGFloat descent; ///< line descent @property (nonatomic, readonly) CGFloat leading; ///< line leading @property (nonatomic, readonly) CGFloat lineWidth; ///< line width @property (nonatomic, readonly) CGFloat trailingWhitespaceWidth; @property (nullable, nonatomic, readonly) NSArray<YYTextAttachment *> *attachments; ///< YYTextAttachment @property (nullable, nonatomic, readonly) NSArray<NSValue *> *attachmentRanges; ///< NSRange(NSValue) @property (nullable, nonatomic, readonly) NSArray<NSValue *> *attachmentRects; ///< CGRect(NSValue) @end typedef NS_ENUM(NSUInteger, YYTextRunGlyphDrawMode) { /// No rotate. YYTextRunGlyphDrawModeHorizontal = 0, /// Rotate vertical for single glyph. YYTextRunGlyphDrawModeVerticalRotate = 1, /// Rotate vertical for single glyph, and move the glyph to a better position, /// such as fullwidth punctuation. YYTextRunGlyphDrawModeVerticalRotateMove = 2, }; /** A range in CTRun, used for vertical form. */ @interface YYTextRunGlyphRange : NSObject @property (nonatomic) NSRange glyphRangeInRun; @property (nonatomic) YYTextRunGlyphDrawMode drawMode; + (instancetype)rangeWithRange:(NSRange)range drawMode:(YYTextRunGlyphDrawMode)mode; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextLine.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
730
```objective-c // // YYTextContainerView.h // YYKit <path_to_url // // Created by ibireme on 15/4/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextLayout.h> #else #import "YYTextLayout.h" #endif NS_ASSUME_NONNULL_BEGIN /** A simple view to diaplay `YYTextLayout`. @discussion This view can become first responder. If this view is first responder, all the action (such as UIMenu's action) would forward to the `hostView` property. Typically, you should not use this class directly. @warning All the methods in this class should be called on main thread. */ @interface YYTextContainerView : UIView /// First responder's aciton will forward to this view. @property (nullable, nonatomic, weak) UIView *hostView; /// Debug option for layout debug. Set this property will let the view redraw it's contents. @property (nullable, nonatomic, copy) YYTextDebugOption *debugOption; /// Text vertical alignment. @property (nonatomic) YYTextVerticalAlignment textVerticalAlignment; /// Text layout. Set this property will let the view redraw it's contents. @property (nullable, nonatomic, strong) YYTextLayout *layout; /// The contents fade animation duration when the layout's contents changed. Default is 0 (no animation). @property (nonatomic) NSTimeInterval contentsFadeDuration; /// Convenience method to set `layout` and `contentsFadeDuration`. /// @param layout Same as `layout` property. /// @param fadeDuration Same as `contentsFadeDuration` property. - (void)setLayout:(nullable YYTextLayout *)layout withFadeDuration:(NSTimeInterval)fadeDuration; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextContainerView.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
404
```objective-c // // YYTextSelectionView.h // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextAttribute.h> #import <YYKit/YYTextInput.h> #else #import "YYTextAttribute.h" #import "YYTextInput.h" #endif NS_ASSUME_NONNULL_BEGIN /** A single dot view. The frame should be foursquare. Change the background color for display. @discussion Typically, you should not use this class directly. */ @interface YYSelectionGrabberDot : UIView /// Dont't access this property. It was used by `YYTextEffectWindow`. @property (nonatomic, strong) UIView *mirror; @end /** A grabber (stick with a dot). @discussion Typically, you should not use this class directly. */ @interface YYSelectionGrabber : UIView @property (nonatomic, readonly) YYSelectionGrabberDot *dot; ///< the dot view @property (nonatomic) YYTextDirection dotDirection; ///< don't support composite direction @property (nullable, nonatomic, strong) UIColor *color; ///< tint color, default is nil @end /** The selection view for text edit and select. @discussion Typically, you should not use this class directly. */ @interface YYTextSelectionView : UIView @property (nullable, nonatomic, weak) UIView *hostView; ///< the holder view @property (nullable, nonatomic, strong) UIColor *color; ///< the tint color @property (nonatomic, getter = isCaretBlinks) BOOL caretBlinks; ///< whether the caret is blinks @property (nonatomic, getter = isCaretVisible) BOOL caretVisible; ///< whether the caret is visible @property (nonatomic, getter = isVerticalForm) BOOL verticalForm; ///< weather the text view is vertical form @property (nonatomic) CGRect caretRect; ///< caret rect (width==0 or height==0) @property (nullable, nonatomic, copy) NSArray<YYTextSelectionRect *> *selectionRects; ///< default is nil @property (nonatomic, readonly) UIView *caretView; @property (nonatomic, readonly) YYSelectionGrabber *startGrabber; @property (nonatomic, readonly) YYSelectionGrabber *endGrabber; - (BOOL)isGrabberContainsPoint:(CGPoint)point; - (BOOL)isStartGrabberContainsPoint:(CGPoint)point; - (BOOL)isEndGrabberContainsPoint:(CGPoint)point; - (BOOL)isCaretContainsPoint:(CGPoint)point; - (BOOL)isSelectionRectsContainsPoint:(CGPoint)point; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextSelectionView.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
592
```objective-c // // YYTextMagnifier.h // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> #if __has_include(<YYKit/YYKit.h>) #import <YYKit/YYTextAttribute.h> #else #import "YYTextAttribute.h" #endif NS_ASSUME_NONNULL_BEGIN /// Magnifier type typedef NS_ENUM(NSInteger, YYTextMagnifierType) { YYTextMagnifierTypeCaret, ///< Circular magnifier YYTextMagnifierTypeRanged, ///< Round rectangle magnifier }; /** A magnifier view which can be displayed in `YYTextEffectWindow`. @discussion Use `magnifierWithType:` to create instance. Typically, you should not use this class directly. */ @interface YYTextMagnifier : UIView /// Create a mangifier with the specified type. @param type The magnifier type. + (id)magnifierWithType:(YYTextMagnifierType)type; @property (nonatomic, readonly) YYTextMagnifierType type; ///< Type of magnifier @property (nonatomic, readonly) CGSize fitSize; ///< The 'best' size for magnifier view. @property (nonatomic, readonly) CGSize snapshotSize; ///< The 'best' snapshot image size for magnifier. @property (nullable, nonatomic, strong) UIImage *snapshot; ///< The image in magnifier (readwrite). @property (nullable, nonatomic, weak) UIView *hostView; ///< The coordinate based view. @property (nonatomic) CGPoint hostCaptureCenter; ///< The snapshot capture center in `hostView`. @property (nonatomic) CGPoint hostPopoverCenter; ///< The popover center in `hostView`. @property (nonatomic) BOOL hostVerticalForm; ///< The host view is vertical form. @property (nonatomic) BOOL captureDisabled; ///< A hint for `YYTextEffectWindow` to disable capture. @property (nonatomic) BOOL captureFadeAnimation; ///< Show fade animation when the snapshot image changed. @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextMagnifier.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
456
```objective-c // // YYTextInput.m // YYKit <path_to_url // // Created by ibireme on 15/4/17. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextInput.h" #import "YYKitMacro.h" @implementation YYTextPosition + (instancetype)positionWithOffset:(NSInteger)offset { return [self positionWithOffset:offset affinity:YYTextAffinityForward]; } + (instancetype)positionWithOffset:(NSInteger)offset affinity:(YYTextAffinity)affinity { YYTextPosition *p = [self new]; p->_offset = offset; p->_affinity = affinity; return p; } - (instancetype)copyWithZone:(NSZone *)zone { return [self.class positionWithOffset:_offset affinity:_affinity]; } - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p> (%@%@)", self.class, self, @(_offset), _affinity == YYTextAffinityForward ? @"F":@"B"]; } - (NSUInteger)hash { return _offset * 2 + (_affinity == YYTextAffinityForward ? 1 : 0); } - (BOOL)isEqual:(YYTextPosition *)object { if (!object) return NO; return _offset == object.offset && _affinity == object.affinity; } - (NSComparisonResult)compare:(YYTextPosition *)otherPosition { if (!otherPosition) return NSOrderedAscending; if (_offset < otherPosition.offset) return NSOrderedAscending; if (_offset > otherPosition.offset) return NSOrderedDescending; if (_affinity == YYTextAffinityBackward && otherPosition.affinity == YYTextAffinityForward) return NSOrderedAscending; if (_affinity == YYTextAffinityForward && otherPosition.affinity == YYTextAffinityBackward) return NSOrderedDescending; return NSOrderedSame; } @end @implementation YYTextRange { YYTextPosition *_start; YYTextPosition *_end; } - (instancetype)init { self = [super init]; if (!self) return nil; _start = [YYTextPosition positionWithOffset:0]; _end = [YYTextPosition positionWithOffset:0]; return self; } - (YYTextPosition *)start { return _start; } - (YYTextPosition *)end { return _end; } - (BOOL)isEmpty { return _start.offset == _end.offset; } - (NSRange)asRange { return NSMakeRange(_start.offset, _end.offset - _start.offset); } + (instancetype)rangeWithRange:(NSRange)range { return [self rangeWithRange:range affinity:YYTextAffinityForward]; } + (instancetype)rangeWithRange:(NSRange)range affinity:(YYTextAffinity)affinity { YYTextPosition *start = [YYTextPosition positionWithOffset:range.location affinity:affinity]; YYTextPosition *end = [YYTextPosition positionWithOffset:range.location + range.length affinity:affinity]; return [self rangeWithStart:start end:end]; } + (instancetype)rangeWithStart:(YYTextPosition *)start end:(YYTextPosition *)end { if (!start || !end) return nil; if ([start compare:end] == NSOrderedDescending) { YY_SWAP(start, end); } YYTextRange *range = [YYTextRange new]; range->_start = start; range->_end = end; return range; } + (instancetype)defaultRange { return [self new]; } - (instancetype)copyWithZone:(NSZone *)zone { return [self.class rangeWithStart:_start end:_end]; } - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p> (%@, %@)%@", self.class, self, @(_start.offset), @(_end.offset - _start.offset), _end.affinity == YYTextAffinityForward ? @"F":@"B"]; } - (NSUInteger)hash { return (sizeof(NSUInteger) == 8 ? OSSwapInt64(_start.hash) : OSSwapInt32(_start.hash)) + _end.hash; } - (BOOL)isEqual:(YYTextRange *)object { if (!object) return NO; return [_start isEqual:object.start] && [_end isEqual:object.end]; } @end @implementation YYTextSelectionRect @synthesize rect = _rect; @synthesize writingDirection = _writingDirection; @synthesize containsStart = _containsStart; @synthesize containsEnd = _containsEnd; @synthesize isVertical = _isVertical; - (id)copyWithZone:(NSZone *)zone { YYTextSelectionRect *one = [self.class new]; one.rect = _rect; one.writingDirection = _writingDirection; one.containsStart = _containsStart; one.containsEnd = _containsEnd; one.isVertical = _isVertical; return one; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextInput.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,077
```objective-c // // YYTextContainerView.m // YYKit <path_to_url // // Created by ibireme on 15/4/21. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextContainerView.h" @implementation YYTextContainerView { BOOL _attachmentChanged; NSMutableArray *_attachmentViews; NSMutableArray *_attachmentLayers; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (!self) return nil; self.backgroundColor = [UIColor clearColor]; _attachmentViews = [NSMutableArray array]; _attachmentLayers = [NSMutableArray array]; return self; } - (void)setDebugOption:(YYTextDebugOption *)debugOption { BOOL needDraw = _debugOption.needDrawDebug; _debugOption = debugOption.copy; if (_debugOption.needDrawDebug != needDraw) { [self setNeedsDisplay]; } } - (void)setTextVerticalAlignment:(YYTextVerticalAlignment)textVerticalAlignment { if (_textVerticalAlignment == textVerticalAlignment) return; _textVerticalAlignment = textVerticalAlignment; [self setNeedsDisplay]; } - (void)setContentsFadeDuration:(NSTimeInterval)contentsFadeDuration { if (_contentsFadeDuration == contentsFadeDuration) return; _contentsFadeDuration = contentsFadeDuration; if (contentsFadeDuration <= 0) { [self.layer removeAnimationForKey:@"contents"]; } } - (void)setLayout:(YYTextLayout *)layout { if (_layout == layout) return; _layout = layout; _attachmentChanged = YES; [self setNeedsDisplay]; } - (void)setLayout:(YYTextLayout *)layout withFadeDuration:(NSTimeInterval)fadeDuration { self.contentsFadeDuration = fadeDuration; self.layout = layout; } - (void)drawRect:(CGRect)rect { // fade content [self.layer removeAnimationForKey:@"contents"]; if (_contentsFadeDuration > 0) { CATransition *transition = [CATransition animation]; transition.duration = _contentsFadeDuration; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; transition.type = kCATransitionFade; [self.layer addAnimation:transition forKey:@"contents"]; } // update attachment if (_attachmentChanged) { for (UIView *view in _attachmentViews) { if (view.superview == self) [view removeFromSuperview]; } for (CALayer *layer in _attachmentLayers) { if (layer.superlayer == self.layer) [layer removeFromSuperlayer]; } [_attachmentViews removeAllObjects]; [_attachmentLayers removeAllObjects]; } // draw layout CGSize boundingSize = _layout.textBoundingSize; CGPoint point = CGPointZero; if (_textVerticalAlignment == YYTextVerticalAlignmentCenter) { if (_layout.container.isVerticalForm) { point.x = -(self.bounds.size.width - boundingSize.width) * 0.5; } else { point.y = (self.bounds.size.height - boundingSize.height) * 0.5; } } else if (_textVerticalAlignment == YYTextVerticalAlignmentBottom) { if (_layout.container.isVerticalForm) { point.x = -(self.bounds.size.width - boundingSize.width); } else { point.y = (self.bounds.size.height - boundingSize.height); } } [_layout drawInContext:UIGraphicsGetCurrentContext() size:self.bounds.size point:point view:self layer:self.layer debug:_debugOption cancel:nil]; // update attachment if (_attachmentChanged) { _attachmentChanged = NO; for (YYTextAttachment *a in _layout.attachments) { if ([a.content isKindOfClass:[UIView class]]) [_attachmentViews addObject:a.content]; if ([a.content isKindOfClass:[CALayer class]]) [_attachmentLayers addObject:a.content]; } } } - (void)setFrame:(CGRect)frame { CGSize oldSize = self.bounds.size; [super setFrame:frame]; if (!CGSizeEqualToSize(oldSize, self.bounds.size)) { [self setNeedsLayout]; } } - (void)setBounds:(CGRect)bounds { CGSize oldSize = self.bounds.size; [super setBounds:bounds]; if (!CGSizeEqualToSize(oldSize, self.bounds.size)) { [self setNeedsLayout]; } } #pragma mark - UIResponder forward - (BOOL)canBecomeFirstResponder { return YES; } - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { return [self.hostView canPerformAction:action withSender:sender]; } - (id)forwardingTargetForSelector:(SEL)aSelector { return self.hostView; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextContainerView.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,029
```objective-c // // YYTextDebugOption.m // YYKit <path_to_url // // Created by ibireme on 15/4/8. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextDebugOption.h" #import "YYKitMacro.h" #import "UIColor+YYAdd.h" #import "YYWeakProxy.h" static pthread_mutex_t _sharedDebugLock; static CFMutableSetRef _sharedDebugTargets = nil; static YYTextDebugOption *_sharedDebugOption = nil; static const void* _sharedDebugSetRetain(CFAllocatorRef allocator, const void *value) { return value; } static void _sharedDebugSetRelease(CFAllocatorRef allocator, const void *value) { } void _sharedDebugSetFunction(const void *value, void *context) { id<YYTextDebugTarget> target = (__bridge id<YYTextDebugTarget>)(value); [target setDebugOption:_sharedDebugOption]; } static void _initSharedDebug() { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ pthread_mutex_init(&_sharedDebugLock, NULL); CFSetCallBacks callbacks = kCFTypeSetCallBacks; callbacks.retain = _sharedDebugSetRetain; callbacks.release = _sharedDebugSetRelease; _sharedDebugTargets = CFSetCreateMutable(CFAllocatorGetDefault(), 0, &callbacks); }); } static void _setSharedDebugOption(YYTextDebugOption *option) { _initSharedDebug(); pthread_mutex_lock(&_sharedDebugLock); _sharedDebugOption = option.copy; CFSetApplyFunction(_sharedDebugTargets, _sharedDebugSetFunction, NULL); pthread_mutex_unlock(&_sharedDebugLock); } static YYTextDebugOption *_getSharedDebugOption() { _initSharedDebug(); pthread_mutex_lock(&_sharedDebugLock); YYTextDebugOption *op = _sharedDebugOption; pthread_mutex_unlock(&_sharedDebugLock); return op; } static void _addDebugTarget(id<YYTextDebugTarget> target) { _initSharedDebug(); pthread_mutex_lock(&_sharedDebugLock); CFSetAddValue(_sharedDebugTargets, (__bridge const void *)(target)); pthread_mutex_unlock(&_sharedDebugLock); } static void _removeDebugTarget(id<YYTextDebugTarget> target) { _initSharedDebug(); pthread_mutex_lock(&_sharedDebugLock); CFSetRemoveValue(_sharedDebugTargets, (__bridge const void *)(target)); pthread_mutex_unlock(&_sharedDebugLock); } @implementation YYTextDebugOption - (id)copyWithZone:(NSZone *)zone { YYTextDebugOption *op = [self.class new]; op.baselineColor = self.baselineColor; op.CTFrameBorderColor = self.CTFrameBorderColor; op.CTFrameFillColor = self.CTFrameFillColor; op.CTLineBorderColor = self.CTLineBorderColor; op.CTLineFillColor = self.CTLineFillColor; op.CTLineNumberColor = self.CTLineNumberColor; op.CTRunBorderColor = self.CTRunBorderColor; op.CTRunFillColor = self.CTRunFillColor; op.CTRunNumberColor = self.CTRunNumberColor; op.CGGlyphBorderColor = self.CGGlyphBorderColor; op.CGGlyphFillColor = self.CGGlyphFillColor; return op; } - (BOOL)needDrawDebug { if (self.baselineColor || self.CTFrameBorderColor || self.CTFrameFillColor || self.CTLineBorderColor || self.CTLineFillColor || self.CTLineNumberColor || self.CTRunBorderColor || self.CTRunFillColor || self.CTRunNumberColor || self.CGGlyphBorderColor || self.CGGlyphFillColor) return YES; return NO; } - (void)clear { self.baselineColor = nil; self.CTFrameBorderColor = nil; self.CTFrameFillColor = nil; self.CTLineBorderColor = nil; self.CTLineFillColor = nil; self.CTLineNumberColor = nil; self.CTRunBorderColor = nil; self.CTRunFillColor = nil; self.CTRunNumberColor = nil; self.CGGlyphBorderColor = nil; self.CGGlyphFillColor = nil; } + (void)addDebugTarget:(id<YYTextDebugTarget>)target { if (target) _addDebugTarget(target); } + (void)removeDebugTarget:(id<YYTextDebugTarget>)target { if (target) _removeDebugTarget(target); } + (YYTextDebugOption *)sharedDebugOption { return _getSharedDebugOption(); } + (void)setSharedDebugOption:(YYTextDebugOption *)option { YYAssertMainThread(); _setSharedDebugOption(option); } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextDebugOption.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,050
```objective-c // // YYTextKeyboardManager.h // YYKit <path_to_url // // Created by ibireme on 15/6/3. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** System keyboard transition information. Use -[YYTextKeyboardManager convertRect:toView:] to convert frame to specified view. */ typedef struct { BOOL fromVisible; ///< Keyboard visible before transition. BOOL toVisible; ///< Keyboard visible after transition. CGRect fromFrame; ///< Keyboard frame before transition. CGRect toFrame; ///< Keyboard frame after transition. NSTimeInterval animationDuration; ///< Keyboard transition animation duration. UIViewAnimationCurve animationCurve; ///< Keyboard transition animation curve. UIViewAnimationOptions animationOption; ///< Keybaord transition animation option. } YYTextKeyboardTransition; /** The YYTextKeyboardObserver protocol defines the method you can use to receive system keyboard change information. */ @protocol YYTextKeyboardObserver <NSObject> @optional - (void)keyboardChangedWithTransition:(YYTextKeyboardTransition)transition; @end /** A YYTextKeyboardManager object lets you get the system keyboard information, and track the keyboard visible/frame/transition. @discussion You should access this class in main thread. Compatible: iPhone/iPad with iOS6/7/8/9. */ @interface YYTextKeyboardManager : NSObject - (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)new UNAVAILABLE_ATTRIBUTE; /// Get the default manager (returns nil in App Extension). + (nullable instancetype)defaultManager; /// Get the keyboard window. nil if there's no keyboard window. @property (nullable, nonatomic, readonly) UIWindow *keyboardWindow; /// Get the keyboard view. nil if there's no keyboard view. @property (nullable, nonatomic, readonly) UIView *keyboardView; /// Whether the keyboard is visible. @property (nonatomic, readonly, getter=isKeyboardVisible) BOOL keyboardVisible; /// Get the keyboard frame. CGRectNull if there's no keyboard view. /// Use convertRect:toView: to convert frame to specified view. @property (nonatomic, readonly) CGRect keyboardFrame; /** Add an observer to manager to get keyboard change information. This method makes a weak reference to the observer. @param observer An observer. This method will do nothing if the observer is nil, or already added. */ - (void)addObserver:(id<YYTextKeyboardObserver>)observer; /** Remove an observer from manager. @param observer An observer. This method will do nothing if the observer is nil, or not in manager. */ - (void)removeObserver:(id<YYTextKeyboardObserver>)observer; /** Convert rect to specified view or window. @param rect The frame rect. @param view A specified view or window (pass nil to convert for main window). @return The converted rect in specifeid view. */ - (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextKeyboardManager.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
646
```objective-c // // YYTextSelectionView.m // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextSelectionView.h" #import "YYCGUtilities.h" #import "YYWeakProxy.h" #define kMarkAlpha 0.2 #define kLineWidth 2.0 #define kBlinkDuration 0.5 #define kBlinkFadeDuration 0.2 #define kBlinkFirstDelay 0.1 #define kTouchTestExtend 14.0 #define kTouchDotExtend 7.0 @implementation YYSelectionGrabberDot - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (!self) return nil; self.userInteractionEnabled = NO; self.mirror = [UIView new]; return self; } - (void)layoutSubviews { [super layoutSubviews]; CGFloat length = MIN(self.bounds.size.width, self.bounds.size.height); self.layer.cornerRadius = length * 0.5; self.mirror.bounds = self.bounds; self.mirror.layer.cornerRadius = self.layer.cornerRadius; } - (void)setBackgroundColor:(UIColor *)backgroundColor { [super setBackgroundColor:backgroundColor]; _mirror.backgroundColor = backgroundColor; } @end @implementation YYSelectionGrabber - (instancetype) initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (!self) return nil; _dot = [[YYSelectionGrabberDot alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; return self; } - (void)setDotDirection:(YYTextDirection)dotDirection { _dotDirection = dotDirection; [self addSubview:_dot]; CGRect frame = _dot.frame; CGFloat ofs = 0.5; if (dotDirection == YYTextDirectionTop) { frame.origin.y = -frame.size.height + ofs; frame.origin.x = (self.bounds.size.width - frame.size.width) / 2; } else if (dotDirection == YYTextDirectionRight) { frame.origin.x = self.bounds.size.width - ofs; frame.origin.y = (self.bounds.size.height - frame.size.height) / 2; } else if (dotDirection == YYTextDirectionBottom) { frame.origin.y = self.bounds.size.height - ofs; frame.origin.x = (self.bounds.size.width - frame.size.width) / 2; } else if (dotDirection == YYTextDirectionLeft) { frame.origin.x = -frame.size.width + ofs; frame.origin.y = (self.bounds.size.height - frame.size.height) / 2; } else { [_dot removeFromSuperview]; } _dot.frame = frame; } - (void)setColor:(UIColor *)color { self.backgroundColor = color; _dot.backgroundColor = color; _color = color; } - (void)layoutSubviews { [super layoutSubviews]; [self setDotDirection:_dotDirection]; } - (CGRect)touchRect { CGRect rect = CGRectInset(self.frame, -kTouchTestExtend, -kTouchTestExtend); UIEdgeInsets insets = {0}; if (_dotDirection == YYTextDirectionTop) { insets.top = -kTouchDotExtend; } else if (_dotDirection == YYTextDirectionRight) { insets.right = -kTouchDotExtend; } else if (_dotDirection == YYTextDirectionBottom) { insets.bottom = -kTouchDotExtend; } else if (_dotDirection == YYTextDirectionLeft) { insets.left = -kTouchDotExtend; } rect = UIEdgeInsetsInsetRect(rect, insets); return rect; } @end @interface YYTextSelectionView () @property (nonatomic, strong) NSTimer *caretTimer; @property (nonatomic, strong) UIView *caretView; @property (nonatomic, strong) YYSelectionGrabber *startGrabber; @property (nonatomic, strong) YYSelectionGrabber *endGrabber; @property (nonatomic, strong) NSMutableArray *markViews; @end @implementation YYTextSelectionView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (!self) return nil; self.userInteractionEnabled = NO; self.clipsToBounds = NO; _markViews = [NSMutableArray array]; _caretView = [UIView new]; _caretView.hidden = YES; _startGrabber = [YYSelectionGrabber new]; _startGrabber.dotDirection = YYTextDirectionTop; _startGrabber.hidden = YES; _endGrabber = [YYSelectionGrabber new]; _endGrabber.dotDirection = YYTextDirectionBottom; _endGrabber.hidden = YES; [self addSubview:_startGrabber]; [self addSubview:_endGrabber]; [self addSubview:_caretView]; return self; } - (void)dealloc { [_caretTimer invalidate]; } - (void)setColor:(UIColor *)color { _color = color; self.caretView.backgroundColor = color; self.startGrabber.color = color; self.endGrabber.color = color; [self.markViews enumerateObjectsUsingBlock: ^(UIView *v, NSUInteger idx, BOOL *stop) { v.backgroundColor = color; }]; } - (void)setCaretBlinks:(BOOL)caretBlinks { if (_caretBlinks != caretBlinks) { _caretView.alpha = 1; [self.class cancelPreviousPerformRequestsWithTarget:self selector:@selector(_startBlinks) object:nil]; if (caretBlinks) { [self performSelector:@selector(_startBlinks) withObject:nil afterDelay:kBlinkFirstDelay]; } else { [_caretTimer invalidate]; _caretTimer = nil; } _caretBlinks = caretBlinks; } } - (void)_startBlinks { [_caretTimer invalidate]; if (_caretVisible) { _caretTimer = [NSTimer timerWithTimeInterval:kBlinkDuration target:[YYWeakProxy proxyWithTarget:self] selector:@selector(_doBlink) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:_caretTimer forMode:NSDefaultRunLoopMode]; } else { _caretView.alpha = 1; } } - (void)_doBlink { [UIView animateWithDuration:kBlinkFadeDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations: ^{ if (_caretView.alpha == 1) _caretView.alpha = 0; else _caretView.alpha = 1; } completion:NULL]; } - (void)setCaretVisible:(BOOL)caretVisible { _caretVisible = caretVisible; self.caretView.hidden = !caretVisible; _caretView.alpha = 1; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_startBlinks) object:nil]; if (_caretBlinks) { [self performSelector:@selector(_startBlinks) withObject:nil afterDelay:kBlinkFirstDelay]; } } - (void)setVerticalForm:(BOOL)verticalForm { if (_verticalForm != verticalForm) { _verticalForm = verticalForm; [self setCaretRect:_caretRect]; self.startGrabber.dotDirection = verticalForm ? YYTextDirectionRight : YYTextDirectionTop; self.endGrabber.dotDirection = verticalForm ? YYTextDirectionLeft : YYTextDirectionBottom; } } - (CGRect)_standardCaretRect:(CGRect)caretRect { caretRect = CGRectStandardize(caretRect); if (_verticalForm) { if (caretRect.size.height == 0) { caretRect.size.height = kLineWidth; caretRect.origin.y -= kLineWidth * 0.5; } if (caretRect.origin.y < 0) { caretRect.origin.y = 0; } else if (caretRect.origin.y + caretRect.size.height > self.bounds.size.height) { caretRect.origin.y = self.bounds.size.height - caretRect.size.height; } } else { if (caretRect.size.width == 0) { caretRect.size.width = kLineWidth; caretRect.origin.x -= kLineWidth * 0.5; } if (caretRect.origin.x < 0) { caretRect.origin.x = 0; } else if (caretRect.origin.x + caretRect.size.width > self.bounds.size.width) { caretRect.origin.x = self.bounds.size.width - caretRect.size.width; } } caretRect = CGRectPixelRound(caretRect); if (isnan(caretRect.origin.x) || isinf(caretRect.origin.x)) caretRect.origin.x = 0; if (isnan(caretRect.origin.y) || isinf(caretRect.origin.y)) caretRect.origin.y = 0; if (isnan(caretRect.size.width) || isinf(caretRect.size.width)) caretRect.size.width = 0; if (isnan(caretRect.size.height) || isinf(caretRect.size.height)) caretRect.size.height = 0; return caretRect; } - (void)setCaretRect:(CGRect)caretRect { _caretRect = caretRect; self.caretView.frame = [self _standardCaretRect:caretRect]; CGFloat minWidth = MIN(self.caretView.bounds.size.width, self.caretView.bounds.size.height); self.caretView.layer.cornerRadius = minWidth / 2; } - (void)setSelectionRects:(NSArray *)selectionRects { _selectionRects = selectionRects.copy; [self.markViews enumerateObjectsUsingBlock: ^(UIView *v, NSUInteger idx, BOOL *stop) { [v removeFromSuperview]; }]; [self.markViews removeAllObjects]; self.startGrabber.hidden = YES; self.endGrabber.hidden = YES; [selectionRects enumerateObjectsUsingBlock: ^(YYTextSelectionRect *r, NSUInteger idx, BOOL *stop) { CGRect rect = r.rect; rect = CGRectStandardize(rect); rect = CGRectPixelRound(rect); if (r.containsStart || r.containsEnd) { rect = [self _standardCaretRect:rect]; if (r.containsStart) { self.startGrabber.hidden = NO; self.startGrabber.frame = rect; } if (r.containsEnd) { self.endGrabber.hidden = NO; self.endGrabber.frame = rect; } } else { if (rect.size.width > 0 && rect.size.height > 0) { UIView *mark = [[UIView alloc] initWithFrame:rect]; mark.backgroundColor = _color; mark.alpha = kMarkAlpha; [self insertSubview:mark atIndex:0]; [self.markViews addObject:mark]; } } }]; } - (BOOL)isGrabberContainsPoint:(CGPoint)point { return [self isStartGrabberContainsPoint:point] || [self isEndGrabberContainsPoint:point]; } - (BOOL)isStartGrabberContainsPoint:(CGPoint)point { if (_startGrabber.hidden) return NO; CGRect startRect = [_startGrabber touchRect]; CGRect endRect = [_endGrabber touchRect]; if (CGRectIntersectsRect(startRect, endRect)) { CGFloat distStart = CGPointGetDistanceToPoint(point, CGRectGetCenter(startRect)); CGFloat distEnd = CGPointGetDistanceToPoint(point, CGRectGetCenter(endRect)); if (distEnd <= distStart) return NO; } return CGRectContainsPoint(startRect, point); } - (BOOL)isEndGrabberContainsPoint:(CGPoint)point { if (_endGrabber.hidden) return NO; CGRect startRect = [_startGrabber touchRect]; CGRect endRect = [_endGrabber touchRect]; if (CGRectIntersectsRect(startRect, endRect)) { CGFloat distStart = CGPointGetDistanceToPoint(point, CGRectGetCenter(startRect)); CGFloat distEnd = CGPointGetDistanceToPoint(point, CGRectGetCenter(endRect)); if (distEnd > distStart) return NO; } return CGRectContainsPoint(endRect, point); } - (BOOL)isCaretContainsPoint:(CGPoint)point { if (_caretVisible) { CGRect rect = CGRectInset(_caretRect, -kTouchTestExtend, -kTouchTestExtend); return CGRectContainsPoint(rect, point); } return NO; } - (BOOL)isSelectionRectsContainsPoint:(CGPoint)point { if (_selectionRects.count == 0) return NO; for (YYTextSelectionRect *rect in _selectionRects) { if (CGRectContainsPoint(rect.rect, point)) return YES; } return NO; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextSelectionView.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,721
```objective-c // // YYTextInput.h // YYKit <path_to_url // // Created by ibireme on 15/4/17. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** Text position affinity. For example, the offset appears after the last character on a line is backward affinity, before the first character on the following line is forward affinity. */ typedef NS_ENUM(NSInteger, YYTextAffinity) { YYTextAffinityForward = 0, ///< offset appears before the character YYTextAffinityBackward = 1, ///< offset appears after the character }; /** A YYTextPosition object represents a position in a text container; in other words, it is an index into the backing string in a text-displaying view. YYTextPosition has the same API as Apple's implementation in UITextView/UITextField, so you can alse use it to interact with UITextView/UITextField. */ @interface YYTextPosition : UITextPosition <NSCopying> @property (nonatomic, readonly) NSInteger offset; @property (nonatomic, readonly) YYTextAffinity affinity; + (instancetype)positionWithOffset:(NSInteger)offset; + (instancetype)positionWithOffset:(NSInteger)offset affinity:(YYTextAffinity) affinity; - (NSComparisonResult)compare:(id)otherPosition; @end /** A YYTextRange object represents a range of characters in a text container; in other words, it identifies a starting index and an ending index in string backing a text-displaying view. YYTextRange has the same API as Apple's implementation in UITextView/UITextField, so you can alse use it to interact with UITextView/UITextField. */ @interface YYTextRange : UITextRange <NSCopying> @property (nonatomic, readonly) YYTextPosition *start; @property (nonatomic, readonly) YYTextPosition *end; @property (nonatomic, readonly, getter=isEmpty) BOOL empty; + (instancetype)rangeWithRange:(NSRange)range; + (instancetype)rangeWithRange:(NSRange)range affinity:(YYTextAffinity) affinity; + (instancetype)rangeWithStart:(YYTextPosition *)start end:(YYTextPosition *)end; + (instancetype)defaultRange; ///< <{0,0} Forward> - (NSRange)asRange; @end /** A YYTextSelectionRect object encapsulates information about a selected range of text in a text-displaying view. YYTextSelectionRect has the same API as Apple's implementation in UITextView/UITextField, so you can alse use it to interact with UITextView/UITextField. */ @interface YYTextSelectionRect : UITextSelectionRect <NSCopying> @property (nonatomic, readwrite) CGRect rect; @property (nonatomic, readwrite) UITextWritingDirection writingDirection; @property (nonatomic, readwrite) BOOL containsStart; @property (nonatomic, readwrite) BOOL containsEnd; @property (nonatomic, readwrite) BOOL isVertical; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextInput.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
643
```objective-c // // YYYTextLine.m // YYKit <path_to_url // // Created by ibireme on 15/3/3. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextLine.h" #import "YYTextUtilities.h" #import "YYKitMacro.h" @implementation YYTextLine { CGFloat _firstGlyphPos; // first glyph position for baseline, typically 0. } + (instancetype)lineWithCTLine:(CTLineRef)CTLine position:(CGPoint)position vertical:(BOOL)isVertical { if (!CTLine) return nil; YYTextLine *line = [self new]; line->_position = position; line->_vertical = isVertical; [line setCTLine:CTLine]; return line; } - (void)dealloc { if (_CTLine) CFRelease(_CTLine); } - (void)setCTLine:(_Nonnull CTLineRef)CTLine { if (_CTLine != CTLine) { if (CTLine) CFRetain(CTLine); if (_CTLine) CFRelease(_CTLine); _CTLine = CTLine; if (_CTLine) { _lineWidth = CTLineGetTypographicBounds(_CTLine, &_ascent, &_descent, &_leading); CFRange range = CTLineGetStringRange(_CTLine); _range = NSMakeRange(range.location, range.length); if (CTLineGetGlyphCount(_CTLine) > 0) { CFArrayRef runs = CTLineGetGlyphRuns(_CTLine); CTRunRef run = CFArrayGetValueAtIndex(runs, 0); CGPoint pos; CTRunGetPositions(run, CFRangeMake(0, 1), &pos); _firstGlyphPos = pos.x; } else { _firstGlyphPos = 0; } _trailingWhitespaceWidth = CTLineGetTrailingWhitespaceWidth(_CTLine); } else { _lineWidth = _ascent = _descent = _leading = _firstGlyphPos = _trailingWhitespaceWidth = 0; _range = NSMakeRange(0, 0); } [self reloadBounds]; } } - (void)setPosition:(CGPoint)position { _position = position; [self reloadBounds]; } - (void)reloadBounds { if (_vertical) { _bounds = CGRectMake(_position.x - _descent, _position.y, _ascent + _descent, _lineWidth); _bounds.origin.y += _firstGlyphPos; } else { _bounds = CGRectMake(_position.x, _position.y - _ascent, _lineWidth, _ascent + _descent); _bounds.origin.x += _firstGlyphPos; } _attachments = nil; _attachmentRanges = nil; _attachmentRects = nil; if (!_CTLine) return; CFArrayRef runs = CTLineGetGlyphRuns(_CTLine); NSUInteger runCount = CFArrayGetCount(runs); if (runCount == 0) return; NSMutableArray *attachments = [NSMutableArray new]; NSMutableArray *attachmentRanges = [NSMutableArray new]; NSMutableArray *attachmentRects = [NSMutableArray new]; for (NSUInteger r = 0; r < runCount; r++) { CTRunRef run = CFArrayGetValueAtIndex(runs, r); CFIndex glyphCount = CTRunGetGlyphCount(run); if (glyphCount == 0) continue; NSDictionary *attrs = (id)CTRunGetAttributes(run); YYTextAttachment *attachment = attrs[YYTextAttachmentAttributeName]; if (attachment) { CGPoint runPosition = CGPointZero; CTRunGetPositions(run, CFRangeMake(0, 1), &runPosition); CGFloat ascent, descent, leading, runWidth; CGRect runTypoBounds; runWidth = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, &leading); if (_vertical) { YY_SWAP(runPosition.x, runPosition.y); runPosition.y = _position.y + runPosition.y; runTypoBounds = CGRectMake(_position.x + runPosition.x - descent, runPosition.y , ascent + descent, runWidth); } else { runPosition.x += _position.x; runPosition.y = _position.y - runPosition.y; runTypoBounds = CGRectMake(runPosition.x, runPosition.y - ascent, runWidth, ascent + descent); } NSRange runRange = YYNSRangeFromCFRange(CTRunGetStringRange(run)); [attachments addObject:attachment]; [attachmentRanges addObject:[NSValue valueWithRange:runRange]]; [attachmentRects addObject:[NSValue valueWithCGRect:runTypoBounds]]; } } _attachments = attachments.count ? attachments : nil; _attachmentRanges = attachmentRanges.count ? attachmentRanges : nil; _attachmentRects = attachmentRects.count ? attachmentRects : nil; } - (CGSize)size { return _bounds.size; } - (CGFloat)width { return CGRectGetWidth(_bounds); } - (CGFloat)height { return CGRectGetHeight(_bounds); } - (CGFloat)top { return CGRectGetMinY(_bounds); } - (CGFloat)bottom { return CGRectGetMaxY(_bounds); } - (CGFloat)left { return CGRectGetMinX(_bounds); } - (CGFloat)right { return CGRectGetMaxX(_bounds); } - (NSString *)description { NSMutableString *desc = @"".mutableCopy; NSRange range = self.range; [desc appendFormat:@"<YYTextLine: %p> row:%zd range:%tu,%tu",self, self.row, range.location, range.length]; [desc appendFormat:@" position:%@",NSStringFromCGPoint(self.position)]; [desc appendFormat:@" bounds:%@",NSStringFromCGRect(self.bounds)]; return desc; } @end @implementation YYTextRunGlyphRange + (instancetype)rangeWithRange:(NSRange)range drawMode:(YYTextRunGlyphDrawMode)mode { YYTextRunGlyphRange *one = [self new]; one.glyphRangeInRun = range; one.drawMode = mode; return one; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextLine.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,368
```objective-c // // YYTextDebugOption.h // YYKit <path_to_url // // Created by ibireme on 15/4/8. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> @class YYTextDebugOption; NS_ASSUME_NONNULL_BEGIN /** The YYTextDebugTarget protocol defines the method a debug target should implement. A debug target can be add to the global container to receive the shared debug option changed notification. */ @protocol YYTextDebugTarget <NSObject> @required /** When the shared debug option changed, this method would be called on main thread. It should return as quickly as possible. The option's property should not be changed in this method. @param option The shared debug option. */ - (void)setDebugOption:(nullable YYTextDebugOption *)option; @end /** The debug option for YYText. */ @interface YYTextDebugOption : NSObject <NSCopying> @property (nullable, nonatomic, strong) UIColor *baselineColor; ///< baseline color @property (nullable, nonatomic, strong) UIColor *CTFrameBorderColor; ///< CTFrame path border color @property (nullable, nonatomic, strong) UIColor *CTFrameFillColor; ///< CTFrame path fill color @property (nullable, nonatomic, strong) UIColor *CTLineBorderColor; ///< CTLine bounds border color @property (nullable, nonatomic, strong) UIColor *CTLineFillColor; ///< CTLine bounds fill color @property (nullable, nonatomic, strong) UIColor *CTLineNumberColor; ///< CTLine line number color @property (nullable, nonatomic, strong) UIColor *CTRunBorderColor; ///< CTRun bounds border color @property (nullable, nonatomic, strong) UIColor *CTRunFillColor; ///< CTRun bounds fill color @property (nullable, nonatomic, strong) UIColor *CTRunNumberColor; ///< CTRun number color @property (nullable, nonatomic, strong) UIColor *CGGlyphBorderColor; ///< CGGlyph bounds border color @property (nullable, nonatomic, strong) UIColor *CGGlyphFillColor; ///< CGGlyph bounds fill color - (BOOL)needDrawDebug; ///< `YES`: at least one debug color is visible. `NO`: all debug color is invisible/nil. - (void)clear; ///< Set all debug color to nil. /** Add a debug target. @discussion When `setSharedDebugOption:` is called, all added debug target will receive `setDebugOption:` in main thread. It maintains an unsafe_unretained reference to this target. The target must to removed before dealloc. @param target A debug target. */ + (void)addDebugTarget:(id<YYTextDebugTarget>)target; /** Remove a debug target which is added by `addDebugTarget:`. @param target A debug target. */ + (void)removeDebugTarget:(id<YYTextDebugTarget>)target; /** Returns the shared debug option. @return The shared debug option, default is nil. */ + (nullable YYTextDebugOption *)sharedDebugOption; /** Set a debug option as shared debug option. This method must be called on main thread. @discussion When call this method, the new option will set to all debug target which is added by `addDebugTarget:`. @param option A new debug option (nil is valid). */ + (void)setSharedDebugOption:(nullable YYTextDebugOption *)option; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextDebugOption.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
741
```objective-c // // YYTextKeyboardManager.m // YYKit <path_to_url // // Created by ibireme on 15/6/3. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextKeyboardManager.h" #import "UIApplication+YYAdd.h" #import <objc/runtime.h> static int _YYTextKeyboardViewFrameObserverKey; /// Observer for view's frame/bounds/center/transform @interface _YYTextKeyboardViewFrameObserver : NSObject @property (nonatomic, copy) void (^notifyBlock)(UIView *keyboard); - (void)addToKeyboardView:(UIView *)keyboardView; + (instancetype)observerForView:(UIView *)keyboardView; @end @implementation _YYTextKeyboardViewFrameObserver { __unsafe_unretained UIView *_keyboardView; } - (void)addToKeyboardView:(UIView *)keyboardView { if (_keyboardView == keyboardView) return; if (_keyboardView) { [self removeFrameObserver]; objc_setAssociatedObject(_keyboardView, &_YYTextKeyboardViewFrameObserverKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } _keyboardView = keyboardView; if (keyboardView) { [self addFrameObserver]; } objc_setAssociatedObject(keyboardView, &_YYTextKeyboardViewFrameObserverKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)removeFrameObserver { [_keyboardView removeObserver:self forKeyPath:@"frame"]; [_keyboardView removeObserver:self forKeyPath:@"center"]; [_keyboardView removeObserver:self forKeyPath:@"bounds"]; [_keyboardView removeObserver:self forKeyPath:@"transform"]; _keyboardView = nil; } - (void)addFrameObserver { if (!_keyboardView) return; [_keyboardView addObserver:self forKeyPath:@"frame" options:kNilOptions context:NULL]; [_keyboardView addObserver:self forKeyPath:@"center" options:kNilOptions context:NULL]; [_keyboardView addObserver:self forKeyPath:@"bounds" options:kNilOptions context:NULL]; [_keyboardView addObserver:self forKeyPath:@"transform" options:kNilOptions context:NULL]; } - (void)dealloc { [self removeFrameObserver]; } + (instancetype)observerForView:(UIView *)keyboardView { if (!keyboardView) return nil; return objc_getAssociatedObject(keyboardView, &_YYTextKeyboardViewFrameObserverKey); } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { BOOL isPrior = [[change objectForKey:NSKeyValueChangeNotificationIsPriorKey] boolValue]; if (isPrior) return; NSKeyValueChange changeKind = [[change objectForKey:NSKeyValueChangeKindKey] integerValue]; if (changeKind != NSKeyValueChangeSetting) return; id newVal = [change objectForKey:NSKeyValueChangeNewKey]; if (newVal == [NSNull null]) newVal = nil; if (_notifyBlock) { _notifyBlock(_keyboardView); } } @end @implementation YYTextKeyboardManager { NSHashTable *_observers; CGRect _fromFrame; BOOL _fromVisible; UIInterfaceOrientation _fromOrientation; CGRect _notificationFromFrame; CGRect _notificationToFrame; NSTimeInterval _notificationDuration; UIViewAnimationCurve _notificationCurve; BOOL _hasNotification; CGRect _observedToFrame; BOOL _hasObservedChange; BOOL _lastIsNotification; } - (instancetype)init { @throw [NSException exceptionWithName:@"YYTextKeyboardManager init error" reason:@"Use 'defaultManager' to get instance." userInfo:nil]; return [super init]; } - (instancetype)_init { self = [super init]; _observers = [[NSHashTable alloc] initWithOptions:NSPointerFunctionsWeakMemory|NSPointerFunctionsObjectPointerPersonality capacity:0]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_keyboardFrameWillChangeNotification:) name:UIKeyboardWillChangeFrameNotification object:nil]; // for iPad (iOS 9) if ([UIDevice currentDevice].systemVersion.floatValue >= 9) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_keyboardFrameDidChangeNotification:) name:UIKeyboardDidChangeFrameNotification object:nil]; } return self; } - (void)_initFrameObserver { UIView *keyboardView = self.keyboardView; if (!keyboardView) return; __weak typeof(self) _self = self; _YYTextKeyboardViewFrameObserver *observer = [_YYTextKeyboardViewFrameObserver observerForView:keyboardView]; if (!observer) { observer = [_YYTextKeyboardViewFrameObserver new]; observer.notifyBlock = ^(UIView *keyboard) { [_self _keyboardFrameChanged:keyboard]; }; [observer addToKeyboardView:keyboardView]; } } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } + (instancetype)defaultManager { static YYTextKeyboardManager *mgr = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (![UIApplication isAppExtension]) { mgr = [[self alloc] _init]; } }); return mgr; } + (void)load { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self defaultManager]; }); } - (void)addObserver:(id<YYTextKeyboardObserver>)observer { if (!observer) return; [_observers addObject:observer]; } - (void)removeObserver:(id<YYTextKeyboardObserver>)observer { if (!observer) return; [_observers removeObject:observer]; } - (UIWindow *)keyboardWindow { UIApplication *app = [UIApplication sharedExtensionApplication]; if (!app) return nil; UIWindow *window = nil; for (window in app.windows) { if ([self _getKeyboardViewFromWindow:window]) return window; } window = app.keyWindow; if ([self _getKeyboardViewFromWindow:window]) return window; NSMutableArray *kbWindows = nil; for (window in app.windows) { NSString *windowName = NSStringFromClass(window.class); if ([self _systemVersion] < 9) { // UITextEffectsWindow if (windowName.length == 19 && [windowName hasPrefix:@"UI"] && [windowName hasSuffix:@"TextEffectsWindow"]) { if (!kbWindows) kbWindows = [NSMutableArray new]; [kbWindows addObject:window]; } } else { // UIRemoteKeyboardWindow if (windowName.length == 22 && [windowName hasPrefix:@"UI"] && [windowName hasSuffix:@"RemoteKeyboardWindow"]) { if (!kbWindows) kbWindows = [NSMutableArray new]; [kbWindows addObject:window]; } } } if (kbWindows.count == 1) { return kbWindows.firstObject; } return nil; } - (UIView *)keyboardView { UIApplication *app = [UIApplication sharedExtensionApplication]; if (!app) return nil; UIWindow *window = nil; UIView *view = nil; for (window in app.windows) { view = [self _getKeyboardViewFromWindow:window]; if (view) return view; } window = app.keyWindow; view = [self _getKeyboardViewFromWindow:window]; if (view) return view; return nil; } - (BOOL)isKeyboardVisible { UIWindow *window = self.keyboardWindow; if (!window) return NO; UIView *view = self.keyboardView; if (!view) return NO; CGRect rect = CGRectIntersection(window.bounds, view.frame); if (CGRectIsNull(rect)) return NO; if (CGRectIsInfinite(rect)) return NO; return rect.size.width > 0 && rect.size.height > 0; } - (CGRect)keyboardFrame { UIView *keyboard = [self keyboardView]; if (!keyboard) return CGRectNull; CGRect frame = CGRectNull; UIWindow *window = keyboard.window; if (window) { frame = [window convertRect:keyboard.frame toWindow:nil]; } else { frame = keyboard.frame; } return frame; } #pragma mark - private - (CGFloat)_systemVersion { static CGFloat v; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ v = [UIDevice currentDevice].systemVersion.floatValue; }); return v; } - (UIView *)_getKeyboardViewFromWindow:(UIWindow *)window { /* iOS 6/7: UITextEffectsWindow UIPeripheralHostView << keyboard iOS 8: UITextEffectsWindow UIInputSetContainerView UIInputSetHostView << keyboard iOS 9: UIRemoteKeyboardWindow UIInputSetContainerView UIInputSetHostView << keyboard */ if (!window) return nil; // Get the window NSString *windowName = NSStringFromClass(window.class); if ([self _systemVersion] < 9) { // UITextEffectsWindow if (windowName.length != 19) return nil; if (![windowName hasPrefix:@"UI"]) return nil; if (![windowName hasSuffix:@"TextEffectsWindow"]) return nil; } else { // UIRemoteKeyboardWindow if (windowName.length != 22) return nil; if (![windowName hasPrefix:@"UI"]) return nil; if (![windowName hasSuffix:@"RemoteKeyboardWindow"]) return nil; } // Get the view if ([self _systemVersion] < 8) { // UIPeripheralHostView for (UIView *view in window.subviews) { NSString *viewName = NSStringFromClass(view.class); if (viewName.length != 20) continue; if (![viewName hasPrefix:@"UI"]) continue; if (![viewName hasSuffix:@"PeripheralHostView"]) continue; return view; } } else { // UIInputSetContainerView for (UIView *view in window.subviews) { NSString *viewName = NSStringFromClass(view.class); if (viewName.length != 23) continue; if (![viewName hasPrefix:@"UI"]) continue; if (![viewName hasSuffix:@"InputSetContainerView"]) continue; // UIInputSetHostView for (UIView *subView in view.subviews) { NSString *subViewName = NSStringFromClass(subView.class); if (subViewName.length != 18) continue; if (![subViewName hasPrefix:@"UI"]) continue; if (![subViewName hasSuffix:@"InputSetHostView"]) continue; return subView; } } } return nil; } - (void)_keyboardFrameWillChangeNotification:(NSNotification *)notif { if (![notif.name isEqualToString:UIKeyboardWillChangeFrameNotification]) return; NSDictionary *info = notif.userInfo; if (!info) return; [self _initFrameObserver]; NSValue *beforeValue = info[UIKeyboardFrameBeginUserInfoKey]; NSValue *afterValue = info[UIKeyboardFrameEndUserInfoKey]; NSNumber *curveNumber = info[UIKeyboardAnimationCurveUserInfoKey]; NSNumber *durationNumber = info[UIKeyboardAnimationDurationUserInfoKey]; CGRect before = beforeValue.CGRectValue; CGRect after = afterValue.CGRectValue; UIViewAnimationCurve curve = curveNumber.integerValue; NSTimeInterval duration = durationNumber.doubleValue; // ignore zero end frame if (after.size.width <= 0 && after.size.height <= 0) return; _notificationFromFrame = before; _notificationToFrame = after; _notificationCurve = curve; _notificationDuration = duration; _hasNotification = YES; _lastIsNotification = YES; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_notifyAllObservers) object:nil]; if (duration == 0) { [self performSelector:@selector(_notifyAllObservers) withObject:nil afterDelay:0 inModes:@[NSRunLoopCommonModes]]; } else { [self _notifyAllObservers]; } } - (void)_keyboardFrameDidChangeNotification:(NSNotification *)notif { if (![notif.name isEqualToString:UIKeyboardDidChangeFrameNotification]) return; NSDictionary *info = notif.userInfo; if (!info) return; [self _initFrameObserver]; NSValue *afterValue = info[UIKeyboardFrameEndUserInfoKey]; CGRect after = afterValue.CGRectValue; // ignore zero end frame if (after.size.width <= 0 && after.size.height <= 0) return; _notificationToFrame = after; _notificationCurve = UIViewAnimationCurveEaseInOut; _notificationDuration = 0; _hasNotification = YES; _lastIsNotification = YES; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_notifyAllObservers) object:nil]; [self performSelector:@selector(_notifyAllObservers) withObject:nil afterDelay:0 inModes:@[NSRunLoopCommonModes]]; } - (void)_keyboardFrameChanged:(UIView *)keyboard { if (keyboard != self.keyboardView) return; UIWindow *window = keyboard.window; if (window) { _observedToFrame = [window convertRect:keyboard.frame toWindow:nil]; } else { _observedToFrame = keyboard.frame; } _hasObservedChange = YES; _lastIsNotification = NO; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_notifyAllObservers) object:nil]; [self performSelector:@selector(_notifyAllObservers) withObject:nil afterDelay:0 inModes:@[NSRunLoopCommonModes]]; } - (void)_notifyAllObservers { UIApplication *app = [UIApplication sharedExtensionApplication]; if (!app) return; UIView *keyboard = self.keyboardView; UIWindow *window = keyboard.window; if (!window) { window = app.keyWindow; } if (!window) { window = app.windows.firstObject; } YYTextKeyboardTransition trans = {0}; // from if (_fromFrame.size.width == 0 && _fromFrame.size.height == 0) { // first notify _fromFrame.size.width = window.bounds.size.width; _fromFrame.size.height = trans.toFrame.size.height; _fromFrame.origin.x = trans.toFrame.origin.x; _fromFrame.origin.y = window.bounds.size.height; } trans.fromFrame = _fromFrame; trans.fromVisible = _fromVisible; // to if (_lastIsNotification || (_hasObservedChange && CGRectEqualToRect(_observedToFrame, _notificationToFrame))) { trans.toFrame = _notificationToFrame; trans.animationDuration = _notificationDuration; trans.animationCurve = _notificationCurve; trans.animationOption = _notificationCurve << 16; // Fix iPad(iOS7) keyboard frame error after rorate device when the keyboard is not docked to bottom. if (((int)[self _systemVersion]) == 7) { UIInterfaceOrientation ori = app.statusBarOrientation; if (_fromOrientation != UIInterfaceOrientationUnknown && _fromOrientation != ori) { switch (ori) { case UIInterfaceOrientationPortrait: { if (CGRectGetMaxY(trans.toFrame) != window.frame.size.height) { trans.toFrame.origin.y -= trans.toFrame.size.height; } } break; case UIInterfaceOrientationPortraitUpsideDown: { if (CGRectGetMinY(trans.toFrame) != 0) { trans.toFrame.origin.y += trans.toFrame.size.height; } } break; case UIInterfaceOrientationLandscapeLeft: { if (CGRectGetMaxX(trans.toFrame) != window.frame.size.width) { trans.toFrame.origin.x -= trans.toFrame.size.width; } } break; case UIInterfaceOrientationLandscapeRight: { if (CGRectGetMinX(trans.toFrame) != 0) { trans.toFrame.origin.x += trans.toFrame.size.width; } } break; default: break; } } } } else { trans.toFrame = _observedToFrame; } if (window && trans.toFrame.size.width > 0 && trans.toFrame.size.height > 0) { CGRect rect = CGRectIntersection(window.bounds, trans.toFrame); if (!CGRectIsNull(rect) && !CGRectIsEmpty(rect)) { trans.toVisible = YES; } } if (!CGRectEqualToRect(trans.toFrame, _fromFrame)) { for (id<YYTextKeyboardObserver> observer in _observers.copy) { if ([observer respondsToSelector:@selector(keyboardChangedWithTransition:)]) { [observer keyboardChangedWithTransition:trans]; } } } _hasNotification = NO; _hasObservedChange = NO; _fromFrame = trans.toFrame; _fromVisible = trans.toVisible; _fromOrientation = app.statusBarOrientation; } - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view { UIApplication *app = [UIApplication sharedExtensionApplication]; if (!app) return CGRectZero; if (CGRectIsNull(rect)) return rect; if (CGRectIsInfinite(rect)) return rect; UIWindow *mainWindow = app.keyWindow; if (!mainWindow) mainWindow = app.windows.firstObject; if (!mainWindow) { // no window ?! if (view) { [view convertRect:rect fromView:nil]; } else { return rect; } } rect = [mainWindow convertRect:rect fromWindow:nil]; if (!view) return [mainWindow convertRect:rect toWindow:nil]; if (view == mainWindow) return rect; UIWindow *toWindow = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window; if (!mainWindow || !toWindow) return [mainWindow convertRect:rect toView:view]; if (mainWindow == toWindow) return [mainWindow convertRect:rect toView:view]; // in different window rect = [mainWindow convertRect:rect toView:mainWindow]; rect = [toWindow convertRect:rect fromWindow:mainWindow]; rect = [view convertRect:rect fromView:toWindow]; return rect; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextKeyboardManager.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
4,007
```objective-c // // YYTextMagnifier.m // YYKit <path_to_url // // Created by ibireme on 15/2/25. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYTextMagnifier.h" #import "YYCGUtilities.h" #define kCaptureDisableFadeTime 0.1 @interface _YYTextMagnifierCaret : YYTextMagnifier { UIImageView *_contentView; UIImageView *_coverView; } @end @implementation _YYTextMagnifierCaret #define kMultiple 1.2 #define kDiameter 113.0 #define kPadding 7.0 #define kSize CGSizeMake(kDiameter + kPadding * 2, kDiameter + kPadding * 2) - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; _contentView = [UIImageView new]; _contentView.frame = CGRectMake(kPadding, kPadding, kDiameter, kDiameter); _contentView.layer.cornerRadius = kDiameter / 2; _contentView.clipsToBounds = YES; [self addSubview:_contentView]; _coverView = [UIImageView new]; _coverView.frame = (CGRect){.origin = CGPointZero, .size = kSize}; _coverView.image = [self.class coverImage]; [self addSubview:_coverView]; return self; } - (instancetype)init { self = [self initWithFrame:CGRectZero]; self.frame = (CGRect){.size = [self sizeThatFits:CGSizeZero]}; return self; } - (YYTextMagnifierType)type { return YYTextMagnifierTypeCaret; } - (CGSize)sizeThatFits:(CGSize)size { return kSize; } - (void)setSnapshot:(UIImage *)snapshot { if (self.captureFadeAnimation) { [_contentView.layer removeAnimationForKey:@"contents"]; CABasicAnimation *animation = [CABasicAnimation animation]; animation.duration = kCaptureDisableFadeTime; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; [_contentView.layer addAnimation:animation forKey:@"contents"]; } _contentView.image = snapshot; } - (UIImage *)snapshot { return _contentView.image; } - (CGSize)snapshotSize { CGFloat length = floor(kDiameter / 1.2); return CGSizeMake(length, length); } - (CGSize)fitSize { return [self sizeThatFits:CGSizeZero]; } + (UIImage *)coverImage { static UIImage *image; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ CGSize size = kSize; CGRect rect = (CGRect) {.size = size, .origin = CGPointZero}; rect = CGRectInset(rect, kPadding, kPadding); UIGraphicsBeginImageContextWithOptions(size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); CGPathRef boxPath = CGPathCreateWithRect(CGRectMake(0, 0, size.width, size.height), NULL); CGPathRef fillPath = CGPathCreateWithEllipseInRect(rect, NULL); CGPathRef strokePath = CGPathCreateWithEllipseInRect(CGRectPixelHalf(rect), NULL); // inner shadow CGContextSaveGState(context); { CGFloat blurRadius = 25; CGSize offset = CGSizeMake(0, 15); CGColorRef shadowColor = [UIColor colorWithWhite:0 alpha:0.16].CGColor; CGColorRef opaqueShadowColor = CGColorCreateCopyWithAlpha(shadowColor, 1.0); CGContextAddPath(context, fillPath); CGContextClip(context); CGContextSetAlpha(context, CGColorGetAlpha(shadowColor)); CGContextBeginTransparencyLayer(context, NULL); { CGContextSetShadowWithColor(context, offset, blurRadius, opaqueShadowColor); CGContextSetBlendMode(context, kCGBlendModeSourceOut); CGContextSetFillColorWithColor(context, opaqueShadowColor); CGContextAddPath(context, fillPath); CGContextFillPath(context); } CGContextEndTransparencyLayer(context); CGColorRelease(opaqueShadowColor); } CGContextRestoreGState(context); // outer shadow CGContextSaveGState(context); { CGContextAddPath(context, boxPath); CGContextAddPath(context, fillPath); CGContextEOClip(context); CGColorRef shadowColor = [UIColor colorWithWhite:0 alpha:0.32].CGColor; CGContextSetShadowWithColor(context, CGSizeMake(0, 1.5), 3, shadowColor); CGContextBeginTransparencyLayer(context, NULL); { CGContextAddPath(context, fillPath); [[UIColor colorWithWhite:0.7 alpha:1.000] setFill]; CGContextFillPath(context); } CGContextEndTransparencyLayer(context); } CGContextRestoreGState(context); // stroke CGContextSaveGState(context); { CGContextAddPath(context, strokePath); [[UIColor colorWithWhite:0.6 alpha:1] setStroke]; CGContextSetLineWidth(context, CGFloatFromPixel(1)); CGContextStrokePath(context); } CGContextRestoreGState(context); CFRelease(boxPath); CFRelease(fillPath); CFRelease(strokePath); image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }); return image; } #undef kMultiple #undef kDiameter #undef kPadding #undef kSize @end @interface _YYTextMagnifierRanged : YYTextMagnifier { UIImageView *_contentView; UIImageView *_coverView; } @end @implementation _YYTextMagnifierRanged #define kMultiple 1.2 #define kSize CGSizeMake(141, 60) #define kPadding CGFloatPixelHalf(6.0) #define kRadius 6.0 #define kHeight 32.0 #define kArrow 14.0 - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; _contentView = [UIImageView new]; _contentView.frame = CGRectMake(kPadding, kPadding, kSize.width - 2 * kPadding, kHeight); _contentView.layer.cornerRadius = kRadius; _contentView.clipsToBounds = YES; [self addSubview:_contentView]; _coverView = [UIImageView new]; _coverView.frame = (CGRect){.origin = CGPointZero, .size = kSize}; _coverView.image = [self.class coverImage]; [self addSubview:_coverView]; self.layer.anchorPoint = CGPointMake(0.5, 1.2); return self; } - (instancetype)init { self = [self initWithFrame:CGRectZero]; self.frame = (CGRect){.size = [self sizeThatFits:CGSizeZero]}; return self; } - (YYTextMagnifierType)type { return YYTextMagnifierTypeRanged; } - (CGSize)sizeThatFits:(CGSize)size { return kSize; } - (void)setSnapshot:(UIImage *)snapshot { if (self.captureFadeAnimation) { [_contentView.layer removeAnimationForKey:@"contents"]; CABasicAnimation *animation = [CABasicAnimation animation]; animation.duration = kCaptureDisableFadeTime; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; [_contentView.layer addAnimation:animation forKey:@"contents"]; } _contentView.image = snapshot; } - (UIImage *)snapshot { return _contentView.image; } - (CGSize)snapshotSize { CGSize size; size.width = floor((kSize.width - 2 * kPadding) / kMultiple); size.height = floor(kHeight / kMultiple); return size; } - (CGSize)fitSize { return [self sizeThatFits:CGSizeZero]; } + (UIImage *)coverImage { static UIImage *image; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ CGSize size = kSize; CGRect rect = (CGRect) {.size = size, .origin = CGPointZero}; UIGraphicsBeginImageContextWithOptions(size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); CGPathRef boxPath = CGPathCreateWithRect(rect, NULL); CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, kPadding + kRadius, kPadding); CGPathAddLineToPoint(path, NULL, size.width - kPadding - kRadius, kPadding); CGPathAddQuadCurveToPoint(path, NULL, size.width - kPadding, kPadding, size.width - kPadding, kPadding + kRadius); CGPathAddLineToPoint(path, NULL, size.width - kPadding, kHeight); CGPathAddCurveToPoint(path, NULL, size.width - kPadding, kPadding + kHeight, size.width - kPadding - kRadius, kPadding + kHeight, size.width - kPadding - kRadius, kPadding + kHeight); CGPathAddLineToPoint(path, NULL, size.width / 2 + kArrow, kPadding + kHeight); CGPathAddLineToPoint(path, NULL, size.width / 2, kPadding + kHeight + kArrow); CGPathAddLineToPoint(path, NULL, size.width / 2 - kArrow, kPadding + kHeight); CGPathAddLineToPoint(path, NULL, kPadding + kRadius, kPadding + kHeight); CGPathAddQuadCurveToPoint(path, NULL, kPadding, kPadding + kHeight, kPadding, kHeight); CGPathAddLineToPoint(path, NULL, kPadding, kPadding + kRadius); CGPathAddQuadCurveToPoint(path, NULL, kPadding, kPadding, kPadding + kRadius, kPadding); CGPathCloseSubpath(path); CGMutablePathRef arrowPath = CGPathCreateMutable(); CGPathMoveToPoint(arrowPath, NULL, size.width / 2 - kArrow, CGFloatPixelFloor(kPadding) + kHeight); CGPathAddLineToPoint(arrowPath, NULL, size.width / 2 + kArrow, CGFloatPixelFloor(kPadding) + kHeight); CGPathAddLineToPoint(arrowPath, NULL, size.width / 2, kPadding + kHeight + kArrow); CGPathCloseSubpath(arrowPath); // inner shadow CGContextSaveGState(context); { CGFloat blurRadius = 25; CGSize offset = CGSizeMake(0, 15); CGColorRef shadowColor = [UIColor colorWithWhite:0 alpha:0.16].CGColor; CGColorRef opaqueShadowColor = CGColorCreateCopyWithAlpha(shadowColor, 1.0); CGContextAddPath(context, path); CGContextClip(context); CGContextSetAlpha(context, CGColorGetAlpha(shadowColor)); CGContextBeginTransparencyLayer(context, NULL); { CGContextSetShadowWithColor(context, offset, blurRadius, opaqueShadowColor); CGContextSetBlendMode(context, kCGBlendModeSourceOut); CGContextSetFillColorWithColor(context, opaqueShadowColor); CGContextAddPath(context, path); CGContextFillPath(context); } CGContextEndTransparencyLayer(context); CGColorRelease(opaqueShadowColor); } CGContextRestoreGState(context); // outer shadow CGContextSaveGState(context); { CGContextAddPath(context, boxPath); CGContextAddPath(context, path); CGContextEOClip(context); CGColorRef shadowColor = [UIColor colorWithWhite:0 alpha:0.32].CGColor; CGContextSetShadowWithColor(context, CGSizeMake(0, 1.5), 3, shadowColor); CGContextBeginTransparencyLayer(context, NULL); { CGContextAddPath(context, path); [[UIColor colorWithWhite:0.7 alpha:1.000] setFill]; CGContextFillPath(context); } CGContextEndTransparencyLayer(context); } CGContextRestoreGState(context); // arrow CGContextSaveGState(context); { CGContextAddPath(context, arrowPath); [[UIColor colorWithWhite:1 alpha:0.95] set]; CGContextFillPath(context); } CGContextRestoreGState(context); // stroke CGContextSaveGState(context); { CGContextAddPath(context, path); [[UIColor colorWithWhite:0.6 alpha:1] setStroke]; CGContextSetLineWidth(context, CGFloatFromPixel(1)); CGContextStrokePath(context); } CGContextRestoreGState(context); CFRelease(boxPath); CFRelease(path); CFRelease(arrowPath); image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }); return image; } #undef kMultiple #undef kSize #undef kPadding #undef kRadius #undef kHeight #undef kArrow @end @implementation YYTextMagnifier + (id)magnifierWithType:(YYTextMagnifierType)type { switch (type) { case YYTextMagnifierTypeCaret :return [_YYTextMagnifierCaret new]; case YYTextMagnifierTypeRanged :return [_YYTextMagnifierRanged new]; } return nil; } - (id)initWithFrame:(CGRect)frame { // class cluster if ([self isMemberOfClass:[YYTextMagnifier class]]) { @throw [NSException exceptionWithName:NSStringFromClass([self class]) reason:@"Attempting to instantiate an abstract class. Use a concrete subclass instead." userInfo:nil]; return nil; } self = [super initWithFrame:frame]; return self; } @end ```
/content/code_sandbox/WeChat/ThirdLib/YYKit/Text/Component/YYTextMagnifier.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,892
```objective-c // // MBProgressHUD+Show.m // weibo // // Created by apple on 13-9-1. // #import "MBProgressHUD+Show.h" @implementation MBProgressHUD (Show) + (void)showText:(NSString *)text name:(NSString *)name { // MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES]; // (modecustomView) hud.mode = MBProgressHUDModeCustomView; // name = [NSString stringWithFormat:@"MBProgressHUD.bundle/%@", name]; hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]]; hud.labelText = text; // hud.removeFromSuperViewOnHide = YES; // 1 [hud hide:YES afterDelay:1]; } + (void)showErrorWithText:(NSString *)text { [self showText:text name:@"error.png"]; } + (void)showSuccessWithText:(NSString *)text { [self showText:text name:@"success.png"]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MBprogressHUD/MBProgressHUD+Show.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
226
```objective-c // // MBProgressHUD+Show.h // weibo // // Created by apple on 13-9-1. // #import "MBProgressHUD.h" @interface MBProgressHUD (Show) + (void)showErrorWithText:(NSString *)text; + (void)showSuccessWithText:(NSString *)text; @end ```
/content/code_sandbox/WeChat/ThirdLib/MBprogressHUD/MBProgressHUD+Show.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
69
```objective-c // // MBProgressHUD.m // Version 0.7 // Created by Matej Bukovinski on 2.4.09. // #import "MBProgressHUD.h" #if __has_feature(objc_arc) #define MB_AUTORELEASE(exp) exp #define MB_RELEASE(exp) exp #define MB_RETAIN(exp) exp #else #define MB_AUTORELEASE(exp) [exp autorelease] #define MB_RELEASE(exp) [exp release] #define MB_RETAIN(exp) [exp retain] #endif #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 #define MBLabelAlignmentCenter NSTextAlignmentCenter #else #define MBLabelAlignmentCenter UITextAlignmentCenter #endif static const CGFloat kPadding = 4.f; static const CGFloat kLabelFontSize = 14.f; static const CGFloat kDetailsLabelFontSize = 12.f; @interface MBProgressHUD () - (void)setupLabels; - (void)registerForKVO; - (void)unregisterFromKVO; - (NSArray *)observableKeypaths; - (void)registerForNotifications; - (void)unregisterFromNotifications; - (void)updateUIForKeypath:(NSString *)keyPath; - (void)hideUsingAnimation:(BOOL)animated; - (void)showUsingAnimation:(BOOL)animated; - (void)done; - (void)updateIndicators; - (void)handleGraceTimer:(NSTimer *)theTimer; - (void)handleMinShowTimer:(NSTimer *)theTimer; - (void)setTransformForCurrentOrientation:(BOOL)animated; - (void)cleanUp; - (void)launchExecution; - (void)deviceOrientationDidChange:(NSNotification *)notification; - (void)hideDelayed:(NSNumber *)animated; @property (atomic, MB_STRONG) UIView *indicator; @property (atomic, MB_STRONG) NSTimer *graceTimer; @property (atomic, MB_STRONG) NSTimer *minShowTimer; @property (atomic, MB_STRONG) NSDate *showStarted; @property (atomic, assign) CGSize size; @end @implementation MBProgressHUD { BOOL useAnimation; SEL methodForExecution; id targetForExecution; id objectForExecution; UILabel *label; UILabel *detailsLabel; BOOL isFinished; CGAffineTransform rotationTransform; } #pragma mark - Properties @synthesize animationType; @synthesize delegate; @synthesize opacity; @synthesize color; @synthesize labelFont; @synthesize detailsLabelFont; @synthesize indicator; @synthesize xOffset; @synthesize yOffset; @synthesize minSize; @synthesize square; @synthesize margin; @synthesize dimBackground; @synthesize graceTime; @synthesize minShowTime; @synthesize graceTimer; @synthesize minShowTimer; @synthesize taskInProgress; @synthesize removeFromSuperViewOnHide; @synthesize customView; @synthesize showStarted; @synthesize mode; @synthesize labelText; @synthesize detailsLabelText; @synthesize progresses; @synthesize size; #if NS_BLOCKS_AVAILABLE @synthesize completionBlock; #endif #pragma mark - Class methods + (MB_INSTANCETYPE)showHUDAddedTo:(UIView *)view animated:(BOOL)animated { MBProgressHUD *hud = [[self alloc] initWithView:view]; // hud.alpha=.4; [view addSubview:hud]; //[view bringSubviewToFront:hud]; [hud show:animated]; return MB_AUTORELEASE(hud); } + (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated { MBProgressHUD *hud = [self HUDForView:view]; if (hud != nil) { hud.removeFromSuperViewOnHide = YES; [hud hide:animated]; return YES; } return NO; } + (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated { NSArray *huds = [MBProgressHUD allHUDsForView:view]; for (MBProgressHUD *hud in huds) { hud.removeFromSuperViewOnHide = YES; [hud hide:animated]; } return [huds count]; } + (MB_INSTANCETYPE)HUDForView:(UIView *)view { NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator]; for (UIView *subview in subviewsEnum) { if ([subview isKindOfClass:self]) { return (MBProgressHUD *)subview; } } return nil; } + (NSArray *)allHUDsForView:(UIView *)view { NSMutableArray *huds = [NSMutableArray array]; NSArray *subviews = view.subviews; for (UIView *aView in subviews) { if ([aView isKindOfClass:self]) { [huds addObject:aView]; } } return [NSArray arrayWithArray:huds]; } #pragma mark - Lifecycle - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Set default values for properties self.animationType = MBProgressHUDAnimationFade; self.mode = MBProgressHUDModeIndeterminate; self.labelText = nil; self.detailsLabelText = nil; self.opacity = 0.8f; self.color = nil; self.labelFont = [UIFont boldSystemFontOfSize:kLabelFontSize]; self.detailsLabelFont = [UIFont boldSystemFontOfSize:kDetailsLabelFontSize]; self.xOffset = 0.0f; self.yOffset = 0.0f; self.dimBackground = NO; self.margin = 20.0f; self.graceTime = 0.0f; self.minShowTime = 0.0f; self.removeFromSuperViewOnHide = NO; self.minSize = CGSizeZero; self.square = NO; self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin; // Transparent background self.opaque = NO; self.backgroundColor = [UIColor clearColor]; // Make it invisible for now self.alpha = 0.0f; taskInProgress = NO; rotationTransform = CGAffineTransformIdentity; [self setupLabels]; [self updateIndicators]; [self registerForKVO]; [self registerForNotifications]; } return self; } - (id)initWithView:(UIView *)view { NSAssert(view, @"View must not be nil."); //return [self initWithFrame:view.bounds]; return [self initWithFrame:CGRectMake((view.bounds.size.width-200)/2, (view.bounds.size.height-80)/2, 200, 80)]; } - (id)initWithWindow:(UIWindow *)window { return [self initWithView:window]; } - (void)dealloc { [self unregisterFromNotifications]; [self unregisterFromKVO]; #if !__has_feature(objc_arc) [color release]; [indicator release]; [label release]; [detailsLabel release]; [labelText release]; [detailsLabelText release]; [graceTimer release]; [minShowTimer release]; [showStarted release]; [customView release]; #if NS_BLOCKS_AVAILABLE [completionBlock release]; #endif [super dealloc]; #endif } #pragma mark - Show & hide - (void)show:(BOOL)animated { useAnimation = animated; // If the grace time is set postpone the HUD display if (self.graceTime > 0.0) { self.graceTimer = [NSTimer scheduledTimerWithTimeInterval:self.graceTime target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO]; } // ... otherwise show the HUD imediately else { [self setNeedsDisplay]; [self showUsingAnimation:useAnimation]; } } - (void)hide:(BOOL)animated { useAnimation = animated; // If the minShow time is set, calculate how long the hud was shown, // and pospone the hiding operation if necessary if (self.minShowTime > 0.0 && showStarted) { NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:showStarted]; if (interv < self.minShowTime) { self.minShowTimer = [NSTimer scheduledTimerWithTimeInterval:(self.minShowTime - interv) target:self selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO]; return; } } // ... otherwise hide the HUD immediately [self hideUsingAnimation:useAnimation]; } - (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay { [self performSelector:@selector(hideDelayed:) withObject:[NSNumber numberWithBool:animated] afterDelay:delay]; } - (void)hideDelayed:(NSNumber *)animated { [self hide:[animated boolValue]]; } #pragma mark - Timer callbacks - (void)handleGraceTimer:(NSTimer *)theTimer { // Show the HUD only if the task is still running if (taskInProgress) { [self setNeedsDisplay]; [self showUsingAnimation:useAnimation]; } } - (void)handleMinShowTimer:(NSTimer *)theTimer { [self hideUsingAnimation:useAnimation]; } #pragma mark - View Hierrarchy - (void)didMoveToSuperview { // We need to take care of rotation ourselfs if we're adding the HUD to a window if ([self.superview isKindOfClass:[UIWindow class]]) { [self setTransformForCurrentOrientation:NO]; } } #pragma mark - Internal show & hide operations - (void)showUsingAnimation:(BOOL)animated { if (animated && animationType == MBProgressHUDAnimationZoomIn) { self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f)); } else if (animated && animationType == MBProgressHUDAnimationZoomOut) { self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f)); } self.showStarted = [NSDate date]; // Fade in if (animated) { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.30]; self.alpha = 1.0f; if (animationType == MBProgressHUDAnimationZoomIn || animationType == MBProgressHUDAnimationZoomOut) { self.transform = rotationTransform; } [UIView commitAnimations]; } else { self.alpha = 1.0f; } } - (void)hideUsingAnimation:(BOOL)animated { // Fade out if (animated && showStarted) { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.30]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)]; // 0.02 prevents the hud from passing through touches during the animation the hud will get completely hidden // in the done method if (animationType == MBProgressHUDAnimationZoomIn) { self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f)); } else if (animationType == MBProgressHUDAnimationZoomOut) { self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f)); } self.alpha = 0.02f; [UIView commitAnimations]; } else { self.alpha = 0.0f; [self done]; } self.showStarted = nil; } - (void)animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void*)context { [self done]; } - (void)done { isFinished = YES; self.alpha = 0.0f; if ([delegate respondsToSelector:@selector(hudWasHidden:)]) { [delegate performSelector:@selector(hudWasHidden:) withObject:self]; } #if NS_BLOCKS_AVAILABLE if (self.completionBlock) { self.completionBlock(); self.completionBlock = NULL; } #endif if (removeFromSuperViewOnHide) { [self removeFromSuperview]; } } #pragma mark - Threading - (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated { methodForExecution = method; targetForExecution = MB_RETAIN(target); objectForExecution = MB_RETAIN(object); // Launch execution in new thread self.taskInProgress = YES; [NSThread detachNewThreadSelector:@selector(launchExecution) toTarget:self withObject:nil]; // Show HUD view [self show:animated]; } #if NS_BLOCKS_AVAILABLE - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL]; } - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(void (^)())completion { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:completion]; } - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue { [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL]; } - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue completionBlock:(MBProgressHUDCompletionBlock)completion { self.taskInProgress = YES; self.completionBlock = completion; dispatch_async(queue, ^(void) { block(); dispatch_async(dispatch_get_main_queue(), ^(void) { [self cleanUp]; }); }); [self show:animated]; } #endif - (void)launchExecution { @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" // Start executing the requested task [targetForExecution performSelector:methodForExecution withObject:objectForExecution]; #pragma clang diagnostic pop // Task completed, update view in main thread (note: view operations should // be done only in the main thread) [self performSelectorOnMainThread:@selector(cleanUp) withObject:nil waitUntilDone:NO]; } } - (void)cleanUp { taskInProgress = NO; self.indicator = nil; #if !__has_feature(objc_arc) [targetForExecution release]; [objectForExecution release]; #else targetForExecution = nil; objectForExecution = nil; #endif [self hide:useAnimation]; } #pragma mark - UI - (void)setupLabels { label = [[UILabel alloc] initWithFrame:self.bounds]; label.adjustsFontSizeToFitWidth = NO; label.textAlignment = MBLabelAlignmentCenter; label.opaque = NO; label.backgroundColor = [UIColor clearColor]; label.textColor = [UIColor whiteColor]; label.font = self.labelFont; label.text = self.labelText; [self addSubview:label]; detailsLabel = [[UILabel alloc] initWithFrame:self.bounds]; detailsLabel.font = self.detailsLabelFont; detailsLabel.adjustsFontSizeToFitWidth = NO; detailsLabel.textAlignment = MBLabelAlignmentCenter; detailsLabel.opaque = NO; detailsLabel.backgroundColor = [UIColor clearColor]; detailsLabel.textColor = [UIColor whiteColor]; detailsLabel.numberOfLines = 0; detailsLabel.font = self.detailsLabelFont; detailsLabel.text = self.detailsLabelText; [self addSubview:detailsLabel]; } - (void)updateIndicators { BOOL isActivityIndicator = [indicator isKindOfClass:[UIActivityIndicatorView class]]; BOOL isRoundIndicator = [indicator isKindOfClass:[MBRoundProgressView class]]; if (mode == MBProgressHUDModeIndeterminate && !isActivityIndicator) { // Update to indeterminate indicator [indicator removeFromSuperview]; self.indicator = MB_AUTORELEASE([[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]); [(UIActivityIndicatorView *)indicator startAnimating]; [self addSubview:indicator]; } else if (mode == MBProgressHUDModeDeterminateHorizontalBar) { // Update to bar determinate indicator [indicator removeFromSuperview]; self.indicator = MB_AUTORELEASE([[MBBarProgressView alloc] init]); [self addSubview:indicator]; } else if (mode == MBProgressHUDModeDeterminate || mode == MBProgressHUDModeAnnularDeterminate) { if (!isRoundIndicator) { // Update to determinante indicator [indicator removeFromSuperview]; self.indicator = MB_AUTORELEASE([[MBRoundProgressView alloc] init]); [self addSubview:indicator]; } if (mode == MBProgressHUDModeAnnularDeterminate) { [(MBRoundProgressView *)indicator setAnnular:YES]; } } else if (mode == MBProgressHUDModeCustomView && customView != indicator) { // Update custom view indicator [indicator removeFromSuperview]; self.indicator = customView; [self addSubview:indicator]; } else if (mode == MBProgressHUDModeText) { [indicator removeFromSuperview]; self.indicator = nil; } } #pragma mark - Layout - (void)layoutSubviews { // Entirely cover the parent view UIView *parent = self.superview; if (parent) { self.frame = parent.bounds; } CGRect bounds = self.bounds; // Determine the total widt and height needed CGFloat maxWidth = bounds.size.width - 4 * margin; CGSize totalSize = CGSizeZero; CGRect indicatorF = indicator.bounds; indicatorF.size.width = MIN(indicatorF.size.width, maxWidth); totalSize.width = MAX(totalSize.width, indicatorF.size.width); totalSize.height += indicatorF.size.height; //CGSize labelSize = [label.text sizeWithFont:label.font]; CGSize labelSize=[label.text sizeWithAttributes:@{NSFontAttributeName: label.font}]; labelSize.width = MIN(labelSize.width, maxWidth); totalSize.width = MAX(totalSize.width, labelSize.width); totalSize.height += labelSize.height; if (labelSize.height > 0.f && indicatorF.size.height > 0.f) { totalSize.height += kPadding; } CGFloat remainingHeight = bounds.size.height - totalSize.height - kPadding - 4 * margin; CGSize maxSize = CGSizeMake(maxWidth, remainingHeight); // CGSize detailsLabelSize = [detailsLabel.text sizeWithFont:detailsLabel.font // constrainedToSize:maxSize lineBreakMode:detailsLabel.lineBreakMode]; CGSize detailsLabelSize=[detailsLabel.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: detailsLabel.font} context:nil].size; totalSize.width = MAX(totalSize.width, detailsLabelSize.width); totalSize.height += detailsLabelSize.height; if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) { totalSize.height += kPadding; } totalSize.width += 2 * margin; totalSize.height += 2 * margin; // Position elements CGFloat yPos = roundf(((bounds.size.height - totalSize.height) / 2)) + margin + yOffset; CGFloat xPos = xOffset; indicatorF.origin.y = yPos; indicatorF.origin.x = roundf((bounds.size.width - indicatorF.size.width) / 2) + xPos; indicator.frame = indicatorF; yPos += indicatorF.size.height; if (labelSize.height > 0.f && indicatorF.size.height > 0.f) { yPos += kPadding; } CGRect labelF; labelF.origin.y = yPos; labelF.origin.x = roundf((bounds.size.width - labelSize.width) / 2) + xPos; labelF.size = labelSize; label.frame = labelF; yPos += labelF.size.height; if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) { yPos += kPadding; } CGRect detailsLabelF; detailsLabelF.origin.y = yPos; detailsLabelF.origin.x = roundf((bounds.size.width - detailsLabelSize.width) / 2) + xPos; detailsLabelF.size = detailsLabelSize; detailsLabel.frame = detailsLabelF; // Enforce minsize and quare rules if (square) { CGFloat max = MAX(totalSize.width, totalSize.height); if (max <= bounds.size.width - 2 * margin) { totalSize.width = max; } if (max <= bounds.size.height - 2 * margin) { totalSize.height = max; } } if (totalSize.width < minSize.width) { totalSize.width = minSize.width; } if (totalSize.height < minSize.height) { totalSize.height = minSize.height; } self.size = totalSize; } #pragma mark BG Drawing - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); UIGraphicsPushContext(context); if (self.dimBackground) { //Gradient colours size_t gradLocationsNum = 2; CGFloat gradLocations[2] = {0.0f, 1.0f}; CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.75f}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum); CGColorSpaceRelease(colorSpace); //Gradient center CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); //Gradient radius float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ; //Gradient draw CGContextDrawRadialGradient (context, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation); CGGradientRelease(gradient); } // Set background rect color if (self.color) { CGContextSetFillColorWithColor(context, self.color.CGColor); } else { CGContextSetGrayFillColor(context, 0.0f, self.opacity); } // Center HUD CGRect allRect = self.bounds; // Draw rounded HUD backgroud rect CGRect boxRect = CGRectMake(roundf((allRect.size.width - size.width) / 2) + self.xOffset, roundf((allRect.size.height - size.height) / 2) + self.yOffset, size.width, size.height); float radius = 10.0f; CGContextBeginPath(context); CGContextMoveToPoint(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect)); CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMinY(boxRect) + radius, radius, 3 * (float)M_PI / 2, 0, 0); CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMaxY(boxRect) - radius, radius, 0, (float)M_PI / 2, 0); CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMaxY(boxRect) - radius, radius, (float)M_PI / 2, (float)M_PI, 0); CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect) + radius, radius, (float)M_PI, 3 * (float)M_PI / 2, 0); CGContextClosePath(context); CGContextFillPath(context); UIGraphicsPopContext(); } #pragma mark - KVO - (void)registerForKVO { for (NSString *keyPath in [self observableKeypaths]) { [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL]; } } - (void)unregisterFromKVO { for (NSString *keyPath in [self observableKeypaths]) { [self removeObserver:self forKeyPath:keyPath]; } } - (NSArray *)observableKeypaths { return [NSArray arrayWithObjects:@"mode", @"customView", @"labelText", @"labelFont", @"detailsLabelText", @"detailsLabelFont", @"progress", nil]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (![NSThread isMainThread]) { [self performSelectorOnMainThread:@selector(updateUIForKeypath:) withObject:keyPath waitUntilDone:NO]; } else { [self updateUIForKeypath:keyPath]; } } - (void)updateUIForKeypath:(NSString *)keyPath { if ([keyPath isEqualToString:@"mode"] || [keyPath isEqualToString:@"customView"]) { [self updateIndicators]; } else if ([keyPath isEqualToString:@"labelText"]) { label.text = self.labelText; } else if ([keyPath isEqualToString:@"labelFont"]) { label.font = self.labelFont; } else if ([keyPath isEqualToString:@"detailsLabelText"]) { detailsLabel.text = self.detailsLabelText; } else if ([keyPath isEqualToString:@"detailsLabelFont"]) { detailsLabel.font = self.detailsLabelFont; } else if ([keyPath isEqualToString:@"progresses"]) { if ([indicator respondsToSelector:@selector(setProgresses:)]) { [(id)indicator setProgresses:progresses]; } return; } [self setNeedsLayout]; [self setNeedsDisplay]; } #pragma mark - Notifications - (void)registerForNotifications { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil]; } - (void)unregisterFromNotifications { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)deviceOrientationDidChange:(NSNotification *)notification { UIView *superview = self.superview; if (!superview) { return; } else if ([superview isKindOfClass:[UIWindow class]]) { [self setTransformForCurrentOrientation:YES]; } else { self.bounds = self.superview.bounds; [self setNeedsDisplay]; } } - (void)setTransformForCurrentOrientation:(BOOL)animated { // Stay in sync with the superview if (self.superview) { self.bounds = self.superview.bounds; [self setNeedsDisplay]; } UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; CGFloat radians = 0; if (UIInterfaceOrientationIsLandscape(orientation)) { if (orientation == UIInterfaceOrientationLandscapeLeft) { radians = -(CGFloat)M_PI_2; } else { radians = (CGFloat)M_PI_2; } // Window coordinates differ! self.bounds = CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.width); } else { if (orientation == UIInterfaceOrientationPortraitUpsideDown) { radians = (CGFloat)M_PI; } else { radians = 0; } } rotationTransform = CGAffineTransformMakeRotation(radians); if (animated) { [UIView beginAnimations:nil context:nil]; } [self setTransform:rotationTransform]; if (animated) { [UIView commitAnimations]; } } @end @implementation MBRoundProgressView #pragma mark - Lifecycle - (id)init { return [self initWithFrame:CGRectMake(0.f, 0.f, 37.f, 37.f)]; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; self.opaque = NO; _progress = 0.f; _annular = NO; _progressTintColor = [[UIColor alloc] initWithWhite:1.f alpha:1.f]; _backgroundTintColor = [[UIColor alloc] initWithWhite:1.f alpha:.1f]; [self registerForKVO]; } return self; } - (void)dealloc { [self unregisterFromKVO]; #if !__has_feature(objc_arc) [_progressTintColor release]; [_backgroundTintColor release]; [super dealloc]; #endif } #pragma mark - Drawing - (void)drawRect:(CGRect)rect { CGRect allRect = self.bounds; CGRect circleRect = CGRectInset(allRect, 2.0f, 2.0f); CGContextRef context = UIGraphicsGetCurrentContext(); if (_annular) { // Draw background CGFloat lineWidth = 5.f; UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath]; processBackgroundPath.lineWidth = lineWidth; processBackgroundPath.lineCapStyle = kCGLineCapRound; CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); CGFloat radius = (self.bounds.size.width - lineWidth)/2; CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees CGFloat endAngle = (2 * (float)M_PI) + startAngle; [processBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; [_backgroundTintColor set]; [processBackgroundPath stroke]; // Draw progress UIBezierPath *processPath = [UIBezierPath bezierPath]; processPath.lineCapStyle = kCGLineCapRound; processPath.lineWidth = lineWidth; endAngle = (self.progress * 2 * (float)M_PI) + startAngle; [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; [_progressTintColor set]; [processPath stroke]; } else { // Draw background [_progressTintColor setStroke]; [_backgroundTintColor setFill]; CGContextSetLineWidth(context, 2.0f); CGContextFillEllipseInRect(context, circleRect); CGContextStrokeEllipseInRect(context, circleRect); // Draw progress CGPoint center = CGPointMake(allRect.size.width / 2, allRect.size.height / 2); CGFloat radius = (allRect.size.width - 4) / 2; CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees CGFloat endAngle = (self.progress * 2 * (float)M_PI) + startAngle; CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1.0f); // white CGContextMoveToPoint(context, center.x, center.y); CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0); CGContextClosePath(context); CGContextFillPath(context); } } #pragma mark - KVO - (void)registerForKVO { for (NSString *keyPath in [self observableKeypaths]) { [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL]; } } - (void)unregisterFromKVO { for (NSString *keyPath in [self observableKeypaths]) { [self removeObserver:self forKeyPath:keyPath]; } } - (NSArray *)observableKeypaths { return [NSArray arrayWithObjects:@"progressTintColor", @"backgroundTintColor", @"progress", @"annular", nil]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { [self setNeedsDisplay]; } @end @implementation MBBarProgressView #pragma mark - Lifecycle - (id)init { return [self initWithFrame:CGRectMake(.0f, .0f, 120.0f, 20.0f)]; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _progress = 0.f; _lineColor = [UIColor whiteColor]; _progressColor = [UIColor whiteColor]; _progressRemainingColor = [UIColor clearColor]; self.backgroundColor = [UIColor clearColor]; self.opaque = NO; [self registerForKVO]; } return self; } - (void)dealloc { [self unregisterFromKVO]; #if !__has_feature(objc_arc) [_lineColor release]; [_progressColor release]; [_progressRemainingColor release]; [super dealloc]; #endif } #pragma mark - Drawing - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); // setup properties CGContextSetLineWidth(context, 2); CGContextSetStrokeColorWithColor(context,[_lineColor CGColor]); CGContextSetFillColorWithColor(context, [_progressRemainingColor CGColor]); // draw line border float radius = (rect.size.height / 2) - 2; CGContextMoveToPoint(context, 2, rect.size.height/2); CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); CGContextAddLineToPoint(context, rect.size.width - radius - 2, 2); CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); CGContextAddLineToPoint(context, radius + 2, rect.size.height - 2); CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); CGContextFillPath(context); // draw progress background CGContextMoveToPoint(context, 2, rect.size.height/2); CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); CGContextAddLineToPoint(context, rect.size.width - radius - 2, 2); CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); CGContextAddLineToPoint(context, radius + 2, rect.size.height - 2); CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); CGContextStrokePath(context); // setup to draw progress color CGContextSetFillColorWithColor(context, [_progressColor CGColor]); radius = radius - 2; float amount = self.progress * rect.size.width; // if progress is in the middle area if (amount >= radius + 4 && amount <= (rect.size.width - radius - 4)) { // top CGContextMoveToPoint(context, 4, rect.size.height/2); CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); CGContextAddLineToPoint(context, amount, 4); CGContextAddLineToPoint(context, amount, radius + 4); // bottom CGContextMoveToPoint(context, 4, rect.size.height/2); CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); CGContextAddLineToPoint(context, amount, rect.size.height - 4); CGContextAddLineToPoint(context, amount, radius + 4); CGContextFillPath(context); } // progress is in the right arc else if (amount > radius + 4) { float x = amount - (rect.size.width - radius - 4); // top CGContextMoveToPoint(context, 4, rect.size.height/2); CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); CGContextAddLineToPoint(context, rect.size.width - radius - 4, 4); float angle = -acos(x/radius); if (isnan(angle)) angle = 0; CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, M_PI, angle, 0); CGContextAddLineToPoint(context, amount, rect.size.height/2); // bottom CGContextMoveToPoint(context, 4, rect.size.height/2); CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); CGContextAddLineToPoint(context, rect.size.width - radius - 4, rect.size.height - 4); angle = acos(x/radius); if (isnan(angle)) angle = 0; CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, -M_PI, angle, 1); CGContextAddLineToPoint(context, amount, rect.size.height/2); CGContextFillPath(context); } // progress is in the left arc else if (amount < radius + 4 && amount > 0) { // top CGContextMoveToPoint(context, 4, rect.size.height/2); CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); // bottom CGContextMoveToPoint(context, 4, rect.size.height/2); CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); CGContextFillPath(context); } } #pragma mark - KVO - (void)registerForKVO { for (NSString *keyPath in [self observableKeypaths]) { [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL]; } } - (void)unregisterFromKVO { for (NSString *keyPath in [self observableKeypaths]) { [self removeObserver:self forKeyPath:keyPath]; } } - (NSArray *)observableKeypaths { return [NSArray arrayWithObjects:@"lineColor", @"progressRemainingColor", @"progressColor", @"progress", nil]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { [self setNeedsDisplay]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MBprogressHUD/MBProgressHUD.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
8,299
```objective-c // // MBProgressHUD.h // Version 0.7 // Created by Matej Bukovinski on 2.4.09. // // This code is distributed under the terms and conditions of the MIT license. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <CoreGraphics/CoreGraphics.h> @protocol MBProgressHUDDelegate; typedef enum { /** Progress is shown using an UIActivityIndicatorView. This is the default. */ MBProgressHUDModeIndeterminate, /** Progress is shown using a round, pie-chart like, progress view. */ MBProgressHUDModeDeterminate, /** Progress is shown using a horizontal progress bar */ MBProgressHUDModeDeterminateHorizontalBar, /** Progress is shown using a ring-shaped progress view. */ MBProgressHUDModeAnnularDeterminate, /** Shows a custom view */ MBProgressHUDModeCustomView, /** Shows only labels */ MBProgressHUDModeText } MBProgressHUDMode; typedef enum { /** Opacity animation */ MBProgressHUDAnimationFade, /** Opacity + scale animation */ MBProgressHUDAnimationZoom, MBProgressHUDAnimationZoomOut = MBProgressHUDAnimationZoom, MBProgressHUDAnimationZoomIn } MBProgressHUDAnimation; #ifndef MB_INSTANCETYPE #if __has_feature(objc_instancetype) #define MB_INSTANCETYPE instancetype #else #define MB_INSTANCETYPE id #endif #endif #ifndef MB_STRONG #if __has_feature(objc_arc) #define MB_STRONG strong #else #define MB_STRONG retain #endif #endif #ifndef MB_WEAK #if __has_feature(objc_arc_weak) #define MB_WEAK weak #elif __has_feature(objc_arc) #define MB_WEAK unsafe_unretained #else #define MB_WEAK assign #endif #endif #if NS_BLOCKS_AVAILABLE typedef void (^MBProgressHUDCompletionBlock)(); #endif /** * Displays a simple HUD window containing a progress indicator and two optional labels for short messages. * * This is a simple drop-in class for displaying a progress HUD view similar to Apple's private UIProgressHUD class. * The MBProgressHUD window spans over the entire space given to it by the initWithFrame constructor and catches all * user input on this region, thereby preventing the user operations on components below the view. The HUD itself is * drawn centered as a rounded semi-transparent view which resizes depending on the user specified content. * * This view supports four modes of operation: * - MBProgressHUDModeIndeterminate - shows a UIActivityIndicatorView * - MBProgressHUDModeDeterminate - shows a custom round progress indicator * - MBProgressHUDModeAnnularDeterminate - shows a custom annular progress indicator * - MBProgressHUDModeCustomView - shows an arbitrary, user specified view (@see customView) * * All three modes can have optional labels assigned: * - If the labelText property is set and non-empty then a label containing the provided content is placed below the * indicator view. * - If also the detailsLabelText property is set then another label is placed below the first label. */ @interface MBProgressHUD : UIView /** * Creates a new HUD, adds it to provided view and shows it. The counterpart to this method is hideHUDForView:animated:. * * @param view The view that the HUD will be added to * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use * animations while appearing. * @return A reference to the created HUD. * * @see hideHUDForView:animated: * @see animationType */ + (MB_INSTANCETYPE)showHUDAddedTo:(UIView *)view animated:(BOOL)animated; /** * Finds the top-most HUD subview and hides it. The counterpart to this method is showHUDAddedTo:animated:. * * @param view The view that is going to be searched for a HUD subview. * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use * animations while disappearing. * @return YES if a HUD was found and removed, NO otherwise. * * @see showHUDAddedTo:animated: * @see animationType */ + (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated; /** * Finds all the HUD subviews and hides them. * * @param view The view that is going to be searched for HUD subviews. * @param animated If set to YES the HUDs will disappear using the current animationType. If set to NO the HUDs will not use * animations while disappearing. * @return the number of HUDs found and removed. * * @see hideHUDForView:animated: * @see animationType */ + (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated; /** * Finds the top-most HUD subview and returns it. * * @param view The view that is going to be searched. * @return A reference to the last HUD subview discovered. */ + (MB_INSTANCETYPE)HUDForView:(UIView *)view; /** * Finds all HUD subviews and returns them. * * @param view The view that is going to be searched. * @return All found HUD views (array of MBProgressHUD objects). */ + (NSArray *)allHUDsForView:(UIView *)view; /** * A convenience constructor that initializes the HUD with the window's bounds. Calls the designated constructor with * window.bounds as the parameter. * * @param window The window instance that will provide the bounds for the HUD. Should be the same instance as * the HUD's superview (i.e., the window that the HUD will be added to). */ - (id)initWithWindow:(UIWindow *)window; /** * A convenience constructor that initializes the HUD with the view's bounds. Calls the designated constructor with * view.bounds as the parameter * * @param view The view instance that will provide the bounds for the HUD. Should be the same instance as * the HUD's superview (i.e., the view that the HUD will be added to). */ - (id)initWithView:(UIView *)view; /** * Display the HUD. You need to make sure that the main thread completes its run loop soon after this method call so * the user interface can be updated. Call this method when your task is already set-up to be executed in a new thread * (e.g., when using something like NSOperation or calling an asynchronous call like NSURLRequest). * * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use * animations while appearing. * * @see animationType */ - (void)show:(BOOL)animated; /** * Hide the HUD. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to * hide the HUD when your task completes. * * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use * animations while disappearing. * * @see animationType */ - (void)hide:(BOOL)animated; /** * Hide the HUD after a delay. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to * hide the HUD when your task completes. * * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use * animations while disappearing. * @param delay Delay in seconds until the HUD is hidden. * * @see animationType */ - (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay; /** * Shows the HUD while a background task is executing in a new thread, then hides the HUD. * * This method also takes care of autorelease pools so your method does not have to be concerned with setting up a * pool. * * @param method The method to be executed while the HUD is shown. This method will be executed in a new thread. * @param target The object that the target method belongs to. * @param object An optional object to be passed to the method. * @param animated If set to YES the HUD will (dis)appear using the current animationType. If set to NO the HUD will not use * animations while (dis)appearing. */ - (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated; #if NS_BLOCKS_AVAILABLE /** * Shows the HUD while a block is executing on a background queue, then hides the HUD. * * @see showAnimated:whileExecutingBlock:onQueue:completionBlock: */ - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block; /** * Shows the HUD while a block is executing on a background queue, then hides the HUD. * * @see showAnimated:whileExecutingBlock:onQueue:completionBlock: */ - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(MBProgressHUDCompletionBlock)completion; /** * Shows the HUD while a block is executing on the specified dispatch queue, then hides the HUD. * * @see showAnimated:whileExecutingBlock:onQueue:completionBlock: */ - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue; /** * Shows the HUD while a block is executing on the specified dispatch queue, executes completion block on the main queue, and then hides the HUD. * * @param animated If set to YES the HUD will (dis)appear using the current animationType. If set to NO the HUD will * not use animations while (dis)appearing. * @param block The block to be executed while the HUD is shown. * @param queue The dispatch queue on which the block should be executed. * @param completion The block to be executed on completion. * * @see completionBlock */ - (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue completionBlock:(MBProgressHUDCompletionBlock)completion; /** * A block that gets called after the HUD was completely hidden. */ @property (copy) MBProgressHUDCompletionBlock completionBlock; #endif /** * MBProgressHUD operation mode. The default is MBProgressHUDModeIndeterminate. * * @see MBProgressHUDMode */ @property (assign) MBProgressHUDMode mode; /** * The animation type that should be used when the HUD is shown and hidden. * * @see MBProgressHUDAnimation */ @property (assign) MBProgressHUDAnimation animationType; /** * The UIView (e.g., a UIImageView) to be shown when the HUD is in MBProgressHUDModeCustomView. * For best results use a 37 by 37 pixel view (so the bounds match the built in indicator bounds). */ @property (MB_STRONG) UIView *customView; /** * The HUD delegate object. * * @see MBProgressHUDDelegate */ @property (MB_WEAK) id<MBProgressHUDDelegate> delegate; /** * An optional short message to be displayed below the activity indicator. The HUD is automatically resized to fit * the entire text. If the text is too long it will get clipped by displaying "..." at the end. If left unchanged or * set to @"", then no message is displayed. */ @property (copy) NSString *labelText; /** * An optional details message displayed below the labelText message. This message is displayed only if the labelText * property is also set and is different from an empty string (@""). The details text can span multiple lines. */ @property (copy) NSString *detailsLabelText; /** * The opacity of the HUD window. Defaults to 0.8 (80% opacity). */ @property (assign) float opacity; /** * The color of the HUD window. Defaults to black. If this property is set, color is set using * this UIColor and the opacity property is not used. using retain because performing copy on * UIColor base colors (like [UIColor greenColor]) cause problems with the copyZone. */ @property (MB_STRONG) UIColor *color; /** * The x-axis offset of the HUD relative to the centre of the superview. */ @property (assign) float xOffset; /** * The y-axis offset of the HUD relative to the centre of the superview. */ @property (assign) float yOffset; /** * The amount of space between the HUD edge and the HUD elements (labels, indicators or custom views). * Defaults to 20.0 */ @property (assign) float margin; /** * Cover the HUD background view with a radial gradient. */ @property (assign) BOOL dimBackground; /* * Grace period is the time (in seconds) that the invoked method may be run without * showing the HUD. If the task finishes before the grace time runs out, the HUD will * not be shown at all. * This may be used to prevent HUD display for very short tasks. * Defaults to 0 (no grace time). * Grace time functionality is only supported when the task status is known! * @see taskInProgress */ @property (assign) float graceTime; /** * The minimum time (in seconds) that the HUD is shown. * This avoids the problem of the HUD being shown and than instantly hidden. * Defaults to 0 (no minimum show time). */ @property (assign) float minShowTime; /** * Indicates that the executed operation is in progress. Needed for correct graceTime operation. * If you don't set a graceTime (different than 0.0) this does nothing. * This property is automatically set when using showWhileExecuting:onTarget:withObject:animated:. * When threading is done outside of the HUD (i.e., when the show: and hide: methods are used directly), * you need to set this property when your task starts and completes in order to have normal graceTime * functionality. */ @property (assign) BOOL taskInProgress; /** * Removes the HUD from its parent view when hidden. * Defaults to NO. */ @property (assign) BOOL removeFromSuperViewOnHide; /** * Font to be used for the main label. Set this property if the default is not adequate. */ @property (MB_STRONG) UIFont* labelFont; /** * Font to be used for the details label. Set this property if the default is not adequate. */ @property (MB_STRONG) UIFont* detailsLabelFont; /** * The progress of the progress indicator, from 0.0 to 1.0. Defaults to 0.0. */ @property (assign) float progresses; /** * The minimum size of the HUD bezel. Defaults to CGSizeZero (no minimum size). */ @property (assign) CGSize minSize; /** * Force the HUD dimensions to be equal if possible. */ @property (assign, getter = isSquare) BOOL square; @end @protocol MBProgressHUDDelegate <NSObject> @optional /** * Called after the HUD was fully hidden from the screen. */ - (void)hudWasHidden:(MBProgressHUD *)hud; @end /** * A progress view for showing definite progress by filling up a circle (pie chart). */ @interface MBRoundProgressView : UIView /** * Progress (0.0 to 1.0) */ @property (nonatomic, assign) float progress; /** * Indicator progress color. * Defaults to white [UIColor whiteColor] */ @property (nonatomic, MB_STRONG) UIColor *progressTintColor; /** * Indicator background (non-progress) color. * Defaults to translucent white (alpha 0.1) */ @property (nonatomic, MB_STRONG) UIColor *backgroundTintColor; /* * Display mode - NO = round or YES = annular. Defaults to round. */ @property (nonatomic, assign, getter = isAnnular) BOOL annular; @end /** * A flat bar progress view. */ @interface MBBarProgressView : UIView /** * Progress (0.0 to 1.0) */ @property (nonatomic, assign) float progress; /** * Bar border line color. * Defaults to white [UIColor whiteColor]. */ @property (nonatomic, MB_STRONG) UIColor *lineColor; /** * Bar background color. * Defaults to clear [UIColor clearColor]; */ @property (nonatomic, MB_STRONG) UIColor *progressRemainingColor; /** * Bar progress color. * Defaults to white [UIColor whiteColor]. */ @property (nonatomic, MB_STRONG) UIColor *progressColor; @end ```
/content/code_sandbox/WeChat/ThirdLib/MBprogressHUD/MBProgressHUD.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
3,668