FLEXUtility.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. //
  2. // FLEXUtility.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 4/18/14.
  6. // Copyright (c) 2014 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXColor.h"
  9. #import "FLEXUtility.h"
  10. #import "FLEXResources.h"
  11. #import <ImageIO/ImageIO.h>
  12. #import <zlib.h>
  13. #import <objc/runtime.h>
  14. @implementation FLEXUtility
  15. + (UIColor *)consistentRandomColorForObject:(id)object
  16. {
  17. CGFloat hue = (((NSUInteger)object >> 4) % 256) / 255.0;
  18. return [UIColor colorWithHue:hue saturation:1.0 brightness:1.0 alpha:1.0];
  19. }
  20. + (NSString *)descriptionForView:(UIView *)view includingFrame:(BOOL)includeFrame
  21. {
  22. NSString *description = [[view class] description];
  23. NSString *viewControllerDescription = [[[self viewControllerForView:view] class] description];
  24. if (viewControllerDescription.length > 0) {
  25. description = [description stringByAppendingFormat:@" (%@)", viewControllerDescription];
  26. }
  27. if (includeFrame) {
  28. description = [description stringByAppendingFormat:@" %@", [self stringForCGRect:view.frame]];
  29. }
  30. if (view.accessibilityLabel.length > 0) {
  31. description = [description stringByAppendingFormat:@" · %@", view.accessibilityLabel];
  32. }
  33. return description;
  34. }
  35. + (NSString *)stringForCGRect:(CGRect)rect
  36. {
  37. return [NSString stringWithFormat:@"{(%g, %g), (%g, %g)}", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height];
  38. }
  39. + (UIViewController *)viewControllerForView:(UIView *)view
  40. {
  41. NSString *viewDelegate = @"_viewDelegate";
  42. if ([view respondsToSelector:NSSelectorFromString(viewDelegate)]) {
  43. return [view valueForKey:viewDelegate];
  44. }
  45. return nil;
  46. }
  47. + (UIViewController *)viewControllerForAncestralView:(UIView *)view
  48. {
  49. NSString *_viewControllerForAncestor = @"_viewControllerForAncestor";
  50. if ([view respondsToSelector:NSSelectorFromString(_viewControllerForAncestor)]) {
  51. return [view valueForKey:_viewControllerForAncestor];
  52. }
  53. return nil;
  54. }
  55. + (UIImage *)previewImageForView:(UIView *)view
  56. {
  57. if (CGRectIsEmpty(view.bounds)) {
  58. return nil;
  59. }
  60. CGSize viewSize = view.bounds.size;
  61. UIGraphicsBeginImageContextWithOptions(viewSize, NO, 0.0);
  62. [view drawViewHierarchyInRect:CGRectMake(0, 0, viewSize.width, viewSize.height) afterScreenUpdates:YES];
  63. UIImage *previewImage = UIGraphicsGetImageFromCurrentImageContext();
  64. UIGraphicsEndImageContext();
  65. return previewImage;
  66. }
  67. + (UIImage *)previewImageForLayer:(CALayer *)layer
  68. {
  69. if (CGRectIsEmpty(layer.bounds)) {
  70. return nil;
  71. }
  72. UIGraphicsBeginImageContextWithOptions(layer.bounds.size, NO, 0.0);
  73. CGContextRef imageContext = UIGraphicsGetCurrentContext();
  74. [layer renderInContext:imageContext];
  75. UIImage *previewImage = UIGraphicsGetImageFromCurrentImageContext();
  76. UIGraphicsEndImageContext();
  77. return previewImage;
  78. }
  79. + (NSString *)detailDescriptionForView:(UIView *)view
  80. {
  81. return [NSString stringWithFormat:@"frame %@", [self stringForCGRect:view.frame]];
  82. }
  83. + (UIImage *)circularImageWithColor:(UIColor *)color radius:(CGFloat)radius
  84. {
  85. CGFloat diameter = radius * 2.0;
  86. UIGraphicsBeginImageContextWithOptions(CGSizeMake(diameter, diameter), NO, 0.0);
  87. CGContextRef imageContext = UIGraphicsGetCurrentContext();
  88. CGContextSetFillColorWithColor(imageContext, color.CGColor);
  89. CGContextFillEllipseInRect(imageContext, CGRectMake(0, 0, diameter, diameter));
  90. UIImage *circularImage = UIGraphicsGetImageFromCurrentImageContext();
  91. UIGraphicsEndImageContext();
  92. return circularImage;
  93. }
  94. + (UIColor *)hierarchyIndentPatternColor
  95. {
  96. static UIColor *patternColor = nil;
  97. static dispatch_once_t onceToken;
  98. dispatch_once(&onceToken, ^{
  99. UIImage *indentationPatternImage = [FLEXResources hierarchyIndentPattern];
  100. patternColor = [UIColor colorWithPatternImage:indentationPatternImage];
  101. #if FLEX_AT_LEAST_IOS13_SDK
  102. if (@available(iOS 13.0, *)) {
  103. // Create a dark mode version
  104. UIGraphicsBeginImageContextWithOptions(indentationPatternImage.size, NO, indentationPatternImage.scale);
  105. [[FLEXColor iconColor] set];
  106. [indentationPatternImage drawInRect:CGRectMake(0, 0, indentationPatternImage.size.width, indentationPatternImage.size.height)];
  107. UIImage *darkModePatternImage = UIGraphicsGetImageFromCurrentImageContext();
  108. UIGraphicsEndImageContext();
  109. // Create dynamic color provider
  110. patternColor = [UIColor colorWithDynamicProvider:^UIColor *(UITraitCollection *traitCollection) {
  111. return (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight
  112. ? [UIColor colorWithPatternImage:indentationPatternImage]
  113. : [UIColor colorWithPatternImage:darkModePatternImage]);
  114. }];
  115. }
  116. #endif
  117. });
  118. return patternColor;
  119. }
  120. + (NSString *)applicationImageName
  121. {
  122. return NSBundle.mainBundle.executablePath;
  123. }
  124. + (NSString *)applicationName
  125. {
  126. return [FLEXUtility applicationImageName].lastPathComponent;
  127. }
  128. + (NSString *)pointerToString:(void *)ptr
  129. {
  130. return [NSString stringWithFormat:@"%p", ptr];
  131. }
  132. + (NSString *)addressOfObject:(id)object
  133. {
  134. return [NSString stringWithFormat:@"%p", object];
  135. }
  136. + (NSString *)stringByEscapingHTMLEntitiesInString:(NSString *)originalString
  137. {
  138. static NSDictionary<NSString *, NSString *> *escapingDictionary = nil;
  139. static NSRegularExpression *regex = nil;
  140. static dispatch_once_t onceToken;
  141. dispatch_once(&onceToken, ^{
  142. escapingDictionary = @{ @" " : @"&nbsp;",
  143. @">" : @"&gt;",
  144. @"<" : @"&lt;",
  145. @"&" : @"&amp;",
  146. @"'" : @"&apos;",
  147. @"\"" : @"&quot;",
  148. @"«" : @"&laquo;",
  149. @"»" : @"&raquo;"
  150. };
  151. regex = [NSRegularExpression regularExpressionWithPattern:@"(&|>|<|'|\"|«|»)" options:0 error:NULL];
  152. });
  153. NSMutableString *mutableString = [originalString mutableCopy];
  154. NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:mutableString options:0 range:NSMakeRange(0, mutableString.length)];
  155. for (NSTextCheckingResult *result in matches.reverseObjectEnumerator) {
  156. NSString *foundString = [mutableString substringWithRange:result.range];
  157. NSString *replacementString = escapingDictionary[foundString];
  158. if (replacementString) {
  159. [mutableString replaceCharactersInRange:result.range withString:replacementString];
  160. }
  161. }
  162. return [mutableString copy];
  163. }
  164. + (UIInterfaceOrientationMask)infoPlistSupportedInterfaceOrientationsMask
  165. {
  166. NSArray<NSString *> *supportedOrientations = NSBundle.mainBundle.infoDictionary[@"UISupportedInterfaceOrientations"];
  167. UIInterfaceOrientationMask supportedOrientationsMask = 0;
  168. if ([supportedOrientations containsObject:@"UIInterfaceOrientationPortrait"]) {
  169. supportedOrientationsMask |= UIInterfaceOrientationMaskPortrait;
  170. }
  171. if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskLandscapeRight"]) {
  172. supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeRight;
  173. }
  174. if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskPortraitUpsideDown"]) {
  175. supportedOrientationsMask |= UIInterfaceOrientationMaskPortraitUpsideDown;
  176. }
  177. if ([supportedOrientations containsObject:@"UIInterfaceOrientationLandscapeLeft"]) {
  178. supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeLeft;
  179. }
  180. return supportedOrientationsMask;
  181. }
  182. + (UIImage *)thumbnailedImageWithMaxPixelDimension:(NSInteger)dimension fromImageData:(NSData *)data
  183. {
  184. UIImage *thumbnail = nil;
  185. CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, 0);
  186. if (imageSource) {
  187. NSDictionary<NSString *, id> *options = @{ (__bridge id)kCGImageSourceCreateThumbnailWithTransform : @YES,
  188. (__bridge id)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
  189. (__bridge id)kCGImageSourceThumbnailMaxPixelSize : @(dimension) };
  190. CGImageRef scaledImageRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (__bridge CFDictionaryRef)options);
  191. if (scaledImageRef) {
  192. thumbnail = [UIImage imageWithCGImage:scaledImageRef];
  193. CFRelease(scaledImageRef);
  194. }
  195. CFRelease(imageSource);
  196. }
  197. return thumbnail;
  198. }
  199. + (NSString *)stringFromRequestDuration:(NSTimeInterval)duration
  200. {
  201. NSString *string = @"0s";
  202. if (duration > 0.0) {
  203. if (duration < 1.0) {
  204. string = [NSString stringWithFormat:@"%dms", (int)(duration * 1000)];
  205. } else if (duration < 10.0) {
  206. string = [NSString stringWithFormat:@"%.2fs", duration];
  207. } else {
  208. string = [NSString stringWithFormat:@"%.1fs", duration];
  209. }
  210. }
  211. return string;
  212. }
  213. + (NSString *)statusCodeStringFromURLResponse:(NSURLResponse *)response
  214. {
  215. NSString *httpResponseString = nil;
  216. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  217. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  218. NSString *statusCodeDescription = nil;
  219. if (httpResponse.statusCode == 200) {
  220. // Prefer OK to the default "no error"
  221. statusCodeDescription = @"OK";
  222. } else {
  223. statusCodeDescription = [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode];
  224. }
  225. httpResponseString = [NSString stringWithFormat:@"%ld %@", (long)httpResponse.statusCode, statusCodeDescription];
  226. }
  227. return httpResponseString;
  228. }
  229. + (BOOL)isErrorStatusCodeFromURLResponse:(NSURLResponse *)response
  230. {
  231. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  232. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  233. return httpResponse.statusCode >= 400;
  234. }
  235. return NO;
  236. }
  237. + (NSArray<NSURLQueryItem *> *)itemsFromQueryString:(NSString *)query
  238. {
  239. NSMutableArray<NSURLQueryItem *> *items = [NSMutableArray new];
  240. // [a=1, b=2, c=3]
  241. NSArray<NSString *> *queryComponents = [query componentsSeparatedByString:@"&"];
  242. for (NSString *keyValueString in queryComponents) {
  243. // [a, 1]
  244. NSArray<NSString *> *components = [keyValueString componentsSeparatedByString:@"="];
  245. if (components.count == 2) {
  246. NSString *key = components.firstObject.stringByRemovingPercentEncoding;
  247. NSString *value = components.lastObject.stringByRemovingPercentEncoding;
  248. [items addObject:[NSURLQueryItem queryItemWithName:key value:value]];
  249. }
  250. }
  251. return items.copy;
  252. }
  253. + (NSString *)prettyJSONStringFromData:(NSData *)data
  254. {
  255. NSString *prettyString = nil;
  256. id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
  257. if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
  258. prettyString = [NSString stringWithCString:[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL].bytes encoding:NSUTF8StringEncoding];
  259. // NSJSONSerialization escapes forward slashes. We want pretty json, so run through and unescape the slashes.
  260. prettyString = [prettyString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
  261. } else {
  262. prettyString = [NSString stringWithCString:data.bytes encoding:NSUTF8StringEncoding];
  263. }
  264. return prettyString;
  265. }
  266. + (BOOL)isValidJSONData:(NSData *)data
  267. {
  268. return [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL] ? YES : NO;
  269. }
  270. // Thanks to the following links for help with this method
  271. // https://www.cocoanetics.com/2012/02/decompressing-files-into-memory/
  272. // https://github.com/nicklockwood/GZIP
  273. + (NSData *)inflatedDataFromCompressedData:(NSData *)compressedData
  274. {
  275. NSData *inflatedData = nil;
  276. NSUInteger compressedDataLength = compressedData.length;
  277. if (compressedDataLength > 0) {
  278. z_stream stream;
  279. stream.zalloc = Z_NULL;
  280. stream.zfree = Z_NULL;
  281. stream.avail_in = (uInt)compressedDataLength;
  282. stream.next_in = (void *)compressedData.bytes;
  283. stream.total_out = 0;
  284. stream.avail_out = 0;
  285. NSMutableData *mutableData = [NSMutableData dataWithLength:compressedDataLength * 1.5];
  286. if (inflateInit2(&stream, 15 + 32) == Z_OK) {
  287. int status = Z_OK;
  288. while (status == Z_OK) {
  289. if (stream.total_out >= mutableData.length) {
  290. mutableData.length += compressedDataLength / 2;
  291. }
  292. stream.next_out = (uint8_t *)[mutableData mutableBytes] + stream.total_out;
  293. stream.avail_out = (uInt)(mutableData.length - stream.total_out);
  294. status = inflate(&stream, Z_SYNC_FLUSH);
  295. }
  296. if (inflateEnd(&stream) == Z_OK) {
  297. if (status == Z_STREAM_END) {
  298. mutableData.length = stream.total_out;
  299. inflatedData = [mutableData copy];
  300. }
  301. }
  302. }
  303. }
  304. return inflatedData;
  305. }
  306. + (NSArray<UIWindow *> *)allWindows
  307. {
  308. BOOL includeInternalWindows = YES;
  309. BOOL onlyVisibleWindows = NO;
  310. // Obfuscating selector allWindowsIncludingInternalWindows:onlyVisibleWindows:
  311. NSArray<NSString *> *allWindowsComponents = @[@"al", @"lWindo", @"wsIncl", @"udingInt", @"ernalWin", @"dows:o", @"nlyVisi", @"bleWin", @"dows:"];
  312. SEL allWindowsSelector = NSSelectorFromString([allWindowsComponents componentsJoinedByString:@""]);
  313. NSMethodSignature *methodSignature = [[UIWindow class] methodSignatureForSelector:allWindowsSelector];
  314. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
  315. invocation.target = [UIWindow class];
  316. invocation.selector = allWindowsSelector;
  317. [invocation setArgument:&includeInternalWindows atIndex:2];
  318. [invocation setArgument:&onlyVisibleWindows atIndex:3];
  319. [invocation invoke];
  320. __unsafe_unretained NSArray<UIWindow *> *windows = nil;
  321. [invocation getReturnValue:&windows];
  322. return windows;
  323. }
  324. + (UIAlertController *)alert:(NSString *)title message:(NSString *)message
  325. {
  326. return [UIAlertController
  327. alertControllerWithTitle:title
  328. message:message
  329. preferredStyle:UIAlertControllerStyleAlert
  330. ];
  331. }
  332. + (SEL)swizzledSelectorForSelector:(SEL)selector
  333. {
  334. return NSSelectorFromString([NSString stringWithFormat:@"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]);
  335. }
  336. + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls
  337. {
  338. if ([cls instancesRespondToSelector:selector]) {
  339. unsigned int numMethods = 0;
  340. Method *methods = class_copyMethodList(cls, &numMethods);
  341. BOOL implementsSelector = NO;
  342. for (int index = 0; index < numMethods; index++) {
  343. SEL methodSelector = method_getName(methods[index]);
  344. if (selector == methodSelector) {
  345. implementsSelector = YES;
  346. break;
  347. }
  348. }
  349. free(methods);
  350. if (!implementsSelector) {
  351. return YES;
  352. }
  353. }
  354. return NO;
  355. }
  356. + (void)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)class withBlock:(id)block swizzledSelector:(SEL)swizzledSelector
  357. {
  358. // This method is only intended for swizzling methods that are know to exist on the class.
  359. // Bail if that isn't the case.
  360. Method originalMethod = class_getInstanceMethod(class, originalSelector);
  361. if (!originalMethod) {
  362. return;
  363. }
  364. IMP implementation = imp_implementationWithBlock(block);
  365. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalMethod));
  366. Method newMethod = class_getInstanceMethod(class, swizzledSelector);
  367. method_exchangeImplementations(originalMethod, newMethod);
  368. }
  369. + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
  370. {
  371. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  372. return;
  373. }
  374. IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
  375. Method oldMethod = class_getInstanceMethod(cls, selector);
  376. const char *types = methodDescription.types;
  377. if (oldMethod) {
  378. if (!types) {
  379. types = method_getTypeEncoding(oldMethod);
  380. }
  381. class_addMethod(cls, swizzledSelector, implementation, types);
  382. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  383. method_exchangeImplementations(oldMethod, newMethod);
  384. } else {
  385. if (!types) {
  386. // Some protocol method descriptions don't have .types populated
  387. // Set the return type to void and ignore arguments
  388. types = "v@:";
  389. }
  390. class_addMethod(cls, selector, implementation, types);
  391. }
  392. }
  393. @end