FLEXUtility.m 19 KB

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