FLEXUtility.m 16 KB

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