FLEXUtility.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 "FLEXUtility.h"
  9. #import "FLEXResources.h"
  10. #import <ImageIO/ImageIO.h>
  11. #import <zlib.h>
  12. #import <objc/runtime.h>
  13. @implementation FLEXUtility
  14. + (UIColor *)consistentRandomColorForObject:(id)object
  15. {
  16. CGFloat hue = (((NSUInteger)object >> 4) % 256) / 255.0;
  17. return [UIColor colorWithHue:hue saturation:1.0 brightness:1.0 alpha:1.0];
  18. }
  19. + (NSString *)descriptionForView:(UIView *)view includingFrame:(BOOL)includeFrame
  20. {
  21. NSString *description = [[view class] description];
  22. NSString *viewControllerDescription = [[[self viewControllerForView:view] class] description];
  23. if ([viewControllerDescription length] > 0) {
  24. description = [description stringByAppendingFormat:@" (%@)", viewControllerDescription];
  25. }
  26. if (includeFrame) {
  27. description = [description stringByAppendingFormat:@" %@", [self stringForCGRect:view.frame]];
  28. }
  29. if ([view.accessibilityLabel length] > 0) {
  30. description = [description stringByAppendingFormat:@" · %@", view.accessibilityLabel];
  31. }
  32. return description;
  33. }
  34. + (NSString *)stringForCGRect:(CGRect)rect
  35. {
  36. return [NSString stringWithFormat:@"{(%g, %g), (%g, %g)}", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height];
  37. }
  38. + (UIViewController *)viewControllerForView:(UIView *)view
  39. {
  40. UIViewController *viewController = nil;
  41. SEL viewDelSel = NSSelectorFromString(@"_viewDelegate");
  42. if ([view respondsToSelector:viewDelSel]) {
  43. #pragma clang diagnostic push
  44. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  45. viewController = [view performSelector:viewDelSel];
  46. #pragma clang diagnostic pop
  47. }
  48. return viewController;
  49. }
  50. + (UIViewController *)viewControllerForAncestralView:(UIView *)view
  51. {
  52. UIViewController *viewController = nil;
  53. SEL viewDelSel = NSSelectorFromString([NSString stringWithFormat:@"%@ewControllerForAncestor", @"_vi"]);
  54. if ([view respondsToSelector:viewDelSel]) {
  55. #pragma clang diagnostic push
  56. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  57. viewController = [view performSelector:viewDelSel];
  58. #pragma clang diagnostic pop
  59. }
  60. return viewController;
  61. }
  62. + (NSString *)detailDescriptionForView:(UIView *)view
  63. {
  64. return [NSString stringWithFormat:@"frame %@", [self stringForCGRect:view.frame]];
  65. }
  66. + (UIImage *)circularImageWithColor:(UIColor *)color radius:(CGFloat)radius
  67. {
  68. CGFloat diameter = radius * 2.0;
  69. UIGraphicsBeginImageContextWithOptions(CGSizeMake(diameter, diameter), NO, 0.0);
  70. CGContextRef imageContext = UIGraphicsGetCurrentContext();
  71. CGContextSetFillColorWithColor(imageContext, [color CGColor]);
  72. CGContextFillEllipseInRect(imageContext, CGRectMake(0, 0, diameter, diameter));
  73. UIImage *circularImage = UIGraphicsGetImageFromCurrentImageContext();
  74. UIGraphicsEndImageContext();
  75. return circularImage;
  76. }
  77. + (UIColor *)scrollViewGrayColor
  78. {
  79. return [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1.0];
  80. }
  81. + (UIColor *)hierarchyIndentPatternColor
  82. {
  83. static UIColor *patternColor = nil;
  84. static dispatch_once_t onceToken;
  85. dispatch_once(&onceToken, ^{
  86. UIImage *indentationPatternImage = [FLEXResources hierarchyIndentPattern];
  87. patternColor = [UIColor colorWithPatternImage:indentationPatternImage];
  88. });
  89. return patternColor;
  90. }
  91. + (NSString *)applicationImageName
  92. {
  93. return [NSBundle mainBundle].executablePath;
  94. }
  95. + (NSString *)applicationName
  96. {
  97. return [FLEXUtility applicationImageName].lastPathComponent;
  98. }
  99. + (NSString *)safeDescriptionForObject:(id)object
  100. {
  101. // Don't assume that we have an NSObject subclass.
  102. // Check to make sure the object responds to the description methods.
  103. NSString *description = nil;
  104. if ([object respondsToSelector:@selector(debugDescription)]) {
  105. description = [object debugDescription];
  106. } else if ([object respondsToSelector:@selector(description)]) {
  107. description = [object description];
  108. }
  109. return description;
  110. }
  111. + (NSString *)safeDebugDescriptionForObject:(id)object
  112. {
  113. NSString *description = [self safeDescriptionForObject:object];
  114. if (!description) {
  115. NSString *cls = NSStringFromClass(object_getClass(object));
  116. if (object_isClass(object)) {
  117. description = [cls stringByAppendingString:@" class (no description)"];
  118. } else {
  119. description = [cls stringByAppendingString:@" instance (no description)"];
  120. }
  121. }
  122. return description;
  123. }
  124. + (NSString *)addressOfObject:(id)object
  125. {
  126. return [NSString stringWithFormat:@"%p", object];
  127. }
  128. + (UIFont *)defaultFontOfSize:(CGFloat)size
  129. {
  130. return [UIFont fontWithName:@"HelveticaNeue" size:size];
  131. }
  132. + (UIFont *)defaultTableViewCellLabelFont
  133. {
  134. return [self defaultFontOfSize:12.0];
  135. }
  136. + (NSString *)stringByEscapingHTMLEntitiesInString:(NSString *)originalString
  137. {
  138. static NSDictionary<NSString *, NSString *> *escapingDictionary = nil;
  139. static NSRegularExpression *regex = nil;
  140. static dispatch_once_t onceToken;
  141. dispatch_once(&onceToken, ^{
  142. escapingDictionary = @{ @" " : @"&nbsp;",
  143. @">" : @"&gt;",
  144. @"<" : @"&lt;",
  145. @"&" : @"&amp;",
  146. @"'" : @"&apos;",
  147. @"\"" : @"&quot;",
  148. @"«" : @"&laquo;",
  149. @"»" : @"&raquo;"
  150. };
  151. regex = [NSRegularExpression regularExpressionWithPattern:@"(&|>|<|'|\"|«|»)" options:0 error:NULL];
  152. });
  153. NSMutableString *mutableString = [originalString mutableCopy];
  154. NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:mutableString options:0 range:NSMakeRange(0, [mutableString length])];
  155. for (NSTextCheckingResult *result in [matches reverseObjectEnumerator]) {
  156. NSString *foundString = [mutableString substringWithRange:result.range];
  157. NSString *replacementString = escapingDictionary[foundString];
  158. if (replacementString) {
  159. [mutableString replaceCharactersInRange:result.range withString:replacementString];
  160. }
  161. }
  162. return [mutableString copy];
  163. }
  164. + (UIInterfaceOrientationMask)infoPlistSupportedInterfaceOrientationsMask
  165. {
  166. NSArray<NSString *> *supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"];
  167. UIInterfaceOrientationMask supportedOrientationsMask = 0;
  168. if ([supportedOrientations containsObject:@"UIInterfaceOrientationPortrait"]) {
  169. supportedOrientationsMask |= UIInterfaceOrientationMaskPortrait;
  170. }
  171. if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskLandscapeRight"]) {
  172. supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeRight;
  173. }
  174. if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskPortraitUpsideDown"]) {
  175. supportedOrientationsMask |= UIInterfaceOrientationMaskPortraitUpsideDown;
  176. }
  177. if ([supportedOrientations containsObject:@"UIInterfaceOrientationLandscapeLeft"]) {
  178. supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeLeft;
  179. }
  180. return supportedOrientationsMask;
  181. }
  182. + (NSString *)searchBarPlaceholderText
  183. {
  184. return @"Filter";
  185. }
  186. + (UIImage *)thumbnailedImageWithMaxPixelDimension:(NSInteger)dimension fromImageData:(NSData *)data
  187. {
  188. UIImage *thumbnail = nil;
  189. CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, 0);
  190. if (imageSource) {
  191. NSDictionary<NSString *, id> *options = @{ (__bridge id)kCGImageSourceCreateThumbnailWithTransform : @YES,
  192. (__bridge id)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
  193. (__bridge id)kCGImageSourceThumbnailMaxPixelSize : @(dimension) };
  194. CGImageRef scaledImageRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (__bridge CFDictionaryRef)options);
  195. if (scaledImageRef) {
  196. thumbnail = [UIImage imageWithCGImage:scaledImageRef];
  197. CFRelease(scaledImageRef);
  198. }
  199. CFRelease(imageSource);
  200. }
  201. return thumbnail;
  202. }
  203. + (NSString *)stringFromRequestDuration:(NSTimeInterval)duration
  204. {
  205. NSString *string = @"0s";
  206. if (duration > 0.0) {
  207. if (duration < 1.0) {
  208. string = [NSString stringWithFormat:@"%dms", (int)(duration * 1000)];
  209. } else if (duration < 10.0) {
  210. string = [NSString stringWithFormat:@"%.2fs", duration];
  211. } else {
  212. string = [NSString stringWithFormat:@"%.1fs", duration];
  213. }
  214. }
  215. return string;
  216. }
  217. + (NSString *)statusCodeStringFromURLResponse:(NSURLResponse *)response
  218. {
  219. NSString *httpResponseString = nil;
  220. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  221. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  222. NSString *statusCodeDescription = nil;
  223. if (httpResponse.statusCode == 200) {
  224. // Prefer OK to the default "no error"
  225. statusCodeDescription = @"OK";
  226. } else {
  227. statusCodeDescription = [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode];
  228. }
  229. httpResponseString = [NSString stringWithFormat:@"%ld %@", (long)httpResponse.statusCode, statusCodeDescription];
  230. }
  231. return httpResponseString;
  232. }
  233. + (BOOL)isErrorStatusCodeFromURLResponse:(NSURLResponse *)response
  234. {
  235. NSIndexSet *errorStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(400, 200)];
  236. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  237. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  238. return [errorStatusCodes containsIndex:httpResponse.statusCode];
  239. }
  240. return NO;
  241. }
  242. + (NSDictionary<NSString *, id> *)dictionaryFromQuery:(NSString *)query
  243. {
  244. NSMutableDictionary<NSString *, id> *queryDictionary = [NSMutableDictionary dictionary];
  245. // [a=1, b=2, c=3]
  246. NSArray<NSString *> *queryComponents = [query componentsSeparatedByString:@"&"];
  247. for (NSString *keyValueString in queryComponents) {
  248. // [a, 1]
  249. NSArray<NSString *> *components = [keyValueString componentsSeparatedByString:@"="];
  250. if ([components count] == 2) {
  251. NSString *key = [[components firstObject] stringByRemovingPercentEncoding];
  252. id value = [[components lastObject] stringByRemovingPercentEncoding];
  253. // Handle multiple entries under the same key as an array
  254. id existingEntry = queryDictionary[key];
  255. if (existingEntry) {
  256. if ([existingEntry isKindOfClass:[NSArray class]]) {
  257. value = [existingEntry arrayByAddingObject:value];
  258. } else {
  259. value = @[existingEntry, value];
  260. }
  261. }
  262. [queryDictionary setObject:value forKey:key];
  263. }
  264. }
  265. return queryDictionary;
  266. }
  267. + (NSString *)prettyJSONStringFromData:(NSData *)data
  268. {
  269. NSString *prettyString = nil;
  270. id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
  271. if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
  272. prettyString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL] encoding:NSUTF8StringEncoding];
  273. // NSJSONSerialization escapes forward slashes. We want pretty json, so run through and unescape the slashes.
  274. prettyString = [prettyString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
  275. } else {
  276. prettyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  277. }
  278. return prettyString;
  279. }
  280. + (BOOL)isValidJSONData:(NSData *)data
  281. {
  282. return [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL] ? YES : NO;
  283. }
  284. // Thanks to the following links for help with this method
  285. // https://www.cocoanetics.com/2012/02/decompressing-files-into-memory/
  286. // https://github.com/nicklockwood/GZIP
  287. + (NSData *)inflatedDataFromCompressedData:(NSData *)compressedData
  288. {
  289. NSData *inflatedData = nil;
  290. NSUInteger compressedDataLength = [compressedData length];
  291. if (compressedDataLength > 0) {
  292. z_stream stream;
  293. stream.zalloc = Z_NULL;
  294. stream.zfree = Z_NULL;
  295. stream.avail_in = (uInt)compressedDataLength;
  296. stream.next_in = (void *)[compressedData bytes];
  297. stream.total_out = 0;
  298. stream.avail_out = 0;
  299. NSMutableData *mutableData = [NSMutableData dataWithLength:compressedDataLength * 1.5];
  300. if (inflateInit2(&stream, 15 + 32) == Z_OK) {
  301. int status = Z_OK;
  302. while (status == Z_OK) {
  303. if (stream.total_out >= [mutableData length]) {
  304. mutableData.length += compressedDataLength / 2;
  305. }
  306. stream.next_out = (uint8_t *)[mutableData mutableBytes] + stream.total_out;
  307. stream.avail_out = (uInt)([mutableData length] - stream.total_out);
  308. status = inflate(&stream, Z_SYNC_FLUSH);
  309. }
  310. if (inflateEnd(&stream) == Z_OK) {
  311. if (status == Z_STREAM_END) {
  312. mutableData.length = stream.total_out;
  313. inflatedData = [mutableData copy];
  314. }
  315. }
  316. }
  317. }
  318. return inflatedData;
  319. }
  320. + (NSArray<UIWindow *> *)allWindows
  321. {
  322. BOOL includeInternalWindows = YES;
  323. BOOL onlyVisibleWindows = NO;
  324. // Obfuscating selector allWindowsIncludingInternalWindows:onlyVisibleWindows:
  325. NSArray<NSString *> *allWindowsComponents = @[@"al", @"lWindo", @"wsIncl", @"udingInt", @"ernalWin", @"dows:o", @"nlyVisi", @"bleWin", @"dows:"];
  326. SEL allWindowsSelector = NSSelectorFromString([allWindowsComponents componentsJoinedByString:@""]);
  327. NSMethodSignature *methodSignature = [[UIWindow class] methodSignatureForSelector:allWindowsSelector];
  328. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
  329. invocation.target = [UIWindow class];
  330. invocation.selector = allWindowsSelector;
  331. [invocation setArgument:&includeInternalWindows atIndex:2];
  332. [invocation setArgument:&onlyVisibleWindows atIndex:3];
  333. [invocation invoke];
  334. __unsafe_unretained NSArray<UIWindow *> *windows = nil;
  335. [invocation getReturnValue:&windows];
  336. return windows;
  337. }
  338. + (void)alert:(NSString *)title message:(NSString *)message from:(UIViewController *)viewController
  339. {
  340. [[[UIAlertView alloc] initWithTitle:title
  341. message:message
  342. delegate:nil
  343. cancelButtonTitle:nil
  344. otherButtonTitles:@"Dismiss", nil] show];
  345. }
  346. + (SEL)swizzledSelectorForSelector:(SEL)selector
  347. {
  348. return NSSelectorFromString([NSString stringWithFormat:@"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]);
  349. }
  350. + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls
  351. {
  352. if ([cls instancesRespondToSelector:selector]) {
  353. unsigned int numMethods = 0;
  354. Method *methods = class_copyMethodList(cls, &numMethods);
  355. BOOL implementsSelector = NO;
  356. for (int index = 0; index < numMethods; index++) {
  357. SEL methodSelector = method_getName(methods[index]);
  358. if (selector == methodSelector) {
  359. implementsSelector = YES;
  360. break;
  361. }
  362. }
  363. free(methods);
  364. if (!implementsSelector) {
  365. return YES;
  366. }
  367. }
  368. return NO;
  369. }
  370. + (void)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)class withBlock:(id)block swizzledSelector:(SEL)swizzledSelector
  371. {
  372. // This method is only intended for swizzling methods that are know to exist on the class.
  373. // Bail if that isn't the case.
  374. Method originalMethod = class_getInstanceMethod(class, originalSelector);
  375. if (!originalMethod) {
  376. return;
  377. }
  378. IMP implementation = imp_implementationWithBlock(block);
  379. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalMethod));
  380. Method newMethod = class_getInstanceMethod(class, swizzledSelector);
  381. method_exchangeImplementations(originalMethod, newMethod);
  382. }
  383. + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
  384. {
  385. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  386. return;
  387. }
  388. IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
  389. Method oldMethod = class_getInstanceMethod(cls, selector);
  390. if (oldMethod) {
  391. class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
  392. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  393. method_exchangeImplementations(oldMethod, newMethod);
  394. } else {
  395. class_addMethod(cls, selector, implementation, methodDescription.types);
  396. }
  397. }
  398. @end