FLEXUtility.m 17 KB

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