forked from facebookarchive/AsyncDisplayKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASDisplayNode.mm
More file actions
1827 lines (1482 loc) · 54.8 KB
/
ASDisplayNode.mm
File metadata and controls
1827 lines (1482 loc) · 54.8 KB
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
/* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import "ASDisplayNode.h"
#import "ASDisplayNode+Subclasses.h"
#import "ASDisplayNodeInternal.h"
#import <objc/runtime.h>
#import "_ASAsyncTransaction.h"
#import "_ASPendingState.h"
#import "_ASDisplayView.h"
#import "_ASScopeTimer.h"
#import "ASDisplayNodeExtras.h"
@interface ASDisplayNode () <UIGestureRecognizerDelegate>
/**
*
* See ASDisplayNodeInternal.h for ivars
*
*/
@end
// Conditionally time these scopes to our debug ivars (only exist in debug/profile builds)
#if TIME_DISPLAYNODE_OPS
#define TIME_SCOPED(outVar) ASDN::ScopeTimer t(outVar)
#else
#define TIME_SCOPED(outVar)
#endif
@implementation ASDisplayNode
BOOL ASDisplayNodeSubclassOverridesSelector(Class subclass, SEL selector)
{
Method superclassMethod = class_getInstanceMethod([ASDisplayNode class], selector);
Method subclassMethod = class_getInstanceMethod(subclass, selector);
IMP superclassIMP = superclassMethod ? method_getImplementation(superclassMethod) : NULL;
IMP subclassIMP = subclassMethod ? method_getImplementation(subclassMethod) : NULL;
return (superclassIMP != subclassIMP);
}
CGFloat ASDisplayNodeScreenScale()
{
static CGFloat screenScale = 0.0;
static dispatch_once_t onceToken;
ASDispatchOnceOnMainThread(&onceToken, ^{
screenScale = [[UIScreen mainScreen] scale];
});
return screenScale;
}
static void ASDispatchOnceOnMainThread(dispatch_once_t *predicate, dispatch_block_t block)
{
if ([NSThread isMainThread]) {
dispatch_once(predicate, block);
} else {
if (DISPATCH_EXPECT(*predicate == 0L, NO)) {
dispatch_sync(dispatch_get_main_queue(), ^{
dispatch_once(predicate, block);
});
}
}
}
void ASDisplayNodePerformBlockOnMainThread(void (^block)())
{
if ([NSThread isMainThread]) {
block();
} else {
dispatch_async(dispatch_get_main_queue(), ^{
block();
});
}
}
+ (void)initialize
{
if (self == [ASDisplayNode class]) {
return;
}
// Subclasses should never override these
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(calculatedSize)), @"Subclass %@ must not override calculatedSize method", NSStringFromClass(self));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(measure:)), @"Subclass %@ must not override measure method", NSStringFromClass(self));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(recursivelyClearContents)), @"Subclass %@ must not override recursivelyClearContents method", NSStringFromClass(self));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(recursivelyClearFetchedData)), @"Subclass %@ must not override recursivelyClearFetchedData method", NSStringFromClass(self));
}
+ (BOOL)layerBackedNodesEnabled
{
return YES;
}
+ (Class)viewClass
{
return [_ASDisplayView class];
}
+ (Class)layerClass
{
return [_ASDisplayLayer class];
}
#pragma mark - Lifecycle
- (void)_initializeInstance
{
_contentsScaleForDisplay = ASDisplayNodeScreenScale();
_displaySentinel = [[ASSentinel alloc] init];
_flags.isInHierarchy = NO;
_flags.displaysAsynchronously = YES;
// As an optimization, it may be worth a caching system that performs these checks once per class in +initialize (see above).
_flags.implementsDrawRect = ([[self class] respondsToSelector:@selector(drawRect:withParameters:isCancelled:isRasterizing:)] ? 1 : 0);
_flags.implementsImageDisplay = ([[self class] respondsToSelector:@selector(displayWithParameters:isCancelled:)] ? 1 : 0);
_flags.implementsDrawParameters = ([self respondsToSelector:@selector(drawParametersForAsyncLayer:)] ? 1 : 0);
ASDisplayNodeMethodOverrides overrides = ASDisplayNodeMethodOverrideNone;
if (ASDisplayNodeSubclassOverridesSelector([self class], @selector(touchesBegan:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesBegan;
}
if (ASDisplayNodeSubclassOverridesSelector([self class], @selector(touchesMoved:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesMoved;
}
if (ASDisplayNodeSubclassOverridesSelector([self class], @selector(touchesCancelled:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesCancelled;
}
if (ASDisplayNodeSubclassOverridesSelector([self class], @selector(touchesEnded:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesEnded;
}
_methodOverrides = overrides;
}
- (id)init
{
if (!(self = [super init]))
return nil;
[self _initializeInstance];
return self;
}
- (id)initWithViewClass:(Class)viewClass
{
if (!(self = [super init]))
return nil;
ASDisplayNodeAssert([viewClass isSubclassOfClass:[UIView class]], @"should initialize with a subclass of UIView");
[self _initializeInstance];
_viewClass = viewClass;
_flags.synchronous = ![viewClass isSubclassOfClass:[_ASDisplayView class]];
return self;
}
- (id)initWithLayerClass:(Class)layerClass
{
if (!(self = [super init]))
return nil;
ASDisplayNodeAssert([layerClass isSubclassOfClass:[CALayer class]], @"should initialize with a subclass of CALayer");
[self _initializeInstance];
_layerClass = layerClass;
_flags.synchronous = ![layerClass isSubclassOfClass:[_ASDisplayLayer class]];
_flags.layerBacked = YES;
return self;
}
- (id)initWithViewBlock:(ASDisplayNodeViewBlock)viewBlock
{
if (!(self = [super init]))
return nil;
ASDisplayNodeAssertNotNil(viewBlock, @"should initialize with a valid block that returns a UIView");
[self _initializeInstance];
_viewBlock = viewBlock;
_flags.synchronous = YES;
return self;
}
- (id)initWithLayerBlock:(ASDisplayNodeLayerBlock)layerBlock
{
if (!(self = [super init]))
return nil;
ASDisplayNodeAssertNotNil(layerBlock, @"should initialize with a valid block that returns a CALayer");
[self _initializeInstance];
_layerBlock = layerBlock;
_flags.synchronous = YES;
_flags.layerBacked = YES;
return self;
}
- (void)dealloc
{
ASDisplayNodeAssertMainThread();
self.asyncLayer.asyncDelegate = nil;
_view.asyncdisplaykit_node = nil;
_layer.asyncdisplaykit_node = nil;
// Remove any subnodes so they lose their connection to the now deallocated parent. This can happen
// because subnodes do not retain their supernode, but subnodes can legitimately remain alive if another
// thing outside the view hierarchy system (e.g. async display, controller code, etc). keeps a retained
// reference to subnodes.
for (ASDisplayNode *subnode in _subnodes)
[subnode __setSupernode:nil];
_view = nil;
_subnodes = nil;
if (_flags.layerBacked)
_layer.delegate = nil;
_layer = nil;
[self __setSupernode:nil];
_pendingViewState = nil;
_replaceAsyncSentinel = nil;
_displaySentinel = nil;
_pendingDisplayNodes = nil;
}
#pragma mark - Core
- (ASDisplayNode *)__rasterizedContainerNode
{
ASDisplayNode *node = self.supernode;
while (node) {
if (node.shouldRasterizeDescendants) {
return node;
}
node = node.supernode;
}
return nil;
}
- (BOOL)__shouldLoadViewOrLayer
{
return ![self __rasterizedContainerNode];
}
- (BOOL)__shouldSize
{
return YES;
}
- (void)__exitedHierarchy
{
}
- (UIView *)_viewToLoad
{
UIView *view;
ASDN::MutexLocker l(_propertyLock);
if (_viewBlock) {
view = _viewBlock();
ASDisplayNodeAssertNotNil(view, @"View block returned nil");
ASDisplayNodeAssert(![view isKindOfClass:[_ASDisplayView class]], @"View block should return a synchronously displayed view");
_viewBlock = nil;
_viewClass = [view class];
} else {
if (!_viewClass) {
_viewClass = [self.class viewClass];
}
view = [[_viewClass alloc] init];
}
return view;
}
- (CALayer *)_layerToLoad
{
CALayer *layer;
ASDN::MutexLocker l(_propertyLock);
if (_layerBlock) {
layer = _layerBlock();
ASDisplayNodeAssertNotNil(layer, @"Layer block returned nil");
ASDisplayNodeAssert(![layer isKindOfClass:[_ASDisplayLayer class]], @"Layer block should return a synchronously displayed layer");
_layerBlock = nil;
_layerClass = [layer class];
} else {
if (!_layerClass) {
_layerClass = [self.class layerClass];
}
layer = [[_layerClass alloc] init];
}
return layer;
}
- (void)_loadViewOrLayerIsLayerBacked:(BOOL)isLayerBacked
{
ASDN::MutexLocker l(_propertyLock);
if (self._isDeallocating) {
return;
}
if (![self __shouldLoadViewOrLayer]) {
return;
}
if (isLayerBacked) {
TIME_SCOPED(_debugTimeToCreateView);
_layer = [self _layerToLoad];
_layer.delegate = self;
} else {
TIME_SCOPED(_debugTimeToCreateView);
_view = [self _viewToLoad];
_view.asyncdisplaykit_node = self;
_layer = _view.layer;
}
_layer.asyncdisplaykit_node = self;
#if DEBUG
_layer.name = self.description;
#endif
self.asyncLayer.asyncDelegate = self;
{
TIME_SCOPED(_debugTimeToApplyPendingState);
[self _applyPendingStateToViewOrLayer];
}
{
TIME_SCOPED(_debugTimeToAddSubnodeViews);
[self _addSubnodeViewsAndLayers];
}
{
TIME_SCOPED(_debugTimeForDidLoad);
[self didLoad];
}
if (self.placeholderEnabled) {
[self _setupPlaceholderLayer];
}
}
- (UIView *)view
{
ASDisplayNodeAssert(!_flags.layerBacked, @"Call to -view undefined on layer-backed nodes");
if (_flags.layerBacked) {
return nil;
}
if (!_view) {
ASDisplayNodeAssertMainThread();
[self _loadViewOrLayerIsLayerBacked:NO];
}
return _view;
}
- (CALayer *)layer
{
if (!_layer) {
ASDisplayNodeAssertMainThread();
if (!_flags.layerBacked) {
return self.view.layer;
}
[self _loadViewOrLayerIsLayerBacked:YES];
}
return _layer;
}
// Returns nil if our view is not an _ASDisplayView, but will create it if necessary.
- (_ASDisplayView *)ensureAsyncView
{
return _flags.synchronous ? nil : (_ASDisplayView *)self.view;
}
// Returns nil if the layer is not an _ASDisplayLayer; will not create the layer if nil.
- (_ASDisplayLayer *)asyncLayer
{
ASDN::MutexLocker l(_propertyLock);
return [_layer isKindOfClass:[_ASDisplayLayer class]] ? (_ASDisplayLayer *)_layer : nil;
}
- (BOOL)isNodeLoaded
{
ASDN::MutexLocker l(_propertyLock);
return (_view != nil || (_flags.layerBacked && _layer != nil));
}
- (BOOL)isSynchronous
{
return _flags.synchronous;
}
- (void)setSynchronous:(BOOL)flag
{
_flags.synchronous = flag;
}
- (void)setLayerBacked:(BOOL)isLayerBacked
{
if (![self.class layerBackedNodesEnabled]) return;
ASDN::MutexLocker l(_propertyLock);
ASDisplayNodeAssert(!_view && !_layer, @"Cannot change isLayerBacked after layer or view has loaded");
ASDisplayNodeAssert(!_viewBlock && !_layerBlock, @"Cannot change isLayerBacked when a layer or view block is provided");
ASDisplayNodeAssert(!_viewClass && !_layerClass, @"Cannot change isLayerBacked when a layer or view class is provided");
if (isLayerBacked != _flags.layerBacked && !_view && !_layer) {
_flags.layerBacked = isLayerBacked;
}
}
- (BOOL)isLayerBacked
{
ASDN::MutexLocker l(_propertyLock);
return _flags.layerBacked;
}
#pragma mark -
- (CGSize)measure:(CGSize)constrainedSize
{
ASDN::MutexLocker l(_propertyLock);
return [self __measure:constrainedSize];
}
- (CGSize)__measure:(CGSize)constrainedSize
{
ASDisplayNodeAssertThreadAffinity(self);
if (![self __shouldSize])
return CGSizeZero;
// only calculate the size if
// - we haven't already
// - the width is different from the last time
// - the height is different from the last time
if (!_flags.isMeasured || !CGSizeEqualToSize(constrainedSize, _constrainedSize)) {
_size = [self calculateSizeThatFits:constrainedSize];
_constrainedSize = constrainedSize;
_flags.isMeasured = YES;
}
ASDisplayNodeAssertTrue(_size.width >= 0.0);
ASDisplayNodeAssertTrue(_size.height >= 0.0);
// we generate placeholders at measure: time so that a node is guaranteed to have a placeholder ready to go
// also if a node has no size, it should not have a placeholder
if (self.placeholderEnabled && [self _displaysAsynchronously] && _size.width > 0.0 && _size.height > 0.0) {
if (!_placeholderImage) {
_placeholderImage = [self placeholderImage];
}
if (_placeholderLayer) {
_placeholderLayer.contents = (id)_placeholderImage.CGImage;
}
}
return _size;
}
- (BOOL)displaysAsynchronously
{
ASDN::MutexLocker l(_propertyLock);
return [self _displaysAsynchronously];
}
/**
* Core implementation of -displaysAsynchronously.
* Must be called with _propertyLock held.
*/
- (BOOL)_displaysAsynchronously
{
ASDisplayNodeAssertThreadAffinity(self);
if (self.isSynchronous) {
return NO;
} else {
return _flags.displaysAsynchronously;
}
}
- (void)setDisplaysAsynchronously:(BOOL)displaysAsynchronously
{
ASDisplayNodeAssertThreadAffinity(self);
// Can't do this for synchronous nodes (using layers that are not _ASDisplayLayer and so we can't control display prevention/cancel)
if (_flags.synchronous)
return;
ASDN::MutexLocker l(_propertyLock);
if (_flags.displaysAsynchronously == displaysAsynchronously)
return;
_flags.displaysAsynchronously = displaysAsynchronously;
self.asyncLayer.displaysAsynchronously = displaysAsynchronously;
}
- (BOOL)shouldRasterizeDescendants
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
return _flags.shouldRasterizeDescendants;
}
- (void)setShouldRasterizeDescendants:(BOOL)flag
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
if (_flags.shouldRasterizeDescendants == flag)
return;
_flags.shouldRasterizeDescendants = flag;
}
- (CGFloat)contentsScaleForDisplay
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
return _contentsScaleForDisplay;
}
- (void)setContentsScaleForDisplay:(CGFloat)contentsScaleForDisplay
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
if (_contentsScaleForDisplay == contentsScaleForDisplay)
return;
_contentsScaleForDisplay = contentsScaleForDisplay;
}
- (void)displayImmediately
{
ASDisplayNodeAssertMainThread();
ASDisplayNodeAssert(!_flags.synchronous, @"this method is designed for asynchronous mode only");
[[self asyncLayer] displayImmediately];
}
// These private methods ensure that subclasses are not required to call super in order for _renderingSubnodes to be properly managed.
- (void)__layout
{
ASDisplayNodeAssertMainThread();
ASDN::MutexLocker l(_propertyLock);
if (CGRectEqualToRect(_layer.bounds, CGRectZero)) {
return; // Performing layout on a zero-bounds view often results in frame calculations with negative sizes after applying margins, which will cause measure: on subnodes to assert.
}
_placeholderLayer.frame = _layer.bounds;
[self layout];
[self layoutDidFinish];
}
- (void)layoutDidFinish
{
}
- (CATransform3D)_transformToAncestor:(ASDisplayNode *)ancestor
{
CATransform3D transform = CATransform3DIdentity;
ASDisplayNode *currentNode = self;
while (currentNode.supernode) {
if (currentNode == ancestor) {
return transform;
}
CGPoint anchorPoint = currentNode.anchorPoint;
CGRect bounds = currentNode.bounds;
CGPoint position = currentNode.position;
CGPoint origin = CGPointMake(position.x - bounds.size.width * anchorPoint.x,
position.y - bounds.size.height * anchorPoint.y);
transform = CATransform3DTranslate(transform, origin.x, origin.y, 0);
transform = CATransform3DTranslate(transform, -bounds.origin.x, -bounds.origin.y, 0);
currentNode = currentNode.supernode;
}
return transform;
}
static inline BOOL _ASDisplayNodeIsAncestorOfDisplayNode(ASDisplayNode *possibleAncestor, ASDisplayNode *possibleDescendent)
{
ASDisplayNode *supernode = possibleDescendent;
while (supernode) {
if (supernode == possibleAncestor) {
return YES;
}
supernode = supernode.supernode;
}
return NO;
}
/**
* NOTE: It is an error to try to convert between nodes which do not share a common ancestor. This behavior is
* disallowed in UIKit documentation and the behavior is left undefined. The output does not have a rigorously defined
* failure mode (i.e. returning CGPointZero or returning the point exactly as passed in). Rather than track the internal
* undefined and undocumented behavior of UIKit in ASDisplayNode, this operation is defined to be incorrect in all
* circumstances and must be fixed wherever encountered.
*/
static inline ASDisplayNode *_ASDisplayNodeFindClosestCommonAncestor(ASDisplayNode *node1, ASDisplayNode *node2)
{
ASDisplayNode *possibleAncestor = node1;
while (possibleAncestor) {
if (_ASDisplayNodeIsAncestorOfDisplayNode(possibleAncestor, node2)) {
break;
}
possibleAncestor = possibleAncestor.supernode;
}
ASDisplayNodeCAssertNotNil(possibleAncestor, @"Could not find a common ancestor between node1: %@ and node2: %@", node1, node2);
return possibleAncestor;
}
static inline ASDisplayNode *_getRootNode(ASDisplayNode *node)
{
// node <- supernode on each loop
// previous <- node on each loop where node is not nil
// previous is the final non-nil value of supernode, i.e. the root node
ASDisplayNode *previousNode = node;
while ((node = [node supernode])) {
previousNode = node;
}
return previousNode;
}
static inline CATransform3D _calculateTransformFromReferenceToTarget(ASDisplayNode *referenceNode, ASDisplayNode *targetNode)
{
ASDisplayNode *ancestor = _ASDisplayNodeFindClosestCommonAncestor(referenceNode, targetNode);
// Transform into global (away from reference coordinate space)
CATransform3D transformToGlobal = [referenceNode _transformToAncestor:ancestor];
// Transform into local (via inverse transform from target to ancestor)
CATransform3D transformToLocal = CATransform3DInvert([targetNode _transformToAncestor:ancestor]);
return CATransform3DConcat(transformToGlobal, transformToLocal);
}
- (CGPoint)convertPoint:(CGPoint)point fromNode:(ASDisplayNode *)node
{
ASDisplayNodeAssertThreadAffinity(self);
// Get root node of the accessible node hierarchy, if node not specified
node = node ? node : _getRootNode(self);
// Calculate transform to map points between coordinate spaces
CATransform3D nodeTransform = _calculateTransformFromReferenceToTarget(node, self);
CGAffineTransform flattenedTransform = CATransform3DGetAffineTransform(nodeTransform);
ASDisplayNodeAssertTrue(CATransform3DIsAffine(nodeTransform));
// Apply to point
return CGPointApplyAffineTransform(point, flattenedTransform);
}
- (CGPoint)convertPoint:(CGPoint)point toNode:(ASDisplayNode *)node
{
ASDisplayNodeAssertThreadAffinity(self);
// Get root node of the accessible node hierarchy, if node not specified
node = node ? node : _getRootNode(self);
// Calculate transform to map points between coordinate spaces
CATransform3D nodeTransform = _calculateTransformFromReferenceToTarget(self, node);
CGAffineTransform flattenedTransform = CATransform3DGetAffineTransform(nodeTransform);
ASDisplayNodeAssertTrue(CATransform3DIsAffine(nodeTransform));
// Apply to point
return CGPointApplyAffineTransform(point, flattenedTransform);
}
- (CGRect)convertRect:(CGRect)rect fromNode:(ASDisplayNode *)node
{
ASDisplayNodeAssertThreadAffinity(self);
// Get root node of the accessible node hierarchy, if node not specified
node = node ? node : _getRootNode(self);
// Calculate transform to map points between coordinate spaces
CATransform3D nodeTransform = _calculateTransformFromReferenceToTarget(node, self);
CGAffineTransform flattenedTransform = CATransform3DGetAffineTransform(nodeTransform);
ASDisplayNodeAssertTrue(CATransform3DIsAffine(nodeTransform));
// Apply to rect
return CGRectApplyAffineTransform(rect, flattenedTransform);
}
- (CGRect)convertRect:(CGRect)rect toNode:(ASDisplayNode *)node
{
ASDisplayNodeAssertThreadAffinity(self);
// Get root node of the accessible node hierarchy, if node not specified
node = node ? node : _getRootNode(self);
// Calculate transform to map points between coordinate spaces
CATransform3D nodeTransform = _calculateTransformFromReferenceToTarget(self, node);
CGAffineTransform flattenedTransform = CATransform3DGetAffineTransform(nodeTransform);
ASDisplayNodeAssertTrue(CATransform3DIsAffine(nodeTransform));
// Apply to rect
return CGRectApplyAffineTransform(rect, flattenedTransform);
}
#pragma mark - _ASDisplayLayerDelegate
- (void)willDisplayAsyncLayer:(_ASDisplayLayer *)layer
{
// Subclass hook.
[self displayWillStart];
}
- (void)didDisplayAsyncLayer:(_ASDisplayLayer *)layer
{
// Subclass hook.
[self displayDidFinish];
}
#pragma mark - CALayerDelegate
// We are only the delegate for the layer when we are layer-backed, as UIView performs this funcition normally
- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event
{
if (event == kCAOnOrderIn) {
[self __enterHierarchy];
} else if (event == kCAOnOrderOut) {
[self __exitHierarchy];
}
ASDisplayNodeAssert(_flags.layerBacked, @"We shouldn't get called back here if there is no layer");
return (id<CAAction>)[NSNull null];
}
#pragma mark -
static bool disableNotificationsForMovingBetweenParents(ASDisplayNode *from, ASDisplayNode *to)
{
if (!from || !to) return NO;
if (from->_flags.synchronous) return NO;
if (to->_flags.synchronous) return NO;
if (from->_flags.isInHierarchy != to->_flags.isInHierarchy) return NO;
return YES;
}
- (void)addSubnode:(ASDisplayNode *)subnode
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
ASDisplayNode *oldParent = subnode.supernode;
if (!subnode || subnode == self || oldParent == self)
return;
// Disable appearance methods during move between supernodes, but make sure we restore their state after we do our thing
BOOL isMovingEquivalentParents = disableNotificationsForMovingBetweenParents(oldParent, self);
if (isMovingEquivalentParents) {
[subnode __incrementVisibilityNotificationsDisabled];
}
[subnode removeFromSupernode];
if (!_subnodes)
_subnodes = [[NSMutableArray alloc] init];
[_subnodes addObject:subnode];
if (self.nodeLoaded) {
// If this node has a view or layer, force the subnode to also create its view or layer and add it to the hierarchy here.
// Otherwise there is no way for the subnode's view or layer to enter the hierarchy, except recursing down all
// subnodes on the main thread after the node tree has been created but before the first display (which
// could introduce performance problems).
if (ASDisplayNodeThreadIsMain()) {
[self _addSubnodeSubviewOrSublayer:subnode];
} else {
dispatch_async(dispatch_get_main_queue(), ^{
[self _addSubnodeSubviewOrSublayer:subnode];
});
}
}
ASDisplayNodeAssert(isMovingEquivalentParents == disableNotificationsForMovingBetweenParents(oldParent, self), @"Invariant violated");
if (isMovingEquivalentParents) {
[subnode __decrementVisibilityNotificationsDisabled];
}
[subnode __setSupernode:self];
}
/*
Private helper function.
You must hold _propertyLock to call this.
@param subnode The subnode to insert
@param subnodeIndex The index in _subnodes to insert it
@param viewSublayerIndex The index in layer.sublayers (not view.subviews) at which to insert the view (use if we can use the view API) otherwise pass NSNotFound
@param sublayerIndex The index in layer.sublayers at which to insert the layer (use if either parent or subnode is layer-backed) otherwise pass NSNotFound
@param oldSubnode Remove this subnode before inserting; ok to be nil if no removal is desired
*/
- (void)_insertSubnode:(ASDisplayNode *)subnode atSubnodeIndex:(NSInteger)subnodeIndex sublayerIndex:(NSInteger)sublayerIndex andRemoveSubnode:(ASDisplayNode *)oldSubnode
{
if (subnodeIndex == NSNotFound)
return;
ASDisplayNode *oldParent = [subnode _deallocSafeSupernode];
// Disable appearance methods during move between supernodes, but make sure we restore their state after we do our thing
BOOL isMovingEquivalentParents = disableNotificationsForMovingBetweenParents(oldParent, self);
if (isMovingEquivalentParents) {
[subnode __incrementVisibilityNotificationsDisabled];
}
[subnode removeFromSupernode];
if (!_subnodes)
_subnodes = [[NSMutableArray alloc] init];
[oldSubnode removeFromSupernode];
[_subnodes insertObject:subnode atIndex:subnodeIndex];
// Don't bother inserting the view/layer if in a rasterized subtree, becuase there are no layers in the hierarchy and none of this could possibly work.
if (!_flags.shouldRasterizeDescendants && ![self __rasterizedContainerNode]) {
if (_layer) {
ASDisplayNodeCAssertMainThread();
ASDisplayNodeAssert(sublayerIndex != NSNotFound, @"Should pass either a valid sublayerIndex");
if (sublayerIndex != NSNotFound) {
BOOL canUseViewAPI = !subnode.isLayerBacked && !self.isLayerBacked;
// If we can use view API, do. Due to an apple bug, -insertSubview:atIndex: actually wants a LAYER index, which we pass in
if (canUseViewAPI && sublayerIndex != NSNotFound) {
[_view insertSubview:subnode.view atIndex:sublayerIndex];
} else if (sublayerIndex != NSNotFound) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
[_layer insertSublayer:subnode.layer atIndex:sublayerIndex];
#pragma clang diagnostic pop
}
}
}
}
ASDisplayNodeAssert(isMovingEquivalentParents == disableNotificationsForMovingBetweenParents(oldParent, self), @"Invariant violated");
if (isMovingEquivalentParents) {
[subnode __decrementVisibilityNotificationsDisabled];
}
[subnode __setSupernode:self];
}
- (void)replaceSubnode:(ASDisplayNode *)oldSubnode withSubnode:(ASDisplayNode *)replacementSubnode
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
if (!replacementSubnode || [oldSubnode _deallocSafeSupernode] != self) {
ASDisplayNodeAssert(0, @"Bad use of api. Invalid subnode to replace async.");
return;
}
ASDisplayNodeAssert(!(self.nodeLoaded && !oldSubnode.nodeLoaded), @"ASDisplayNode corruption bug. We have view loaded, but child node does not.");
ASDisplayNodeAssert(_subnodes, @"You should have subnodes if you have a subnode");
NSInteger subnodeIndex = [_subnodes indexOfObjectIdenticalTo:oldSubnode];
NSInteger sublayerIndex = NSNotFound;
if (_layer) {
sublayerIndex = [_layer.sublayers indexOfObjectIdenticalTo:oldSubnode.layer];
ASDisplayNodeAssert(sublayerIndex != NSNotFound, @"Somehow oldSubnode's supernode is self, yet we could not find it in our layers to replace");
if (sublayerIndex == NSNotFound) return;
}
[self _insertSubnode:replacementSubnode atSubnodeIndex:subnodeIndex sublayerIndex:sublayerIndex andRemoveSubnode:oldSubnode];
}
// This is just a convenience to avoid a bunch of conditionals
static NSInteger incrementIfFound(NSInteger i) {
return i == NSNotFound ? NSNotFound : i + 1;
}
- (void)insertSubnode:(ASDisplayNode *)subnode belowSubnode:(ASDisplayNode *)below
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
ASDisplayNodeAssert(subnode, @"Cannot insert a nil subnode");
if (!subnode)
return;
ASDisplayNodeAssert([below _deallocSafeSupernode] == self, @"Node to insert below must be a subnode");
if ([below _deallocSafeSupernode] != self)
return;
ASDisplayNodeAssert(_subnodes, @"You should have subnodes if you have a subnode");
NSInteger belowSubnodeIndex = [_subnodes indexOfObjectIdenticalTo:below];
NSInteger belowSublayerIndex = NSNotFound;
if (_layer) {
belowSublayerIndex = [_layer.sublayers indexOfObjectIdenticalTo:below.layer];
ASDisplayNodeAssert(belowSublayerIndex != NSNotFound, @"Somehow below's supernode is self, yet we could not find it in our layers to reference");
if (belowSublayerIndex == NSNotFound)
return;
}
// If the subnode is already in the subnodes array / sublayers and it's before the below node, removing it to insert it will mess up our calculation
if ([subnode _deallocSafeSupernode] == self) {
NSInteger currentIndexInSubnodes = [_subnodes indexOfObjectIdenticalTo:subnode];
if (currentIndexInSubnodes < belowSubnodeIndex) {
belowSubnodeIndex--;
}
if (_layer) {
NSInteger currentIndexInSublayers = [_layer.sublayers indexOfObjectIdenticalTo:subnode.layer];
if (currentIndexInSublayers < belowSublayerIndex) {
belowSublayerIndex--;
}
}
}
ASDisplayNodeAssert(belowSubnodeIndex != NSNotFound, @"Couldn't find below in subnodes");
[self _insertSubnode:subnode atSubnodeIndex:belowSubnodeIndex sublayerIndex:belowSublayerIndex andRemoveSubnode:nil];
}
- (void)insertSubnode:(ASDisplayNode *)subnode aboveSubnode:(ASDisplayNode *)above
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
ASDisplayNodeAssert(subnode, @"Cannot insert a nil subnode");
if (!subnode)
return;
ASDisplayNodeAssert([above _deallocSafeSupernode] == self, @"Node to insert above must be a subnode");
if ([above _deallocSafeSupernode] != self)
return;
ASDisplayNodeAssert(_subnodes, @"You should have subnodes if you have a subnode");
NSInteger aboveSubnodeIndex = [_subnodes indexOfObjectIdenticalTo:above];
NSInteger aboveSublayerIndex = NSNotFound;
// Don't bother figuring out the sublayerIndex if in a rasterized subtree, becuase there are no layers in the hierarchy and none of this could possibly work.
if (!_flags.shouldRasterizeDescendants && ![self __rasterizedContainerNode]) {
if (_layer) {
aboveSublayerIndex = [_layer.sublayers indexOfObjectIdenticalTo:above.layer];
ASDisplayNodeAssert(aboveSublayerIndex != NSNotFound, @"Somehow above's supernode is self, yet we could not find it in our layers to replace");
if (aboveSublayerIndex == NSNotFound)
return;
}
ASDisplayNodeAssert(aboveSubnodeIndex != NSNotFound, @"Couldn't find above in subnodes");
// If the subnode is already in the subnodes array / sublayers and it's before the below node, removing it to insert it will mess up our calculation
if ([subnode _deallocSafeSupernode] == self) {
NSInteger currentIndexInSubnodes = [_subnodes indexOfObjectIdenticalTo:subnode];
if (currentIndexInSubnodes <= aboveSubnodeIndex) {
aboveSubnodeIndex--;
}
if (_layer) {
NSInteger currentIndexInSublayers = [_layer.sublayers indexOfObjectIdenticalTo:subnode.layer];
if (currentIndexInSublayers <= aboveSublayerIndex) {
aboveSublayerIndex--;
}
}
}
}
[self _insertSubnode:subnode atSubnodeIndex:incrementIfFound(aboveSubnodeIndex) sublayerIndex:incrementIfFound(aboveSublayerIndex) andRemoveSubnode:nil];
}
- (void)insertSubnode:(ASDisplayNode *)subnode atIndex:(NSInteger)idx
{
ASDisplayNodeAssertThreadAffinity(self);
ASDN::MutexLocker l(_propertyLock);
if (idx > _subnodes.count || idx < 0) {
NSString *reason = [NSString stringWithFormat:@"Cannot insert a subnode at index %zd. Count is %zd", idx, _subnodes.count];
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil];
}
NSInteger sublayerIndex = NSNotFound;
// Account for potentially having other subviews
if (_layer && idx == 0) {
sublayerIndex = 0;
} else if (_layer) {
ASDisplayNode *positionInRelationTo = (_subnodes.count > 0 && idx > 0) ? _subnodes[idx - 1] : nil;
if (positionInRelationTo) {
sublayerIndex = incrementIfFound([_layer.sublayers indexOfObjectIdenticalTo:positionInRelationTo.layer]);