/
TiUtils.m
2193 lines (1922 loc) Β· 66.8 KB
/
TiUtils.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#import <CommonCrypto/CommonDigest.h>
#import <QuartzCore/QuartzCore.h>
#import "ImageLoader.h"
#import "TiApp.h"
#import "TiBase.h"
#import "TiBlob.h"
#import "TiColor.h"
#import "TiDimension.h"
#import "TiExceptionHandler.h"
#import "TiFile.h"
#import "TiHost.h"
#import "TiPoint.h"
#import "TiProxy.h"
#import "TiSharedConfig.h"
#import "TiUIView.h"
#import "TiUtils.h"
#import "WebFont.h"
// for checking version
#import <sys/utsname.h>
#import "UIImage+Resize.h"
static NSDictionary *encodingMap = nil;
static NSDictionary *typeMap = nil;
static NSDictionary *sizeMap = nil;
@implementation TiUtils
+ (TiOrientationFlags)TiOrientationFlagsFromObject:(id)args
{
if (![args isKindOfClass:[NSArray class]]) {
return TiOrientationNone;
}
TiOrientationFlags result = TiOrientationNone;
for (id mode in args) {
UIInterfaceOrientation orientation = (UIInterfaceOrientation)[TiUtils orientationValue:mode def:-1];
switch ((int)orientation) {
case UIDeviceOrientationPortrait:
case UIDeviceOrientationPortraitUpsideDown:
case UIDeviceOrientationLandscapeLeft:
case UIDeviceOrientationLandscapeRight:
TI_ORIENTATION_SET(result, orientation);
break;
case UIDeviceOrientationUnknown:
DebugLog(@"[WARN] Ti.Gesture.UNKNOWN / Ti.UI.UNKNOWN is an invalid orientation mode.");
break;
case UIDeviceOrientationFaceDown:
DebugLog(@"[WARN] Ti.Gesture.FACE_DOWN / Ti.UI.FACE_DOWN is an invalid orientation mode.");
break;
case UIDeviceOrientationFaceUp:
DebugLog(@"[WARN] Ti.Gesture.FACE_UP / Ti.UI.FACE_UP is an invalid orientation mode.");
break;
default:
DebugLog(@"[WARN] An invalid orientation was requested. Ignoring.");
break;
}
}
return result;
}
+ (int)dpi
{
if ([TiUtils isIPad]) {
if ([TiUtils is2xRetina]) {
return 260;
}
return 130;
} else {
if ([TiUtils is3xRetina]) {
return 480;
} else if ([TiUtils is2xRetina]) {
return 320;
}
return 160;
}
}
+ (BOOL)isRetinaFourInch
{
CGSize mainScreenBoundsSize = [[UIScreen mainScreen] bounds].size;
return (mainScreenBoundsSize.height == 568 || mainScreenBoundsSize.width == 568);
}
+ (BOOL)isRetinaiPhone6
{
return [TiUtils isRetina4_7Inch];
}
+ (BOOL)isRetinaiPhone6Plus
{
return [TiUtils isRetina5_5Inch];
}
+ (BOOL)isRetinaiPhoneX
{
return [TiUtils isSuperRetina5_8Inch];
}
+ (BOOL)isRetina4_7Inch
{
CGSize mainScreenBoundsSize = [[UIScreen mainScreen] bounds].size;
return (mainScreenBoundsSize.height == 667 || mainScreenBoundsSize.width == 667);
}
+ (BOOL)isRetina5_5Inch
{
CGSize mainScreenBoundsSize = [[UIScreen mainScreen] bounds].size;
return (mainScreenBoundsSize.height == 736 || mainScreenBoundsSize.width == 736);
}
+ (BOOL)isSuperRetina5_8Inch
{
CGSize mainScreenBoundsSize = [[UIScreen mainScreen] bounds].size;
return (mainScreenBoundsSize.height == 812 || mainScreenBoundsSize.width == 812);
}
+ (BOOL)isRetina6_1Inch
{
CGSize mainScreenBoundsSize = [[UIScreen mainScreen] bounds].size;
return (mainScreenBoundsSize.height == 896 || mainScreenBoundsSize.width == 896) && ![TiUtils is3xRetina];
}
+ (BOOL)isSuperRetina6_5Inch
{
CGSize mainScreenBoundsSize = [[UIScreen mainScreen] bounds].size;
return (mainScreenBoundsSize.height == 896 || mainScreenBoundsSize.width == 896) && [TiUtils is3xRetina];
}
+ (BOOL)is3xRetina
{
return [UIScreen mainScreen].scale == 3.0;
}
+ (BOOL)is2xRetina
{
// since we call this alot, cache it
static CGFloat scale = 0.0;
if (scale == 0.0) {
// NOTE: iPad in iPhone compatibility mode will return a scale factor of 2.0
// when in 2x zoom, which leads to false positives and bugs. This tries to
// future proof against possible different model names, but in the event of
// an iPad with a retina display, this will need to be fixed.
// Credit to Brion on github for the origional fix.
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
NSRange iPadStringPosition = [[[UIDevice currentDevice] model] rangeOfString:@"iPad"];
if (iPadStringPosition.location != NSNotFound) {
scale = 1.0;
return NO;
}
}
scale = [[UIScreen mainScreen] scale];
}
return scale > 1.0; // TODO: In the future (next major), this should be == 2.0 which is a breaking change
}
+ (BOOL)isRetinaHDDisplay
{
return [TiUtils is3xRetina];
}
+ (BOOL)isRetinaDisplay
{
return [TiUtils is2xRetina];
}
+ (BOOL)isIOS7OrGreater
{
return [TiUtils isIOSVersionOrGreater:@"7.0"];
}
+ (BOOL)isIOS8OrGreater
{
return [TiUtils isIOSVersionOrGreater:@"8.0"];
}
+ (BOOL)isIOS82rGreater
{
return [TiUtils isIOSVersionOrGreater:@"8.2"];
}
+ (BOOL)isIOS9OrGreater
{
return [TiUtils isIOSVersionOrGreater:@"9.0"];
}
+ (BOOL)isIOS9_1OrGreater
{
return [TiUtils isIOSVersionOrGreater:@"9.1"];
}
+ (BOOL)isIOS9_3OrGreater
{
return [TiUtils isIOSVersionOrGreater:@"9.3"];
}
+ (BOOL)isIOS10OrGreater
{
return [TiUtils isIOSVersionOrGreater:@"10.0"];
}
+ (BOOL)isIOS11OrGreater
{
return [TiUtils isIOSVersionOrGreater:@"11.0"];
}
+ (BOOL)isIOSVersionOrGreater:(NSString *)version
{
return [[[UIDevice currentDevice] systemVersion] compare:version options:NSNumericSearch] != NSOrderedAscending;
}
+ (BOOL)isIOSVersionLower:(NSString *)version
{
return [[[UIDevice currentDevice] systemVersion] compare:version options:NSNumericSearch] == NSOrderedAscending;
}
+ (BOOL)isIPad
{
return [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
}
+ (BOOL)isIPhone4
{
static BOOL iphoneChecked = NO;
static BOOL isiPhone4 = NO;
if (!iphoneChecked) {
iphoneChecked = YES;
// for now, this is all we know. we assume this
// will continue to increase with new models but
// for now we can't really assume
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
struct utsname u;
uname(&u);
if (!strcmp(u.machine, "iPhone3,1")) {
isiPhone4 = YES;
}
}
}
return isiPhone4;
}
+ (NSString *)UTCDateForDate:(NSDate *)data
{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
NSLocale *USLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:USLocale];
[USLocale release];
//Example UTC full format: 2009-06-15T21:46:28.685+0000
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'.'SSS+0000"];
return [dateFormatter stringFromDate:data];
}
+ (NSDate *)dateForUTCDate:(NSString *)date
{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
NSLocale *USLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:USLocale];
[USLocale release];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'.'SSS+0000"];
return [dateFormatter dateFromString:date];
}
+ (NSString *)UTCDate
{
return [TiUtils UTCDateForDate:[NSDate date]];
}
+ (NSString *)createUUID
{
CFUUIDRef resultID = CFUUIDCreate(NULL);
NSString *resultString = (NSString *)CFUUIDCreateString(NULL, resultID);
CFRelease(resultID);
return [resultString autorelease];
}
+ (TiFile *)createTempFile:(NSString *)extension
{
return [TiFile createTempFile:extension];
}
+ (NSString *)encodeQueryPart:(NSString *)unencodedString
{
return [unencodedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}
+ (NSString *)encodeURIParameters:(NSString *)unencodedString
{
// NOTE: we must encode each individual part for the to successfully work
NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
NSArray *parts = [unencodedString componentsSeparatedByString:@"&"];
for (int c = 0; c < [parts count]; c++) {
NSString *part = [parts objectAtIndex:c];
NSRange range = [part rangeOfString:@"="];
if (range.location != NSNotFound) {
[result appendString:[TiUtils encodeQueryPart:[part substringToIndex:range.location]]];
[result appendString:@"="];
[result appendString:[TiUtils encodeQueryPart:[part substringFromIndex:range.location + 1]]];
} else {
[result appendString:[TiUtils encodeQueryPart:part]];
}
if (c + 1 < [parts count]) {
[result appendString:@"&"];
}
}
return result;
}
+ (NSString *)stringValue:(id)value
{
if (value == nil) {
return nil;
}
if ([value isKindOfClass:[NSString class]]) {
return (NSString *)value;
}
if ([value isKindOfClass:[NSURL class]]) {
return [(NSURL *)value absoluteString];
} else if ([value isKindOfClass:[NSNull class]]) {
return nil;
}
if ([value respondsToSelector:@selector(stringValue)]) {
return [value stringValue];
}
return [value description];
}
+ (BOOL)boolValue:(id)value def:(BOOL)def;
{
if ([value respondsToSelector:@selector(boolValue)]) {
return [value boolValue];
}
return def;
}
+ (BOOL)boolValue:(id)value
{
return [self boolValue:value def:NO];
}
+ (double)doubleValue:(id)value
{
return [self doubleValue:value def:0];
}
+ (double)doubleValue:(id)value def:(double)def
{
return [self doubleValue:value def:def valid:NULL];
}
+ (double)doubleValue:(id)value def:(double)def valid:(BOOL *)isValid
{
if ([value respondsToSelector:@selector(doubleValue)]) {
if (isValid != NULL)
*isValid = YES;
return [value doubleValue];
}
return def;
}
+ (UIEdgeInsets)contentInsets:(id)value
{
if ([value isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict = (NSDictionary *)value;
CGFloat t = [TiUtils floatValue:@"top" properties:dict def:0];
CGFloat l = [TiUtils floatValue:@"left" properties:dict def:0];
CGFloat b = [TiUtils floatValue:@"bottom" properties:dict def:0];
CGFloat r = [TiUtils floatValue:@"right" properties:dict def:0];
return UIEdgeInsetsMake(t, l, b, r);
}
return UIEdgeInsetsMake(0, 0, 0, 0);
}
+ (CGRect)rectValue:(id)value
{
if ([value isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict = (NSDictionary *)value;
CGFloat x = [TiUtils floatValue:@"x" properties:dict def:0];
CGFloat y = [TiUtils floatValue:@"y" properties:dict def:0];
CGFloat w = [TiUtils floatValue:@"width" properties:dict def:0];
CGFloat h = [TiUtils floatValue:@"height" properties:dict def:0];
return CGRectMake(x, y, w, h);
}
return CGRectMake(0, 0, 0, 0);
}
+ (CGPoint)pointValue:(id)value
{
if ([value isKindOfClass:[TiPoint class]]) {
return [value point];
}
if ([value isKindOfClass:[NSDictionary class]]) {
return CGPointMake([[value objectForKey:@"x"] floatValue], [[value objectForKey:@"y"] floatValue]);
}
return CGPointMake(0, 0);
}
+ (CGPoint)pointValue:(id)value valid:(BOOL *)isValid
{
if ([value isKindOfClass:[TiPoint class]]) {
if (isValid) {
*isValid = YES;
}
return [value point];
} else if ([value isKindOfClass:[NSDictionary class]]) {
id xVal = [value objectForKey:@"x"];
id yVal = [value objectForKey:@"y"];
if (xVal && yVal) {
if (![xVal respondsToSelector:@selector(floatValue)] || ![yVal respondsToSelector:@selector(floatValue)]) {
if (isValid) {
*isValid = NO;
}
return CGPointMake(0.0, 0.0);
}
if (isValid) {
*isValid = YES;
}
return CGPointMake([xVal floatValue], [yVal floatValue]);
}
}
if (isValid) {
*isValid = NO;
}
return CGPointMake(0, 0);
}
+ (CGPoint)pointValue:(id)value bounds:(CGRect)bounds defaultOffset:(CGPoint)defaultOffset;
{
TiDimension xDimension;
TiDimension yDimension;
CGPoint result;
if ([value isKindOfClass:[TiPoint class]]) {
xDimension = [value xDimension];
yDimension = [value yDimension];
} else if ([value isKindOfClass:[NSDictionary class]]) {
xDimension = [self dimensionValue:@"x" properties:value];
yDimension = [self dimensionValue:@"x" properties:value];
} else {
xDimension = TiDimensionUndefined;
yDimension = TiDimensionUndefined;
}
if (!TiDimensionDidCalculateValue(xDimension, bounds.size.width, &result.x)) {
result.x = defaultOffset.x * bounds.size.width;
}
if (!TiDimensionDidCalculateValue(yDimension, bounds.size.height, &result.y)) {
result.y = defaultOffset.y * bounds.size.height;
}
return CGPointMake(result.x + bounds.origin.x, result.y + bounds.origin.y);
}
+ (NSNumber *)numberFromObject:(id)obj
{
if (obj == nil) {
return nil;
}
if ([obj isKindOfClass:[NSNumber class]]) {
return obj;
}
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
return [formatter numberFromString:[self stringValue:obj]];
}
+ (CGFloat)floatValue:(id)value def:(CGFloat)def
{
return [self floatValue:value def:def valid:NULL];
}
+ (CGFloat)floatValue:(id)value def:(CGFloat)def valid:(BOOL *)isValid
{
if ([value respondsToSelector:@selector(floatValue)]) {
if (isValid != NULL)
*isValid = YES;
return [value floatValue];
}
if (isValid != NULL) {
*isValid = NO;
}
return def;
}
+ (CGFloat)floatValue:(id)value
{
return [self floatValue:value def:NSNotFound];
}
/* Example:
shadow = {
offset: {
width: 10,
height: 10
},
blurRadius: 10,
color: 'red'
}
*/
+ (NSShadow *)shadowValue:(id)value
{
if (![value isKindOfClass:[NSDictionary class]])
return nil;
NSShadow *shadow = [[NSShadow alloc] init];
id offset = [value objectForKey:@"offset"];
if (offset != nil && [offset isKindOfClass:[NSDictionary class]]) {
id w = [offset objectForKey:@"width"];
id h = [offset objectForKey:@"height"];
[shadow setShadowOffset:CGSizeMake([TiUtils floatValue:w def:0], [TiUtils floatValue:h def:0])];
}
id blurRadius = [value objectForKey:@"blurRadius"];
if (blurRadius != nil) {
[shadow setShadowBlurRadius:[TiUtils floatValue:blurRadius def:0]];
}
id color = [value objectForKey:@"color"];
if (color != nil) {
[shadow setShadowColor:[[TiUtils colorValue:color] _color]];
}
return [shadow autorelease];
}
+ (int)intValue:(id)value def:(int)def valid:(BOOL *)isValid
{
if ([value respondsToSelector:@selector(intValue)]) {
if (isValid != NULL) {
*isValid = YES;
}
return [value intValue];
}
if (isValid != NULL) {
*isValid = NO;
}
return def;
}
+ (int)intValue:(id)value def:(int)def
{
return [self intValue:value def:def valid:NULL];
}
+ (int)intValue:(id)value
{
return [self intValue:value def:0];
}
+ (TiColor *)colorValue:(id)value
{
if ([value isKindOfClass:[TiColor class]]) {
return (TiColor *)value;
}
if ([value respondsToSelector:@selector(stringValue)]) {
value = [value stringValue];
}
if ([value isKindOfClass:[NSString class]]) {
return [TiColor colorNamed:value];
}
return nil;
}
+ (NSString *)hexColorValue:(UIColor *)color
{
const CGFloat *components = CGColorGetComponents(color.CGColor);
return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
lroundf(components[0] * 255),
lroundf(components[1] * 255),
lroundf(components[2] * 255)];
}
+ (TiDimension)dimensionValue:(id)value
{
return TiDimensionFromObject(value);
}
+ (id)valueFromDimension:(TiDimension)dimension
{
switch (dimension.type) {
case TiDimensionTypeUndefined:
return [NSNull null];
case TiDimensionTypeAuto:
return @"auto";
case TiDimensionTypeDip:
return @(dimension.value);
case TiDimensionTypePercent:
return [NSString stringWithFormat:@"%li%%", (long)(dimension.value * 100)];
default: {
break;
}
}
return nil;
}
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize
{
if (!CGSizeEqualToSize(newSize, CGSizeZero)) {
CGSize imageSize = [image size];
if (newSize.width == 0) {
newSize.width = imageSize.width;
}
if (newSize.height == 0) {
newSize.height = imageSize.height;
}
if (!CGSizeEqualToSize(newSize, imageSize)) {
image = [UIImageResize resizedImage:newSize interpolationQuality:kCGInterpolationDefault image:image hires:NO];
}
}
return image;
}
+ (UIImage *)toImage:(id)object proxy:(TiProxy *)proxy size:(CGSize)imageSize
{
if ([object isKindOfClass:[TiBlob class]]) {
return [self scaleImage:[(TiBlob *)object image] toSize:imageSize];
}
if ([object isKindOfClass:[TiFile class]]) {
TiFile *file = (TiFile *)object;
UIImage *image = [UIImage imageWithContentsOfFile:[file path]];
return [self scaleImage:image toSize:imageSize];
}
NSURL *urlAttempt = [self toURL:object proxy:proxy];
UIImage *image = [[ImageLoader sharedLoader] loadImmediateImage:urlAttempt withSize:imageSize];
return image;
//Note: If url is a nonimmediate image, this returns nil.
}
+ (UIImage *)toImage:(id)object proxy:(TiProxy *)proxy
{
if ([object isKindOfClass:[TiBlob class]]) {
return [(TiBlob *)object image];
}
if ([object isKindOfClass:[TiFile class]]) {
TiFile *file = (TiFile *)object;
UIImage *image = [UIImage imageWithContentsOfFile:[file path]];
return image;
}
NSURL *urlAttempt = [self toURL:object proxy:proxy];
UIImage *image = [[ImageLoader sharedLoader] loadImmediateImage:urlAttempt];
return image;
//Note: If url is a nonimmediate image, this returns nil.
}
+ (UIImage *)adjustRotation:(UIImage *)image
{
CGImageRef imgRef = image.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
CGFloat scaleRatio = bounds.size.width / width;
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = image.imageOrientation;
switch (orient) {
case UIImageOrientationUp: //EXIF = 1
transform = CGAffineTransformIdentity;
break;
case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;
case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;
case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
}
UIGraphicsBeginImageContext(bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
CGContextScaleCTM(context, -scaleRatio, scaleRatio);
CGContextTranslateCTM(context, -height, 0);
} else {
CGContextScaleCTM(context, scaleRatio, -scaleRatio);
CGContextTranslateCTM(context, 0, -height);
}
CGContextConcatCTM(context, transform);
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageCopy;
}
+ (NSURL *)checkFor2XImage:(NSURL *)url
{
NSString *path = nil;
if ([url isFileURL]) {
path = [url path];
}
if ([[url scheme] isEqualToString:@"app"]) { //Technically, this will have an extra /, but iOS ignores this.
path = [url resourceSpecifier];
}
NSString *ext = [path pathExtension];
if (![ext isEqualToString:@"png"] && ![ext isEqualToString:@"jpg"] && ![ext isEqualToString:@"jpeg"]) { //It's not an image.
return url;
}
NSFileManager *fm = [NSFileManager defaultManager];
NSString *partial = [path stringByDeletingPathExtension];
NSString *os = [TiUtils isIPad] ? @"~ipad" : @"~iphone";
if ([TiUtils is3xRetina]) {
if ([TiUtils isSuperRetina6_5Inch]) {
// -2688@3x iPhone XS Max specific
NSString *testpath = [NSString stringWithFormat:@"%@-2688h@3x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
} else if ([TiUtils isSuperRetina5_8Inch]) {
// -2436h@3x iPhone X specific
NSString *testpath = [NSString stringWithFormat:@"%@-2436h@3x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
} else if ([TiUtils isRetina4_7Inch]) {
// -736h@3x iPhone 6/7 Plus specific
NSString *testpath = [NSString stringWithFormat:@"%@-736h@3x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
}
// Plain @3x
NSString *testpath = [NSString stringWithFormat:@"%@@3x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
}
if ([TiUtils is2xRetina]) {
if ([TiUtils isRetina6_1Inch]) {
// -1792h@2x iPhone XR specific
NSString *testpath = [NSString stringWithFormat:@"%@-1792h@2x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
} else if ([TiUtils isRetina4_7Inch]) {
// -667h@2x iPhone 6/7 specific
NSString *testpath = [NSString stringWithFormat:@"%@-667h@2x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
} else if ([TiUtils isRetinaFourInch]) {
// -568h@2x iPhone 5 specific
NSString *testpath = [NSString stringWithFormat:@"%@-568h@2x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
}
// @2x device specific
NSString *testpath = [NSString stringWithFormat:@"%@@2x%@.%@", partial, os, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
// Plain @2x
testpath = [NSString stringWithFormat:@"%@@2x.%@", partial, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
}
// Fallback: Just device specific normal res
NSString *testpath = [NSString stringWithFormat:@"%@%@.%@", partial, os, ext];
if ([fm fileExistsAtPath:testpath]) {
return [NSURL fileURLWithPath:testpath];
}
return url;
}
+ (NSURL *)toURL:(NSString *)relativeString relativeToURL:(NSURL *)rootPath
{
/*
Okay, behavior: Bad values are either converted or ejected.
sms:, tel:, mailto: are all done
If the new path is HTTP:// etc, then punt and massage the code.
If the new path starts with / and the base url is app://..., we have to massage the url.
*/
if ((relativeString == nil) || ((void *)relativeString == (void *)[NSNull null])) {
return nil;
}
if (![relativeString isKindOfClass:[NSString class]]) {
relativeString = [TiUtils stringValue:relativeString];
}
if ([relativeString hasPrefix:@"sms:"] ||
[relativeString hasPrefix:@"tel:"] ||
[relativeString hasPrefix:@"mailto:"]) {
return [NSURL URLWithString:relativeString];
}
NSURL *result = [NSURL URLWithString:relativeString relativeToURL:rootPath];
// If the path looks absolute (but isn't valid), try to make it relative to resource path
if ([relativeString hasPrefix:@"/"]) {
if (result == nil) {
// assume it's a file path with some funkiness in it that caused URL parsing to fail. Try standardizing the path
result = [NSURL fileURLWithPath:[relativeString stringByStandardizingPath]];
}
NSString *rootScheme = [rootPath scheme];
NSString *resourcePath = [TiHost resourcePath];
BOOL usesApp = [rootScheme isEqualToString:@"app"];
if (!usesApp && [rootScheme isEqualToString:@"file"]) {
usesApp = [[rootPath path] hasPrefix:resourcePath];
}
if (usesApp) {
if (result && [result isFileURL] && [result checkResourceIsReachableAndReturnError:nil]) {
// good URL, no need to treat it like it's relative to resources dir
result = [result filePathURL];
} else {
// bad URL, assume it's relative to app's resources dir
result = [NSURL fileURLWithPath:[resourcePath stringByAppendingPathComponent:relativeString]];
}
}
}
// Fall back if somehow the URL is bad
if (result == nil) {
// encoding problem - fail fast and make sure we re-escape
NSRange range = [relativeString rangeOfString:@"?"];
if (range.location != NSNotFound) {
NSString *qs = [TiUtils encodeURIParameters:[relativeString substringFromIndex:range.location + 1]];
NSString *newurl = [NSString stringWithFormat:@"%@?%@", [relativeString substringToIndex:range.location], qs];
result = [NSURL URLWithString:newurl];
}
}
// If we have a URL and it's a 'file:' one, check for 2x images
// TIMOB-18262
if (result && ([result isFileURL])) {
BOOL isDir = NO;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:[result path] isDirectory:&isDir];
if (exists && !isDir) {
return [TiUtils checkFor2XImage:result];
}
}
return result;
}
+ (NSURL *)toURL:(NSString *)object proxy:(TiProxy *)proxy
{
return [self toURL:object relativeToURL:[proxy _baseURL]];
}
+ (UIImage *)stretchableImage:(id)object proxy:(TiProxy *)proxy
{
return [[ImageLoader sharedLoader] loadImmediateStretchableImage:[self toURL:object proxy:proxy]];
}
+ (UIImage *)image:(id)object proxy:(TiProxy *)proxy
{
if ([object isKindOfClass:[TiBlob class]]) {
return [(TiBlob *)object image];
} else if ([object isKindOfClass:[NSString class]]) {
return [[ImageLoader sharedLoader] loadImmediateImage:[self toURL:object proxy:proxy]];
}
return nil;
}
+ (int)intValue:(NSString *)name properties:(NSDictionary *)properties def:(int)def exists:(BOOL *)exists
{
if ([properties isKindOfClass:[NSDictionary class]]) {
id value = [properties objectForKey:name];
if ([value respondsToSelector:@selector(intValue)]) {
if (exists != NULL)
*exists = YES;
return [value intValue];
}
}
if (exists != NULL)
*exists = NO;
return def;
}
+ (double)doubleValue:(NSString *)name properties:(NSDictionary *)properties def:(double)def exists:(BOOL *)exists
{
if ([properties isKindOfClass:[NSDictionary class]]) {
id value = [properties objectForKey:name];
if ([value respondsToSelector:@selector(doubleValue)]) {
if (exists != NULL)
*exists = YES;
return [value doubleValue];
}
}
if (exists != NULL)
*exists = NO;
return def;
}
+ (float)floatValue:(NSString *)name properties:(NSDictionary *)properties def:(float)def exists:(BOOL *)exists
{
if ([properties isKindOfClass:[NSDictionary class]]) {
id value = [properties objectForKey:name];
if ([value respondsToSelector:@selector(floatValue)]) {
if (exists != NULL)
*exists = YES;
return [value floatValue];
}
}
if (exists != NULL)
*exists = NO;
return def;
}
+ (BOOL)boolValue:(NSString *)name properties:(NSDictionary *)properties def:(BOOL)def exists:(BOOL *)exists
{
if ([properties isKindOfClass:[NSDictionary class]]) {
id value = [properties objectForKey:name];
if ([value respondsToSelector:@selector(boolValue)]) {
if (exists != NULL)
*exists = YES;
return [value boolValue];