FLEXUtility.m 16 KB

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