WXUtility.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. #import <Foundation/Foundation.h>
  20. #import <UIKit/UIKit.h>
  21. #import "WXDefine.h"
  22. #import "WXType.h"
  23. #import "WXLog.h"
  24. #import "WXSDKInstance.h"
  25. // The default screen width which helps us to calculate the real size or scale in different devices.
  26. static const CGFloat WXDefaultScreenWidth = 750.0;
  27. #define WX_ENUMBER_CASE(_invoke, idx, code, obj, _type, op, _flist) \
  28. case code:{\
  29. _type *_tmp = malloc(sizeof(_type));\
  30. memset(_tmp, 0, sizeof(_type));\
  31. *_tmp = [obj op];\
  32. [_invoke setArgument:_tmp atIndex:(idx) + 2];\
  33. *(_flist + idx) = _tmp;\
  34. break;\
  35. }
  36. #define WX_EPCHAR_CASE(_invoke, idx, code, obj, _type, op, _flist) \
  37. case code:{\
  38. _type *_tmp = (_type *)[obj op];\
  39. [_invoke setArgument:&_tmp atIndex:(idx) + 2];\
  40. *(_flist + idx) = 0;\
  41. break;\
  42. }\
  43. #define WX_ALLOC_FLIST(_ppFree, _count) \
  44. do {\
  45. _ppFree = (void *)malloc(sizeof(void *) * (_count));\
  46. memset(_ppFree, 0, sizeof(void *) * (_count));\
  47. } while(0)
  48. #define WX_FREE_FLIST(_ppFree, _count) \
  49. do {\
  50. for(int i = 0; i < _count; i++){\
  51. if(*(_ppFree + i ) != 0) {\
  52. free(*(_ppFree + i));\
  53. }\
  54. }\
  55. free(_ppFree);\
  56. }while(0)
  57. #define WX_ARGUMENTS_SET(_invocation, _sig, idx, _obj, _ppFree) \
  58. do {\
  59. const char *encode = [_sig getArgumentTypeAtIndex:(idx) + 2];\
  60. switch(encode[0]){\
  61. WX_EPCHAR_CASE(_invocation, idx, _C_CHARPTR, _obj, char *, UTF8String, _ppFree)\
  62. WX_ENUMBER_CASE(_invocation, idx, _C_INT, _obj, int, intValue, _ppFree)\
  63. WX_ENUMBER_CASE(_invocation, idx, _C_SHT, _obj, short, shortValue, _ppFree)\
  64. WX_ENUMBER_CASE(_invocation, idx, _C_LNG, _obj, long, longValue, _ppFree)\
  65. WX_ENUMBER_CASE(_invocation, idx, _C_LNG_LNG, _obj, long long, longLongValue, _ppFree)\
  66. WX_ENUMBER_CASE(_invocation, idx, _C_UCHR, _obj, unsigned char, unsignedCharValue, _ppFree)\
  67. WX_ENUMBER_CASE(_invocation, idx, _C_UINT, _obj, unsigned int, unsignedIntValue, _ppFree)\
  68. WX_ENUMBER_CASE(_invocation, idx, _C_USHT, _obj, unsigned short, unsignedShortValue, _ppFree)\
  69. WX_ENUMBER_CASE(_invocation, idx, _C_ULNG, _obj, unsigned long, unsignedLongValue, _ppFree)\
  70. WX_ENUMBER_CASE(_invocation, idx, _C_ULNG_LNG, _obj,unsigned long long, unsignedLongLongValue, _ppFree)\
  71. WX_ENUMBER_CASE(_invocation, idx, _C_FLT, _obj, float, floatValue, _ppFree)\
  72. WX_ENUMBER_CASE(_invocation, idx, _C_DBL, _obj, double, doubleValue, _ppFree)\
  73. WX_ENUMBER_CASE(_invocation, idx, _C_BOOL, _obj, bool, boolValue, _ppFree)\
  74. default: { [_invocation setArgument:&_obj atIndex:(idx) + 2]; *(_ppFree + idx) = 0; break;}\
  75. }\
  76. }while(0)
  77. #ifdef __cplusplus
  78. extern "C" {
  79. #endif
  80. /**
  81. * @abstract execute asynchronous action block on the main thread.
  82. *
  83. */
  84. void WXPerformBlockOnMainThread( void (^ _Nonnull block)(void));
  85. /**
  86. * @abstract execute synchronous action block on the main thread.
  87. *
  88. */
  89. void WXPerformBlockSyncOnMainThread( void (^ _Nonnull block)(void));
  90. /**
  91. * @abstract execute action block on the specific thread.
  92. *
  93. */
  94. void WXPerformBlockOnThread(void (^ _Nonnull block)(void), NSThread *_Nonnull thread);
  95. /**
  96. * @abstract swizzling methods.
  97. *
  98. */
  99. void WXSwizzleInstanceMethod(_Nonnull Class className, _Nonnull SEL original, _Nonnull SEL replaced);
  100. void WXSwizzleInstanceMethodWithBlock(_Nonnull Class className, _Nonnull SEL original, _Nonnull id block, _Nonnull SEL replaced);
  101. _Nonnull SEL WXSwizzledSelectorForSelector(_Nonnull SEL selector);
  102. #ifdef __cplusplus
  103. }
  104. #endif
  105. @interface WXUtility : NSObject
  106. + (void)performBlock:(void (^_Nonnull)(void))block onThread:(NSThread *_Nonnull)thread;
  107. /**
  108. * @abstract Returns the environment of current application, you can get some necessary properties such as appVersion、sdkVersion、appName etc.
  109. *
  110. * @return A dictionary object which contains these properties.
  111. *
  112. */
  113. + (NSDictionary *_Nonnull)getEnvironment;
  114. + (NSDictionary *_Nonnull)getDebugEnvironment;
  115. + (WXLayoutDirection)getEnvLayoutDirection;
  116. /**
  117. * @abstract UserAgent Generation
  118. *
  119. * @return A ua string by splicing (deviceName、appVersion、sdkVersion、externalField、screenSize)
  120. *
  121. */
  122. + (NSString *_Nonnull)userAgent;
  123. /**
  124. * @abstract JSON Decode Method
  125. *
  126. * @param json String.
  127. *
  128. * @return A json object by decoding json string.
  129. *
  130. */
  131. + (id _Nullable)objectFromJSON:(NSString * _Nonnull)json;
  132. #define WXDecodeJson(json) [WXUtility objectFromJSON:json]
  133. /**
  134. * @abstract JSON Encode Method
  135. *
  136. * @param object Object.
  137. *
  138. * @return A json string by encoding json object.
  139. *
  140. */
  141. + (NSString * _Nullable)JSONString:(id _Nonnull)object;
  142. #define WXEncodeJson(obj) [WXUtility JSONString:obj]
  143. /**
  144. * @abstract Returns a Foundation object from given JSON data. A Foundation object from the JSON data in data, or nil if an error occurs.
  145. *
  146. * @param data A data object containing JSON data.
  147. * @param error If an error occurs, upon return contains an NSError object that describes the problem.
  148. *
  149. * @return A Foundation object from the JSON data in data, or nil if an error occurs.
  150. *
  151. */
  152. + (id _Nullable)JSONObject:(NSData * _Nonnull)data error:(NSError * __nullable * __nullable)error;
  153. #define WXJSONObjectFromData(data) [WXUtility JSONObject:data error:nil]
  154. /**
  155. * @abstract JSON Object Copy Method
  156. *
  157. * @param object Object.
  158. *
  159. * @return A json object by copying.
  160. *
  161. */
  162. + (id _Nullable)copyJSONObject:(id _Nonnull)object;
  163. #define WXCopyJson(obj) [WXUtility copyJSONObject:obj]
  164. /**
  165. *
  166. * Checks if a String is whitespace, empty ("") or nil
  167. * @code
  168. * [WXUtility isBlankString: nil] = true
  169. * [WXUtility isBlankString: ""] = true
  170. * [WXUtility isBlankString: " "] = true
  171. * [WXUtility isBlankString: "bob"] = false
  172. * [WXUtility isBlankString: " bob "] = false
  173. * @endcode
  174. * @param string the String to check, may be null
  175. *
  176. * @return true if the String is null, empty or whitespace
  177. */
  178. + (BOOL)isBlankString:(NSString * _Nullable)string ;
  179. /**
  180. check a point is valid or not. A zero point is also valid
  181. @param point a point value to check
  182. @return true if point.x and point.y are all valid value for a number.
  183. */
  184. + (BOOL)isValidPoint:(CGPoint)point;
  185. /**
  186. * @abstract Returns a standard error object
  187. *
  188. * @param code code.
  189. *
  190. * @param message message.
  191. *
  192. * @return A error object type of NSError.
  193. *
  194. */
  195. + (NSError * _Nonnull)errorWithCode:(NSInteger)code message:(NSString * _Nullable)message;
  196. /**
  197. * @abstract Returns a Font Object by setting some properties such as size、weight、style and fontFamily.
  198. *
  199. * @param size font size
  200. *
  201. * @param textWeight font weight
  202. *
  203. * @param textStyle The type of WXTextStyle (Normal or Italic).
  204. *
  205. * @param fontFamily font family
  206. *
  207. * @param scaleFactor please use instance's scale factor
  208. *
  209. * @return A font object according to the above params.
  210. *
  211. */
  212. + (UIFont *_Nonnull)fontWithSize:(CGFloat)size textWeight:(CGFloat)textWeight textStyle:(WXTextStyle)textStyle fontFamily:(NSString *_Nullable)fontFamily scaleFactor:(CGFloat)scaleFactor;
  213. + (UIFont *_Nonnull)fontWithSize:(CGFloat)size textWeight:(CGFloat)textWeight textStyle:(WXTextStyle)textStyle fontFamily:(NSString *_Nullable)fontFamily scaleFactor:(CGFloat)scaleFactor useCoreText:(BOOL)useCoreText;
  214. /**
  215. * @abstract download remote font from specified url
  216. * @param fontURL for remote font
  217. *
  218. */
  219. + (void)getIconfont:(NSURL * _Nonnull)fontURL completion:( void(^ _Nullable )(NSURL * _Nonnull url, NSError * _Nullable error)) completionBlock;
  220. /**
  221. * @abstract Returns the main screen's size when the device is in portrait mode,.
  222. */
  223. + (CGSize)portraitScreenSize;
  224. /**
  225. * @abstract Returns the default pixel scale factor
  226. * @discussion If orientation is equal to landscape, the value is caculated as follows: WXScreenSize().height / WXDefaultScreenWidth, otherwise, WXScreenSize().width / WXDefaultScreenWidth.
  227. */
  228. + (CGFloat)defaultPixelScaleFactor;
  229. #if defined __cplusplus
  230. extern "C" {
  231. #endif
  232. /**
  233. * @abstract Returns the scale of the main screen.
  234. *
  235. */
  236. CGFloat WXScreenScale(void);
  237. /**
  238. * @abstract Returns a Round float coordinates to the main screen pixel.
  239. *
  240. */
  241. CGFloat WXRoundPixelValue(CGFloat value);
  242. /**
  243. * @abstract Returns a Floor float coordinates to the main screen pixel.
  244. *
  245. */
  246. CGFloat WXFloorPixelValue(CGFloat value);
  247. /**
  248. * @abstract Returns a Ceil float coordinates to the main screen pixel.
  249. *
  250. */
  251. CGFloat WXCeilPixelValue(CGFloat value);
  252. #if defined __cplusplus
  253. };
  254. #endif
  255. /**
  256. * @abstract check whether the file is exist
  257. *
  258. */
  259. + (BOOL)isFileExist:(NSString * _Nonnull)filePath;
  260. /**
  261. * @abstract Returns the document directory path.
  262. *
  263. */
  264. + (NSString *_Nonnull)documentDirectory;
  265. #define WXDocumentPath [WXUtility documentDirectory]
  266. /**
  267. * @abstract Returns the system cache directory path.
  268. *
  269. */
  270. + (NSString *_Nonnull)cacheDirectory;
  271. #define WXCachePath [WXUtility cacheDirectory]
  272. /**
  273. * @abstract Returns the system library directory path.
  274. *
  275. */
  276. + (NSString *_Nonnull)libraryDirectory;
  277. #define WXLibraryPath [WXUtility libraryDirectory]
  278. /**
  279. * @abstract Returns the global cache whose size is 5M.
  280. *
  281. */
  282. + (NSCache *_Nonnull)globalCache;
  283. #define WXGlobalCache [WXUtility globalCache]
  284. + (NSURL *_Nonnull)urlByDeletingParameters:(NSURL *_Nonnull)url;
  285. /**
  286. * @abstract Returns the contents of file.
  287. *
  288. */
  289. + (NSString *_Nullable)stringWithContentsOfFile:(NSString *_Nonnull)filePath;
  290. /**
  291. * @abstract Returns md5 string.
  292. *
  293. */
  294. + (NSString *_Nullable)md5:(NSString *_Nullable)string;
  295. /**
  296. * @abstract Returns Creates a Universally Unique Identifier (UUID) string.
  297. *
  298. */
  299. + (NSString *_Nullable)uuidString;
  300. /**
  301. * @abstract convert date string with formatter yyyy-MM-dd to date.
  302. *
  303. */
  304. + (NSDate *_Nullable)dateStringToDate:(NSString *_Nullable)dateString;
  305. /**
  306. * @abstract convert time string with formatter HH:mm to date.
  307. *
  308. */
  309. + (NSDate *_Nullable)timeStringToDate:(NSString *_Nullable)timeString;
  310. /**
  311. * @abstract convert date to date string with formatter yyyy-MM-dd .
  312. *
  313. */
  314. + (NSString *_Nullable)dateToString:(NSDate *_Nullable)date;
  315. /**
  316. * @abstract convert date to time string with formatter HH:mm .
  317. *
  318. */
  319. + (NSString *_Nullable)timeToString:(NSDate *_Nullable)date;
  320. /**
  321. * @abstract get the repeat substring number of string.
  322. *
  323. */
  324. + (NSUInteger)getSubStringNumber:(NSString *_Nullable)string subString:(NSString *_Nullable)subString;
  325. /**
  326. * @abstract Returns a resized pixel which is calculated according to the WXScreenResizeRadio.
  327. *
  328. */
  329. CGFloat WXPixelScale(CGFloat value, CGFloat scaleFactor);
  330. CGFloat WXScreenResizeRadio(void) DEPRECATED_MSG_ATTRIBUTE("Use [WXUtility defaultPixelScaleFactor] instead");
  331. CGFloat WXPixelResize(CGFloat value) DEPRECATED_MSG_ATTRIBUTE("Use WXPixelScale Instead");
  332. CGRect WXPixelFrameResize(CGRect value) DEPRECATED_MSG_ATTRIBUTE("Use WXPixelScale Instead");
  333. CGPoint WXPixelPointResize(CGPoint value) DEPRECATED_MSG_ATTRIBUTE("Use WXPixelScale Instead");
  334. + (UIFont * _Nullable )fontWithSize:(CGFloat)size textWeight:(CGFloat)textWeight textStyle:(WXTextStyle)textStyle fontFamily:(NSString * _Nullable)fontFamily DEPRECATED_MSG_ATTRIBUTE("Use +[WXUtility fontWithSize:textWeight:textStyle:fontFamily:scaleFactor:]");
  335. /**
  336. @discusstion construct a gradientLayer from the colors locations, gradientType
  337. @param colors The array of UIColor objects defining the color of each gradient
  338. stop. Defaults to nil
  339. @param locations An optional array of NSNumber objects defining the location of each
  340. gradient stop as a value in the range [0,1].
  341. @param frame the layer frame
  342. @param gradientType WXGradientType value specify the gradient location
  343. @return gradient layer
  344. */
  345. + (CAGradientLayer *_Nullable)gradientLayerFromColors:(NSArray*_Nullable)colors
  346. locations:(NSArray*_Nullable)locations
  347. frame:(CGRect)frame
  348. gradientType:(WXGradientType)gradientType;
  349. /**
  350. @discusstion parse gradient-color string to a dictionary, then you can get gradientLayer from @see gradientLayerFromColors:colors:locations:frame:locations
  351. @param backgroundImage linear-gradient string like linear-gradient(to right, #a80077,rgba(200, 54, 54, 0.5))
  352. @return dictionary with endColor, startColor and gradientType value
  353. @code
  354. NSDictionary * linearGradient = [self linearGradientWithBackgroundImage:@"linear-gradient(to right, #a80077,rgba(200, 54, 54, 0.5))"];
  355. CAGradientLayer * gradientLayer = [self gradientLayerFromColors:@[linearGradient[@"startColor"], linearGradient[@"endColor"]],nil,bounds,[linearGradient[@"gradientType"] integerValue]];
  356. @endcode
  357. */
  358. + (NSDictionary *_Nullable)linearGradientWithBackgroundImage:(NSString *_Nullable)backgroundImage;
  359. #if defined __cplusplus
  360. extern "C" {
  361. #endif
  362. /**
  363. * @abstract compare float a and b, if a equal b, return true,or reture false.
  364. *
  365. */
  366. BOOL WXFloatEqual(CGFloat a, CGFloat b);
  367. /**
  368. * @abstract compare float a and b, user give the compare precision, if a equal b, return true,or reture false.
  369. *
  370. */
  371. BOOL WXFloatEqualWithPrecision(CGFloat a, CGFloat b ,double precision);
  372. /**
  373. * @abstract compare float a and b, if a less than b, return true,or reture false.
  374. *
  375. */
  376. BOOL WXFloatLessThan(CGFloat a, CGFloat b);
  377. /**
  378. * @abstract compare float a and b,user give the compare precision, if a less than b,return true,or reture false.
  379. *
  380. */
  381. BOOL WXFloatLessThanWithPrecision(CGFloat a, CGFloat b,double precision);
  382. /**
  383. * @abstract compare float a and b, if a great than b, return true,or reture false.
  384. *
  385. */
  386. BOOL WXFloatGreaterThan(CGFloat a, CGFloat b);
  387. /**
  388. * @abstract compare float a and b, user give the compare precision,if a great than b, return true,or reture false.
  389. *
  390. */
  391. BOOL WXFloatGreaterThanWithPrecision(CGFloat a,CGFloat b,double precision);
  392. #if defined __cplusplus
  393. };
  394. #endif
  395. /**
  396. * @abstract convert returnKeyType to type string .
  397. *
  398. */
  399. + (NSString *_Nullable)returnKeyType:(UIReturnKeyType)type;
  400. /**
  401. * @abstract custorm monitor info
  402. *
  403. */
  404. + (void)customMonitorInfo:(WXSDKInstance *_Nullable)instance key:(NSString * _Nonnull)key value:(id _Nonnull)value;
  405. /**
  406. * @abstract format to base64 dictionary
  407. *
  408. */
  409. + (NSDictionary *_Nonnull)dataToBase64Dict:(NSData *_Nullable)data;
  410. /**
  411. * @abstract format to data
  412. *
  413. */
  414. + (NSData *_Nonnull)base64DictToData:(NSDictionary *_Nullable)base64Dict;
  415. + (void)setUnregisterFontWhenCollision:(BOOL)value;
  416. + (void)setUseJSCApiForCreateInstance:(BOOL)value;
  417. + (BOOL)useJSCApiForCreateInstance;
  418. + (void)setEnableRTLLayoutDirection:(BOOL)value;
  419. + (BOOL)enableRTLLayoutDirection;
  420. + (long) getUnixFixTimeMillis;
  421. + (NSArray<NSString *> *_Nullable)extractPropertyNamesOfJSValueObject:(JSValue *_Nullable)jsvalue;
  422. @end