FLEXUtility.m 16 KB

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