RCTUtils.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RCTUtils.h"
  8. #import <dlfcn.h>
  9. #import <mach/mach_time.h>
  10. #import <objc/message.h>
  11. #import <objc/runtime.h>
  12. #import <zlib.h>
  13. #import <UIKit/UIKit.h>
  14. #import <CommonCrypto/CommonCrypto.h>
  15. #import "RCTAssert.h"
  16. #import "RCTLog.h"
  17. NSString *const RCTErrorUnspecified = @"EUNSPECIFIED";
  18. static NSString *__nullable _RCTJSONStringifyNoRetry(id __nullable jsonObject, NSError **error)
  19. {
  20. if (!jsonObject) {
  21. return nil;
  22. }
  23. static SEL JSONKitSelector = NULL;
  24. static NSSet<Class> *collectionTypes;
  25. static dispatch_once_t onceToken;
  26. dispatch_once(&onceToken, ^{
  27. SEL selector = NSSelectorFromString(@"JSONStringWithOptions:error:");
  28. if ([NSDictionary instancesRespondToSelector:selector]) {
  29. JSONKitSelector = selector;
  30. collectionTypes = [NSSet setWithObjects:
  31. [NSArray class], [NSMutableArray class],
  32. [NSDictionary class], [NSMutableDictionary class], nil];
  33. }
  34. });
  35. @try {
  36. // Use JSONKit if available and object is not a fragment
  37. if (JSONKitSelector && [collectionTypes containsObject:[jsonObject classForCoder]]) {
  38. return ((NSString *(*)(id, SEL, int, NSError **))objc_msgSend)(jsonObject, JSONKitSelector, 0, error);
  39. }
  40. // Use Foundation JSON method
  41. NSData *jsonData = [NSJSONSerialization
  42. dataWithJSONObject:jsonObject options:(NSJSONWritingOptions)NSJSONReadingAllowFragments
  43. error:error];
  44. return jsonData ? [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] : nil;
  45. }
  46. @catch (NSException *exception) {
  47. // Convert exception to error
  48. if (error) {
  49. *error = [NSError errorWithDomain:RCTErrorDomain code:0 userInfo:@{
  50. NSLocalizedDescriptionKey: exception.description ?: @""
  51. }];
  52. }
  53. return nil;
  54. }
  55. }
  56. NSString *__nullable RCTJSONStringify(id __nullable jsonObject, NSError **error)
  57. {
  58. if (error) {
  59. return _RCTJSONStringifyNoRetry(jsonObject, error);
  60. } else {
  61. NSError *localError;
  62. NSString *json = _RCTJSONStringifyNoRetry(jsonObject, &localError);
  63. if (localError) {
  64. RCTLogError(@"RCTJSONStringify() encountered the following error: %@",
  65. localError.localizedDescription);
  66. // Sanitize the data, then retry. This is slow, but it prevents uncaught
  67. // data issues from crashing in production
  68. return _RCTJSONStringifyNoRetry(RCTJSONClean(jsonObject), NULL);
  69. }
  70. return json;
  71. }
  72. }
  73. static id __nullable _RCTJSONParse(NSString *__nullable jsonString, BOOL mutable, NSError **error)
  74. {
  75. static SEL JSONKitSelector = NULL;
  76. static SEL JSONKitMutableSelector = NULL;
  77. static dispatch_once_t onceToken;
  78. dispatch_once(&onceToken, ^{
  79. SEL selector = NSSelectorFromString(@"objectFromJSONStringWithParseOptions:error:");
  80. if ([NSString instancesRespondToSelector:selector]) {
  81. JSONKitSelector = selector;
  82. JSONKitMutableSelector = NSSelectorFromString(@"mutableObjectFromJSONStringWithParseOptions:error:");
  83. }
  84. });
  85. if (jsonString) {
  86. // Use JSONKit if available and string is not a fragment
  87. if (JSONKitSelector) {
  88. NSInteger length = jsonString.length;
  89. for (NSInteger i = 0; i < length; i++) {
  90. unichar c = [jsonString characterAtIndex:i];
  91. if (strchr("{[", c)) {
  92. static const int options = (1 << 2); // loose unicode
  93. SEL selector = mutable ? JSONKitMutableSelector : JSONKitSelector;
  94. return ((id (*)(id, SEL, int, NSError **))objc_msgSend)(jsonString, selector, options, error);
  95. }
  96. if (!strchr(" \r\n\t", c)) {
  97. break;
  98. }
  99. }
  100. }
  101. // Use Foundation JSON method
  102. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  103. if (!jsonData) {
  104. jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
  105. if (jsonData) {
  106. RCTLogWarn(@"RCTJSONParse received the following string, which could "
  107. "not be losslessly converted to UTF8 data: '%@'", jsonString);
  108. } else {
  109. NSString *errorMessage = @"RCTJSONParse received invalid UTF8 data";
  110. if (error) {
  111. *error = RCTErrorWithMessage(errorMessage);
  112. } else {
  113. RCTLogError(@"%@", errorMessage);
  114. }
  115. return nil;
  116. }
  117. }
  118. NSJSONReadingOptions options = NSJSONReadingAllowFragments;
  119. if (mutable) {
  120. options |= NSJSONReadingMutableContainers;
  121. }
  122. return [NSJSONSerialization JSONObjectWithData:jsonData
  123. options:options
  124. error:error];
  125. }
  126. return nil;
  127. }
  128. id __nullable RCTJSONParse(NSString *__nullable jsonString, NSError **error)
  129. {
  130. return _RCTJSONParse(jsonString, NO, error);
  131. }
  132. id __nullable RCTJSONParseMutable(NSString *__nullable jsonString, NSError **error)
  133. {
  134. return _RCTJSONParse(jsonString, YES, error);
  135. }
  136. id RCTJSONClean(id object)
  137. {
  138. static dispatch_once_t onceToken;
  139. static NSSet<Class> *validLeafTypes;
  140. dispatch_once(&onceToken, ^{
  141. validLeafTypes = [[NSSet alloc] initWithArray:@[
  142. [NSString class],
  143. [NSMutableString class],
  144. [NSNumber class],
  145. [NSNull class],
  146. ]];
  147. });
  148. if ([validLeafTypes containsObject:[object classForCoder]]) {
  149. if ([object isKindOfClass:[NSNumber class]]) {
  150. return @(RCTZeroIfNaN([object doubleValue]));
  151. }
  152. if ([object isKindOfClass:[NSString class]]) {
  153. if ([object UTF8String] == NULL) {
  154. return (id)kCFNull;
  155. }
  156. }
  157. return object;
  158. }
  159. if ([object isKindOfClass:[NSDictionary class]]) {
  160. __block BOOL copy = NO;
  161. NSMutableDictionary<NSString *, id> *values = [[NSMutableDictionary alloc] initWithCapacity:[object count]];
  162. [object enumerateKeysAndObjectsUsingBlock:^(NSString *key, id item, __unused BOOL *stop) {
  163. id value = RCTJSONClean(item);
  164. values[key] = value;
  165. copy |= value != item;
  166. }];
  167. return copy ? values : object;
  168. }
  169. if ([object isKindOfClass:[NSArray class]]) {
  170. __block BOOL copy = NO;
  171. __block NSArray *values = object;
  172. [object enumerateObjectsUsingBlock:^(id item, NSUInteger idx, __unused BOOL *stop) {
  173. id value = RCTJSONClean(item);
  174. if (copy) {
  175. [(NSMutableArray *)values addObject:value];
  176. } else if (value != item) {
  177. // Converted value is different, so we'll need to copy the array
  178. values = [[NSMutableArray alloc] initWithCapacity:values.count];
  179. for (NSUInteger i = 0; i < idx; i++) {
  180. [(NSMutableArray *)values addObject:object[i]];
  181. }
  182. [(NSMutableArray *)values addObject:value];
  183. copy = YES;
  184. }
  185. }];
  186. return values;
  187. }
  188. return (id)kCFNull;
  189. }
  190. NSString *RCTMD5Hash(NSString *string)
  191. {
  192. const char *str = string.UTF8String;
  193. unsigned char result[CC_MD5_DIGEST_LENGTH];
  194. CC_MD5(str, (CC_LONG)strlen(str), result);
  195. return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  196. result[0], result[1], result[2], result[3],
  197. result[4], result[5], result[6], result[7],
  198. result[8], result[9], result[10], result[11],
  199. result[12], result[13], result[14], result[15]
  200. ];
  201. }
  202. BOOL RCTIsMainQueue()
  203. {
  204. static void *mainQueueKey = &mainQueueKey;
  205. static dispatch_once_t onceToken;
  206. dispatch_once(&onceToken, ^{
  207. dispatch_queue_set_specific(dispatch_get_main_queue(),
  208. mainQueueKey, mainQueueKey, NULL);
  209. });
  210. return dispatch_get_specific(mainQueueKey) == mainQueueKey;
  211. }
  212. void RCTExecuteOnMainQueue(dispatch_block_t block)
  213. {
  214. if (RCTIsMainQueue()) {
  215. block();
  216. } else {
  217. dispatch_async(dispatch_get_main_queue(), ^{
  218. block();
  219. });
  220. }
  221. }
  222. // Please do not use this method
  223. // unless you know what you are doing.
  224. void RCTUnsafeExecuteOnMainQueueSync(dispatch_block_t block)
  225. {
  226. if (RCTIsMainQueue()) {
  227. block();
  228. } else {
  229. dispatch_sync(dispatch_get_main_queue(), ^{
  230. block();
  231. });
  232. }
  233. }
  234. static void RCTUnsafeExecuteOnMainQueueOnceSync(dispatch_once_t *onceToken, dispatch_block_t block)
  235. {
  236. // The solution was borrowed from a post by Ben Alpert:
  237. // https://benalpert.com/2014/04/02/dispatch-once-initialization-on-the-main-thread.html
  238. // See also: https://www.mikeash.com/pyblog/friday-qa-2014-06-06-secrets-of-dispatch_once.html
  239. if (RCTIsMainQueue()) {
  240. dispatch_once(onceToken, block);
  241. } else {
  242. if (DISPATCH_EXPECT(*onceToken == 0L, NO)) {
  243. dispatch_sync(dispatch_get_main_queue(), ^{
  244. dispatch_once(onceToken, block);
  245. });
  246. }
  247. }
  248. }
  249. CGFloat RCTScreenScale()
  250. {
  251. static dispatch_once_t onceToken;
  252. static CGFloat scale;
  253. RCTUnsafeExecuteOnMainQueueOnceSync(&onceToken, ^{
  254. scale = [UIScreen mainScreen].scale;
  255. });
  256. return scale;
  257. }
  258. CGSize RCTScreenSize()
  259. {
  260. // FIXME: this caches the bounds at app start, whatever those were, and then
  261. // doesn't update when the device is rotated. We need to find another thread-
  262. // safe way to get the screen size.
  263. static CGSize size;
  264. static dispatch_once_t onceToken;
  265. dispatch_once(&onceToken, ^{
  266. RCTUnsafeExecuteOnMainQueueSync(^{
  267. size = [UIScreen mainScreen].bounds.size;
  268. });
  269. });
  270. return size;
  271. }
  272. CGFloat RCTRoundPixelValue(CGFloat value)
  273. {
  274. CGFloat scale = RCTScreenScale();
  275. return round(value * scale) / scale;
  276. }
  277. CGFloat RCTCeilPixelValue(CGFloat value)
  278. {
  279. CGFloat scale = RCTScreenScale();
  280. return ceil(value * scale) / scale;
  281. }
  282. CGFloat RCTFloorPixelValue(CGFloat value)
  283. {
  284. CGFloat scale = RCTScreenScale();
  285. return floor(value * scale) / scale;
  286. }
  287. CGSize RCTSizeInPixels(CGSize pointSize, CGFloat scale)
  288. {
  289. return (CGSize){
  290. ceil(pointSize.width * scale),
  291. ceil(pointSize.height * scale),
  292. };
  293. }
  294. void RCTSwapClassMethods(Class cls, SEL original, SEL replacement)
  295. {
  296. Method originalMethod = class_getClassMethod(cls, original);
  297. IMP originalImplementation = method_getImplementation(originalMethod);
  298. const char *originalArgTypes = method_getTypeEncoding(originalMethod);
  299. Method replacementMethod = class_getClassMethod(cls, replacement);
  300. IMP replacementImplementation = method_getImplementation(replacementMethod);
  301. const char *replacementArgTypes = method_getTypeEncoding(replacementMethod);
  302. if (class_addMethod(cls, original, replacementImplementation, replacementArgTypes)) {
  303. class_replaceMethod(cls, replacement, originalImplementation, originalArgTypes);
  304. } else {
  305. method_exchangeImplementations(originalMethod, replacementMethod);
  306. }
  307. }
  308. void RCTSwapInstanceMethods(Class cls, SEL original, SEL replacement)
  309. {
  310. Method originalMethod = class_getInstanceMethod(cls, original);
  311. IMP originalImplementation = method_getImplementation(originalMethod);
  312. const char *originalArgTypes = method_getTypeEncoding(originalMethod);
  313. Method replacementMethod = class_getInstanceMethod(cls, replacement);
  314. IMP replacementImplementation = method_getImplementation(replacementMethod);
  315. const char *replacementArgTypes = method_getTypeEncoding(replacementMethod);
  316. if (class_addMethod(cls, original, replacementImplementation, replacementArgTypes)) {
  317. class_replaceMethod(cls, replacement, originalImplementation, originalArgTypes);
  318. } else {
  319. method_exchangeImplementations(originalMethod, replacementMethod);
  320. }
  321. }
  322. BOOL RCTClassOverridesClassMethod(Class cls, SEL selector)
  323. {
  324. return RCTClassOverridesInstanceMethod(object_getClass(cls), selector);
  325. }
  326. BOOL RCTClassOverridesInstanceMethod(Class cls, SEL selector)
  327. {
  328. unsigned int numberOfMethods;
  329. Method *methods = class_copyMethodList(cls, &numberOfMethods);
  330. for (unsigned int i = 0; i < numberOfMethods; i++) {
  331. if (method_getName(methods[i]) == selector) {
  332. free(methods);
  333. return YES;
  334. }
  335. }
  336. free(methods);
  337. return NO;
  338. }
  339. NSDictionary<NSString *, id> *RCTMakeError(NSString *message,
  340. id __nullable toStringify,
  341. NSDictionary<NSString *, id> *__nullable extraData)
  342. {
  343. if (toStringify) {
  344. message = [message stringByAppendingString:[toStringify description]];
  345. }
  346. NSMutableDictionary<NSString *, id> *error = [extraData mutableCopy] ?: [NSMutableDictionary new];
  347. error[@"message"] = message;
  348. return error;
  349. }
  350. NSDictionary<NSString *, id> *RCTMakeAndLogError(NSString *message,
  351. id __nullable toStringify,
  352. NSDictionary<NSString *, id> *__nullable extraData)
  353. {
  354. NSDictionary<NSString *, id> *error = RCTMakeError(message, toStringify, extraData);
  355. RCTLogError(@"\nError: %@", error);
  356. return error;
  357. }
  358. NSDictionary<NSString *, id> *RCTJSErrorFromNSError(NSError *error)
  359. {
  360. NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%lld", error.domain.uppercaseString, (long long)error.code];
  361. return RCTJSErrorFromCodeMessageAndNSError(codeWithDomain,
  362. error.localizedDescription,
  363. error);
  364. }
  365. // TODO: Can we just replace RCTMakeError with this function instead?
  366. NSDictionary<NSString *, id> *RCTJSErrorFromCodeMessageAndNSError(NSString *code,
  367. NSString *message,
  368. NSError *__nullable error)
  369. {
  370. NSString *errorMessage;
  371. NSArray<NSString *> *stackTrace = [NSThread callStackSymbols];
  372. NSMutableDictionary *userInfo;
  373. NSMutableDictionary<NSString *, id> *errorInfo =
  374. [NSMutableDictionary dictionaryWithObject:stackTrace forKey:@"nativeStackIOS"];
  375. if (error) {
  376. errorMessage = error.localizedDescription ?: @"Unknown error from a native module";
  377. errorInfo[@"domain"] = error.domain ?: RCTErrorDomain;
  378. if (error.userInfo) {
  379. userInfo = [error.userInfo mutableCopy];
  380. if (userInfo != nil && userInfo[NSUnderlyingErrorKey] != nil) {
  381. NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey];
  382. NSString *underlyingCode = [NSString stringWithFormat:@"%d", (int)underlyingError.code];
  383. userInfo[NSUnderlyingErrorKey] = RCTJSErrorFromCodeMessageAndNSError(underlyingCode, @"underlying error", underlyingError);
  384. }
  385. }
  386. } else {
  387. errorMessage = @"Unknown error from a native module";
  388. errorInfo[@"domain"] = RCTErrorDomain;
  389. userInfo = nil;
  390. }
  391. errorInfo[@"code"] = code ?: RCTErrorUnspecified;
  392. errorInfo[@"userInfo"] = RCTNullIfNil(userInfo);
  393. // Allow for explicit overriding of the error message
  394. errorMessage = message ?: errorMessage;
  395. return RCTMakeError(errorMessage, nil, errorInfo);
  396. }
  397. BOOL RCTRunningInTestEnvironment(void)
  398. {
  399. static BOOL isTestEnvironment = NO;
  400. static dispatch_once_t onceToken;
  401. dispatch_once(&onceToken, ^{
  402. NSDictionary *environment = [[NSProcessInfo processInfo] environment];
  403. isTestEnvironment = objc_lookUpClass("SenTestCase") ||
  404. objc_lookUpClass("XCTest") ||
  405. objc_lookUpClass("SnapshotTestAppDelegate") ||
  406. [environment[@"IS_TESTING"] boolValue];
  407. });
  408. return isTestEnvironment;
  409. }
  410. BOOL RCTRunningInAppExtension(void)
  411. {
  412. return [[[[NSBundle mainBundle] bundlePath] pathExtension] isEqualToString:@"appex"];
  413. }
  414. UIApplication *__nullable RCTSharedApplication(void)
  415. {
  416. if (RCTRunningInAppExtension()) {
  417. return nil;
  418. }
  419. return [[UIApplication class] performSelector:@selector(sharedApplication)];
  420. }
  421. UIWindow *__nullable RCTKeyWindow(void)
  422. {
  423. if (RCTRunningInAppExtension()) {
  424. return nil;
  425. }
  426. // TODO: replace with a more robust solution
  427. return RCTSharedApplication().keyWindow;
  428. }
  429. UIViewController *__nullable RCTPresentedViewController(void)
  430. {
  431. if (RCTRunningInAppExtension()) {
  432. return nil;
  433. }
  434. UIViewController *controller = RCTKeyWindow().rootViewController;
  435. UIViewController *presentedController = controller.presentedViewController;
  436. while (presentedController && ![presentedController isBeingDismissed]) {
  437. controller = presentedController;
  438. presentedController = controller.presentedViewController;
  439. }
  440. return controller;
  441. }
  442. BOOL RCTForceTouchAvailable(void)
  443. {
  444. static BOOL forceSupported;
  445. static dispatch_once_t onceToken;
  446. dispatch_once(&onceToken, ^{
  447. forceSupported = [UITraitCollection class] &&
  448. [UITraitCollection instancesRespondToSelector:@selector(forceTouchCapability)];
  449. });
  450. return forceSupported &&
  451. (RCTKeyWindow() ?: [UIView new]).traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable;
  452. }
  453. NSError *RCTErrorWithMessage(NSString *message)
  454. {
  455. NSDictionary<NSString *, id> *errorInfo = @{NSLocalizedDescriptionKey: message};
  456. return [[NSError alloc] initWithDomain:RCTErrorDomain code:0 userInfo:errorInfo];
  457. }
  458. double RCTZeroIfNaN(double value)
  459. {
  460. return isnan(value) || isinf(value) ? 0 : value;
  461. }
  462. double RCTSanitizeNaNValue(double value, NSString *property)
  463. {
  464. if (!isnan(value) && !isinf(value)) {
  465. return value;
  466. }
  467. RCTLogWarn(@"The value `%@` equals NaN or INF and will be replaced by `0`.", property);
  468. return 0;
  469. }
  470. NSURL *RCTDataURL(NSString *mimeType, NSData *data)
  471. {
  472. return [NSURL URLWithString:
  473. [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
  474. [data base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]]];
  475. }
  476. BOOL RCTIsGzippedData(NSData *__nullable); // exposed for unit testing purposes
  477. BOOL RCTIsGzippedData(NSData *__nullable data)
  478. {
  479. UInt8 *bytes = (UInt8 *)data.bytes;
  480. return (data.length >= 2 && bytes[0] == 0x1f && bytes[1] == 0x8b);
  481. }
  482. NSData *__nullable RCTGzipData(NSData *__nullable input, float level)
  483. {
  484. if (input.length == 0 || RCTIsGzippedData(input)) {
  485. return input;
  486. }
  487. void *libz = dlopen("/usr/lib/libz.dylib", RTLD_LAZY);
  488. int (*deflateInit2_)(z_streamp, int, int, int, int, int, const char *, int) = dlsym(libz, "deflateInit2_");
  489. int (*deflate)(z_streamp, int) = dlsym(libz, "deflate");
  490. int (*deflateEnd)(z_streamp) = dlsym(libz, "deflateEnd");
  491. z_stream stream;
  492. stream.zalloc = Z_NULL;
  493. stream.zfree = Z_NULL;
  494. stream.opaque = Z_NULL;
  495. stream.avail_in = (uint)input.length;
  496. stream.next_in = (Bytef *)input.bytes;
  497. stream.total_out = 0;
  498. stream.avail_out = 0;
  499. static const NSUInteger RCTGZipChunkSize = 16384;
  500. NSMutableData *output = nil;
  501. int compression = (level < 0.0f)? Z_DEFAULT_COMPRESSION: (int)(roundf(level * 9));
  502. if (deflateInit2(&stream, compression, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK) {
  503. output = [NSMutableData dataWithLength:RCTGZipChunkSize];
  504. while (stream.avail_out == 0) {
  505. if (stream.total_out >= output.length) {
  506. output.length += RCTGZipChunkSize;
  507. }
  508. stream.next_out = (uint8_t *)output.mutableBytes + stream.total_out;
  509. stream.avail_out = (uInt)(output.length - stream.total_out);
  510. deflate(&stream, Z_FINISH);
  511. }
  512. deflateEnd(&stream);
  513. output.length = stream.total_out;
  514. }
  515. dlclose(libz);
  516. return output;
  517. }
  518. static NSString *RCTRelativePathForURL(NSString *basePath, NSURL *__nullable URL)
  519. {
  520. if (!URL.fileURL) {
  521. // Not a file path
  522. return nil;
  523. }
  524. NSString *path = [NSString stringWithUTF8String:[URL fileSystemRepresentation]];
  525. if (![path hasPrefix:basePath]) {
  526. // Not a bundle-relative file
  527. return nil;
  528. }
  529. path = [path substringFromIndex:basePath.length];
  530. if ([path hasPrefix:@"/"]) {
  531. path = [path substringFromIndex:1];
  532. }
  533. return path;
  534. }
  535. NSString *__nullable RCTLibraryPath(void)
  536. {
  537. static NSString *libraryPath = nil;
  538. static dispatch_once_t onceToken;
  539. dispatch_once(&onceToken, ^{
  540. libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
  541. });
  542. return libraryPath;
  543. }
  544. NSString *__nullable RCTBundlePathForURL(NSURL *__nullable URL)
  545. {
  546. return RCTRelativePathForURL([[NSBundle mainBundle] resourcePath], URL);
  547. }
  548. NSString *__nullable RCTLibraryPathForURL(NSURL *__nullable URL)
  549. {
  550. return RCTRelativePathForURL(RCTLibraryPath(), URL);
  551. }
  552. static BOOL RCTIsImageAssetsPath(NSString *path)
  553. {
  554. NSString *extension = [path pathExtension];
  555. return [extension isEqualToString:@"png"] || [extension isEqualToString:@"jpg"];
  556. }
  557. BOOL RCTIsBundleAssetURL(NSURL *__nullable imageURL)
  558. {
  559. return RCTIsImageAssetsPath(RCTBundlePathForURL(imageURL));
  560. }
  561. BOOL RCTIsLibraryAssetURL(NSURL *__nullable imageURL)
  562. {
  563. return RCTIsImageAssetsPath(RCTLibraryPathForURL(imageURL));
  564. }
  565. BOOL RCTIsLocalAssetURL(NSURL *__nullable imageURL)
  566. {
  567. return RCTIsBundleAssetURL(imageURL) || RCTIsLibraryAssetURL(imageURL);
  568. }
  569. static NSString *bundleName(NSBundle *bundle)
  570. {
  571. NSString *name = bundle.infoDictionary[@"CFBundleName"];
  572. if (!name) {
  573. name = [[bundle.bundlePath lastPathComponent] stringByDeletingPathExtension];
  574. }
  575. return name;
  576. }
  577. static NSBundle *bundleForPath(NSString *key)
  578. {
  579. static NSMutableDictionary *bundleCache;
  580. if (!bundleCache) {
  581. bundleCache = [NSMutableDictionary new];
  582. bundleCache[@"main"] = [NSBundle mainBundle];
  583. // Initialize every bundle in the array
  584. for (NSString *path in [[NSBundle mainBundle] pathsForResourcesOfType:@"bundle" inDirectory:nil]) {
  585. [NSBundle bundleWithPath:path];
  586. }
  587. // The bundles initialized above will now also be in `allBundles`
  588. for (NSBundle *bundle in [NSBundle allBundles]) {
  589. bundleCache[bundleName(bundle)] = bundle;
  590. }
  591. }
  592. return bundleCache[key];
  593. }
  594. UIImage *__nullable RCTImageFromLocalAssetURL(NSURL *imageURL)
  595. {
  596. NSString *imageName = RCTBundlePathForURL(imageURL);
  597. NSBundle *bundle = nil;
  598. NSArray *imagePathComponents = [imageName pathComponents];
  599. if ([imagePathComponents count] > 1 &&
  600. [[[imagePathComponents firstObject] pathExtension] isEqualToString:@"bundle"]) {
  601. NSString *bundlePath = [imagePathComponents firstObject];
  602. bundle = bundleForPath([bundlePath stringByDeletingPathExtension]);
  603. imageName = [imageName substringFromIndex:(bundlePath.length + 1)];
  604. }
  605. UIImage *image = nil;
  606. if (bundle) {
  607. image = [UIImage imageNamed:imageName inBundle:bundle compatibleWithTraitCollection:nil];
  608. } else {
  609. image = [UIImage imageNamed:imageName];
  610. }
  611. if (!image) {
  612. // Attempt to load from the file system
  613. NSString *filePath = [NSString stringWithUTF8String:[imageURL fileSystemRepresentation]];
  614. if (filePath.pathExtension.length == 0) {
  615. filePath = [filePath stringByAppendingPathExtension:@"png"];
  616. }
  617. image = [UIImage imageWithContentsOfFile:filePath];
  618. }
  619. if (!image && !bundle) {
  620. // We did not find the image in the mainBundle, check in other shipped frameworks.
  621. NSArray<NSURL *> *possibleFrameworks = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[[NSBundle mainBundle] privateFrameworksURL]
  622. includingPropertiesForKeys:@[]
  623. options:0
  624. error:nil];
  625. for (NSURL *frameworkURL in possibleFrameworks) {
  626. bundle = [NSBundle bundleWithURL:frameworkURL];
  627. image = [UIImage imageNamed:imageName inBundle:bundle compatibleWithTraitCollection:nil];
  628. if (image) {
  629. RCTLogWarn(@"Image %@ not found in mainBundle, but found in %@", imageName, bundle);
  630. break;
  631. }
  632. }
  633. }
  634. return image;
  635. }
  636. RCT_EXTERN NSString *__nullable RCTTempFilePath(NSString *extension, NSError **error)
  637. {
  638. static NSError *setupError = nil;
  639. static NSString *directory;
  640. static dispatch_once_t onceToken;
  641. dispatch_once(&onceToken, ^{
  642. directory = [NSTemporaryDirectory() stringByAppendingPathComponent:@"ReactNative"];
  643. // If the temporary directory already exists, we'll delete it to ensure
  644. // that temp files from the previous run have all been deleted. This is not
  645. // a security measure, it simply prevents the temp directory from using too
  646. // much space, as the circumstances under which iOS clears it automatically
  647. // are not well-defined.
  648. NSFileManager *fileManager = [NSFileManager new];
  649. if ([fileManager fileExistsAtPath:directory]) {
  650. [fileManager removeItemAtPath:directory error:NULL];
  651. }
  652. if (![fileManager fileExistsAtPath:directory]) {
  653. NSError *localError = nil;
  654. if (![fileManager createDirectoryAtPath:directory
  655. withIntermediateDirectories:YES
  656. attributes:nil
  657. error:&localError]) {
  658. // This is bad
  659. RCTLogError(@"Failed to create temporary directory: %@", localError);
  660. setupError = localError;
  661. directory = nil;
  662. }
  663. }
  664. });
  665. if (!directory || setupError) {
  666. if (error) {
  667. *error = setupError;
  668. }
  669. return nil;
  670. }
  671. // Append a unique filename
  672. NSString *filename = [NSUUID new].UUIDString;
  673. if (extension) {
  674. filename = [filename stringByAppendingPathExtension:extension];
  675. }
  676. return [directory stringByAppendingPathComponent:filename];
  677. }
  678. static void RCTGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4])
  679. {
  680. CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
  681. const CGFloat *components = CGColorGetComponents(color);
  682. switch (model)
  683. {
  684. case kCGColorSpaceModelMonochrome:
  685. {
  686. rgba[0] = components[0];
  687. rgba[1] = components[0];
  688. rgba[2] = components[0];
  689. rgba[3] = components[1];
  690. break;
  691. }
  692. case kCGColorSpaceModelRGB:
  693. {
  694. rgba[0] = components[0];
  695. rgba[1] = components[1];
  696. rgba[2] = components[2];
  697. rgba[3] = components[3];
  698. break;
  699. }
  700. case kCGColorSpaceModelCMYK:
  701. case kCGColorSpaceModelDeviceN:
  702. case kCGColorSpaceModelIndexed:
  703. case kCGColorSpaceModelLab:
  704. case kCGColorSpaceModelPattern:
  705. case kCGColorSpaceModelUnknown:
  706. // TODO: kCGColorSpaceModelXYZ should be added sometime after Xcode 10 release.
  707. default:
  708. {
  709. #if RCT_DEBUG
  710. //unsupported format
  711. RCTLogError(@"Unsupported color model: %i", model);
  712. #endif
  713. rgba[0] = 0.0;
  714. rgba[1] = 0.0;
  715. rgba[2] = 0.0;
  716. rgba[3] = 1.0;
  717. break;
  718. }
  719. }
  720. }
  721. NSString *RCTColorToHexString(CGColorRef color)
  722. {
  723. CGFloat rgba[4];
  724. RCTGetRGBAColorComponents(color, rgba);
  725. uint8_t r = rgba[0]*255;
  726. uint8_t g = rgba[1]*255;
  727. uint8_t b = rgba[2]*255;
  728. uint8_t a = rgba[3]*255;
  729. if (a < 255) {
  730. return [NSString stringWithFormat:@"#%02x%02x%02x%02x", r, g, b, a];
  731. } else {
  732. return [NSString stringWithFormat:@"#%02x%02x%02x", r, g, b];
  733. }
  734. }
  735. // (https://github.com/0xced/XCDFormInputAccessoryView/blob/master/XCDFormInputAccessoryView/XCDFormInputAccessoryView.m#L10-L14)
  736. NSString *RCTUIKitLocalizedString(NSString *string)
  737. {
  738. NSBundle *UIKitBundle = [NSBundle bundleForClass:[UIApplication class]];
  739. return UIKitBundle ? [UIKitBundle localizedStringForKey:string value:string table:nil] : string;
  740. }
  741. NSString *__nullable RCTGetURLQueryParam(NSURL *__nullable URL, NSString *param)
  742. {
  743. RCTAssertParam(param);
  744. if (!URL) {
  745. return nil;
  746. }
  747. NSURLComponents *components = [NSURLComponents componentsWithURL:URL
  748. resolvingAgainstBaseURL:YES];
  749. for (NSURLQueryItem *queryItem in [components.queryItems reverseObjectEnumerator]) {
  750. if ([queryItem.name isEqualToString:param]) {
  751. return queryItem.value;
  752. }
  753. }
  754. return nil;
  755. }
  756. NSURL *__nullable RCTURLByReplacingQueryParam(NSURL *__nullable URL, NSString *param, NSString *__nullable value)
  757. {
  758. RCTAssertParam(param);
  759. if (!URL) {
  760. return nil;
  761. }
  762. NSURLComponents *components = [NSURLComponents componentsWithURL:URL
  763. resolvingAgainstBaseURL:YES];
  764. __block NSInteger paramIndex = NSNotFound;
  765. NSMutableArray<NSURLQueryItem *> *queryItems = [components.queryItems mutableCopy];
  766. [queryItems enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:
  767. ^(NSURLQueryItem *item, NSUInteger i, BOOL *stop) {
  768. if ([item.name isEqualToString:param]) {
  769. paramIndex = i;
  770. *stop = YES;
  771. }
  772. }];
  773. if (!value) {
  774. if (paramIndex != NSNotFound) {
  775. [queryItems removeObjectAtIndex:paramIndex];
  776. }
  777. } else {
  778. NSURLQueryItem *newItem = [NSURLQueryItem queryItemWithName:param
  779. value:value];
  780. if (paramIndex == NSNotFound) {
  781. [queryItems addObject:newItem];
  782. } else {
  783. [queryItems replaceObjectAtIndex:paramIndex withObject:newItem];
  784. }
  785. }
  786. components.queryItems = queryItems;
  787. return components.URL;
  788. }
  789. RCT_EXTERN NSString *RCTDropReactPrefixes(NSString *s)
  790. {
  791. if ([s hasPrefix:@"RK"]) {
  792. return [s substringFromIndex:2];
  793. } else if ([s hasPrefix:@"RCT"]) {
  794. return [s substringFromIndex:3];
  795. }
  796. return s;
  797. }