FLEXUtility.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. + (UIInterfaceOrientationMask)infoPlistSupportedInterfaceOrientationsMask {
  220. NSArray<NSString *> *supportedOrientations = NSBundle.mainBundle.infoDictionary[@"UISupportedInterfaceOrientations"];
  221. UIInterfaceOrientationMask supportedOrientationsMask = 0;
  222. if ([supportedOrientations containsObject:@"UIInterfaceOrientationPortrait"]) {
  223. supportedOrientationsMask |= UIInterfaceOrientationMaskPortrait;
  224. }
  225. if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskLandscapeRight"]) {
  226. supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeRight;
  227. }
  228. if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskPortraitUpsideDown"]) {
  229. supportedOrientationsMask |= UIInterfaceOrientationMaskPortraitUpsideDown;
  230. }
  231. if ([supportedOrientations containsObject:@"UIInterfaceOrientationLandscapeLeft"]) {
  232. supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeLeft;
  233. }
  234. return supportedOrientationsMask;
  235. }
  236. + (UIImage *)thumbnailedImageWithMaxPixelDimension:(NSInteger)dimension fromImageData:(NSData *)data {
  237. UIImage *thumbnail = nil;
  238. CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, 0);
  239. if (imageSource) {
  240. NSDictionary<NSString *, id> *options = @{
  241. (__bridge id)kCGImageSourceCreateThumbnailWithTransform : @YES,
  242. (__bridge id)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
  243. (__bridge id)kCGImageSourceThumbnailMaxPixelSize : @(dimension)
  244. };
  245. CGImageRef scaledImageRef = CGImageSourceCreateThumbnailAtIndex(
  246. imageSource, 0, (__bridge CFDictionaryRef)options
  247. );
  248. if (scaledImageRef) {
  249. thumbnail = [UIImage imageWithCGImage:scaledImageRef];
  250. CFRelease(scaledImageRef);
  251. }
  252. CFRelease(imageSource);
  253. }
  254. return thumbnail;
  255. }
  256. + (NSString *)stringFromRequestDuration:(NSTimeInterval)duration {
  257. NSString *string = @"0s";
  258. if (duration > 0.0) {
  259. if (duration < 1.0) {
  260. string = [NSString stringWithFormat:@"%dms", (int)(duration * 1000)];
  261. } else if (duration < 10.0) {
  262. string = [NSString stringWithFormat:@"%.2fs", duration];
  263. } else {
  264. string = [NSString stringWithFormat:@"%.1fs", duration];
  265. }
  266. }
  267. return string;
  268. }
  269. + (NSString *)statusCodeStringFromURLResponse:(NSURLResponse *)response {
  270. NSString *httpResponseString = nil;
  271. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  272. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  273. NSString *statusCodeDescription = nil;
  274. if (httpResponse.statusCode == 200) {
  275. // Prefer OK to the default "no error"
  276. statusCodeDescription = @"OK";
  277. } else {
  278. statusCodeDescription = [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode];
  279. }
  280. httpResponseString = [NSString stringWithFormat:@"%ld %@", (long)httpResponse.statusCode, statusCodeDescription];
  281. }
  282. return httpResponseString;
  283. }
  284. + (BOOL)isErrorStatusCodeFromURLResponse:(NSURLResponse *)response {
  285. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  286. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  287. return httpResponse.statusCode >= 400;
  288. }
  289. return NO;
  290. }
  291. + (NSArray<NSURLQueryItem *> *)itemsFromQueryString:(NSString *)query {
  292. NSMutableArray<NSURLQueryItem *> *items = [NSMutableArray new];
  293. // [a=1, b=2, c=3]
  294. NSArray<NSString *> *queryComponents = [query componentsSeparatedByString:@"&"];
  295. for (NSString *keyValueString in queryComponents) {
  296. // [a, 1]
  297. NSArray<NSString *> *components = [keyValueString componentsSeparatedByString:@"="];
  298. if (components.count == 2) {
  299. NSString *key = components.firstObject.stringByRemovingPercentEncoding;
  300. NSString *value = components.lastObject.stringByRemovingPercentEncoding;
  301. [items addObject:[NSURLQueryItem queryItemWithName:key value:value]];
  302. }
  303. }
  304. return items.copy;
  305. }
  306. + (NSString *)prettyJSONStringFromData:(NSData *)data {
  307. NSString *prettyString = nil;
  308. id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
  309. if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
  310. // Thanks RaziPour1993
  311. prettyString = [[NSString alloc]
  312. initWithData:[NSJSONSerialization
  313. dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL
  314. ]
  315. encoding:NSUTF8StringEncoding
  316. ];
  317. // NSJSONSerialization escapes forward slashes.
  318. // We want pretty json, so run through and unescape the slashes.
  319. prettyString = [prettyString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
  320. } else {
  321. prettyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  322. }
  323. return prettyString;
  324. }
  325. + (BOOL)isValidJSONData:(NSData *)data {
  326. return [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL] ? YES : NO;
  327. }
  328. // Thanks to the following links for help with this method
  329. // https://www.cocoanetics.com/2012/02/decompressing-files-into-memory/
  330. // https://github.com/nicklockwood/GZIP
  331. + (NSData *)inflatedDataFromCompressedData:(NSData *)compressedData {
  332. NSData *inflatedData = nil;
  333. NSUInteger compressedDataLength = compressedData.length;
  334. if (compressedDataLength > 0) {
  335. z_stream stream;
  336. stream.zalloc = Z_NULL;
  337. stream.zfree = Z_NULL;
  338. stream.avail_in = (uInt)compressedDataLength;
  339. stream.next_in = (void *)compressedData.bytes;
  340. stream.total_out = 0;
  341. stream.avail_out = 0;
  342. NSMutableData *mutableData = [NSMutableData dataWithLength:compressedDataLength * 1.5];
  343. if (inflateInit2(&stream, 15 + 32) == Z_OK) {
  344. int status = Z_OK;
  345. while (status == Z_OK) {
  346. if (stream.total_out >= mutableData.length) {
  347. mutableData.length += compressedDataLength / 2;
  348. }
  349. stream.next_out = (uint8_t *)[mutableData mutableBytes] + stream.total_out;
  350. stream.avail_out = (uInt)(mutableData.length - stream.total_out);
  351. status = inflate(&stream, Z_SYNC_FLUSH);
  352. }
  353. if (inflateEnd(&stream) == Z_OK) {
  354. if (status == Z_STREAM_END) {
  355. mutableData.length = stream.total_out;
  356. inflatedData = [mutableData copy];
  357. }
  358. }
  359. }
  360. }
  361. return inflatedData;
  362. }
  363. + (NSArray<UIWindow *> *)allWindows {
  364. BOOL includeInternalWindows = YES;
  365. BOOL onlyVisibleWindows = NO;
  366. // Obfuscating selector allWindowsIncludingInternalWindows:onlyVisibleWindows:
  367. NSArray<NSString *> *allWindowsComponents = @[
  368. @"al", @"lWindo", @"wsIncl", @"udingInt", @"ernalWin", @"dows:o", @"nlyVisi", @"bleWin", @"dows:"
  369. ];
  370. SEL allWindowsSelector = NSSelectorFromString([allWindowsComponents componentsJoinedByString:@""]);
  371. NSMethodSignature *methodSignature = [[UIWindow class] methodSignatureForSelector:allWindowsSelector];
  372. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
  373. invocation.target = [UIWindow class];
  374. invocation.selector = allWindowsSelector;
  375. [invocation setArgument:&includeInternalWindows atIndex:2];
  376. [invocation setArgument:&onlyVisibleWindows atIndex:3];
  377. [invocation invoke];
  378. __unsafe_unretained NSArray<UIWindow *> *windows = nil;
  379. [invocation getReturnValue:&windows];
  380. return windows;
  381. }
  382. + (UIAlertController *)alert:(NSString *)title message:(NSString *)message {
  383. return [UIAlertController
  384. alertControllerWithTitle:title
  385. message:message
  386. preferredStyle:UIAlertControllerStyleAlert
  387. ];
  388. }
  389. + (SEL)swizzledSelectorForSelector:(SEL)selector {
  390. return NSSelectorFromString([NSString stringWithFormat:
  391. @"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)
  392. ]);
  393. }
  394. + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls {
  395. if ([cls instancesRespondToSelector:selector]) {
  396. unsigned int numMethods = 0;
  397. Method *methods = class_copyMethodList(cls, &numMethods);
  398. BOOL implementsSelector = NO;
  399. for (int index = 0; index < numMethods; index++) {
  400. SEL methodSelector = method_getName(methods[index]);
  401. if (selector == methodSelector) {
  402. implementsSelector = YES;
  403. break;
  404. }
  405. }
  406. free(methods);
  407. if (!implementsSelector) {
  408. return YES;
  409. }
  410. }
  411. return NO;
  412. }
  413. + (void)replaceImplementationOfKnownSelector:(SEL)originalSelector
  414. onClass:(Class)class
  415. withBlock:(id)block
  416. swizzledSelector:(SEL)swizzledSelector {
  417. // This method is only intended for swizzling methods that are know to exist on the class.
  418. // Bail if that isn't the case.
  419. Method originalMethod = class_getInstanceMethod(class, originalSelector);
  420. if (!originalMethod) {
  421. return;
  422. }
  423. IMP implementation = imp_implementationWithBlock(block);
  424. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalMethod));
  425. Method newMethod = class_getInstanceMethod(class, swizzledSelector);
  426. method_exchangeImplementations(originalMethod, newMethod);
  427. }
  428. + (void)replaceImplementationOfSelector:(SEL)selector
  429. withSelector:(SEL)swizzledSelector
  430. forClass:(Class)cls
  431. withMethodDescription:(struct objc_method_description)methodDescription
  432. implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock {
  433. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  434. return;
  435. }
  436. IMP implementation = imp_implementationWithBlock((id)(
  437. [cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock)
  438. );
  439. Method oldMethod = class_getInstanceMethod(cls, selector);
  440. const char *types = methodDescription.types;
  441. if (oldMethod) {
  442. if (!types) {
  443. types = method_getTypeEncoding(oldMethod);
  444. }
  445. class_addMethod(cls, swizzledSelector, implementation, types);
  446. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  447. method_exchangeImplementations(oldMethod, newMethod);
  448. } else {
  449. if (!types) {
  450. // Some protocol method descriptions don't have .types populated
  451. // Set the return type to void and ignore arguments
  452. types = "v@:";
  453. }
  454. class_addMethod(cls, selector, implementation, types);
  455. }
  456. }
  457. @end