FLEXUtility.m 20 KB

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