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
3631 lines (2997 loc) · 125 KB
/
ASDisplayNode.mm
File metadata and controls
3631 lines (2997 loc) · 125 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
//
// ASDisplayNode.mm
// AsyncDisplayKit
//
// 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 "ASDisplayNodeInternal.h"
#import "ASDisplayNode+Subclasses.h"
#import "ASDisplayNode+FrameworkPrivate.h"
#import "ASDisplayNode+Beta.h"
#import <objc/runtime.h>
#import "_ASAsyncTransaction.h"
#import "_ASAsyncTransactionContainer+Private.h"
#import "_ASPendingState.h"
#import "_ASDisplayView.h"
#import "_ASScopeTimer.h"
#import "_ASCoreAnimationExtras.h"
#import "ASDisplayNodeExtras.h"
#import "ASTraitCollection.h"
#import "ASEqualityHelpers.h"
#import "ASRunLoopQueue.h"
#import "ASEnvironmentInternal.h"
#import "ASDimension.h"
#import "ASLayoutElementStylePrivate.h"
#import "ASInternalHelpers.h"
#import "ASLayout.h"
#import "ASLayoutSpec.h"
#import "ASCellNode+Internal.h"
#import "ASWeakProxy.h"
NSInteger const ASDefaultDrawingPriority = ASDefaultTransactionPriority;
NSString * const ASRenderingEngineDidDisplayScheduledNodesNotification = @"ASRenderingEngineDidDisplayScheduledNodes";
NSString * const ASRenderingEngineDidDisplayNodesScheduledBeforeTimestamp = @"ASRenderingEngineDidDisplayNodesScheduledBeforeTimestamp";
// Forward declare CALayerDelegate protocol as the iOS 10 SDK moves CALayerDelegate from a formal delegate to a protocol.
// We have to forward declare the protocol as this place otherwise it will not compile compiling with an Base SDK < iOS 10
@protocol CALayerDelegate;
@interface ASDisplayNode () <UIGestureRecognizerDelegate, _ASDisplayLayerDelegate, _ASTransitionContextCompletionDelegate>
/**
*
* See ASDisplayNodeInternal.h for ivars
*
*/
- (void)_staticInitialize;
@end
#if ASDisplayNodeLoggingEnabled
#define LOG(...) NSLog(__VA_ARGS__)
#else
#define LOG(...)
#endif
// 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
@dynamic layoutElementType;
@synthesize name = _name;
@synthesize isFinalLayoutElement = _isFinalLayoutElement;
@synthesize threadSafeBounds = _threadSafeBounds;
@synthesize layoutSpecBlock = _layoutSpecBlock;
static BOOL suppressesInvalidCollectionUpdateExceptions = NO;
+ (BOOL)suppressesInvalidCollectionUpdateExceptions
{
return suppressesInvalidCollectionUpdateExceptions;
}
+ (void)setSuppressesInvalidCollectionUpdateExceptions:(BOOL)suppresses
{
suppressesInvalidCollectionUpdateExceptions = suppresses;
}
BOOL ASDisplayNodeSubclassOverridesSelector(Class subclass, SEL selector)
{
return ASSubclassOverridesSelector([ASDisplayNode class], subclass, selector);
}
// For classes like ASTableNode, ASCollectionNode, ASScrollNode and similar - we have to be sure to set certain properties
// like setFrame: and setBackgroundColor: directly to the UIView and not apply it to the layer only.
BOOL ASDisplayNodeNeedsSpecialPropertiesHandlingForFlags(ASDisplayNodeFlags flags)
{
return flags.synchronous && !flags.layerBacked;
}
_ASPendingState *ASDisplayNodeGetPendingState(ASDisplayNode *node)
{
ASDN::MutexLocker l(node->__instanceLock__);
_ASPendingState *result = node->_pendingViewState;
if (result == nil) {
result = [[_ASPendingState alloc] init];
node->_pendingViewState = result;
}
return result;
}
/**
* Returns ASDisplayNodeFlags for the given class/instance. instance MAY BE NIL.
*
* @param c the class, required
* @param instance the instance, which may be nil. (If so, the class is inspected instead)
* @remarks The instance value is used only if we suspect the class may be dynamic (because it overloads
* +respondsToSelector: or -respondsToSelector.) In that case we use our "slow path", calling this
* method on each -init and passing the instance value. While this may seem like an unlikely scenario,
* it turns our our own internal tests use a dynamic class, so it's worth capturing this edge case.
*
* @return ASDisplayNode flags.
*/
static struct ASDisplayNodeFlags GetASDisplayNodeFlags(Class c, ASDisplayNode *instance)
{
ASDisplayNodeCAssertNotNil(c, @"class is required");
struct ASDisplayNodeFlags flags = {0};
flags.isInHierarchy = NO;
flags.displaysAsynchronously = YES;
flags.shouldAnimateSizeChanges = YES;
flags.implementsDrawRect = ([c respondsToSelector:@selector(drawRect:withParameters:isCancelled:isRasterizing:)] ? 1 : 0);
flags.implementsImageDisplay = ([c respondsToSelector:@selector(displayWithParameters:isCancelled:)] ? 1 : 0);
if (instance) {
flags.implementsDrawParameters = ([instance respondsToSelector:@selector(drawParametersForAsyncLayer:)] ? 1 : 0);
flags.implementsInstanceDrawRect = ([instance respondsToSelector:@selector(drawRect:withParameters:isCancelled:isRasterizing:)] ? 1 : 0);
flags.implementsInstanceImageDisplay = ([instance respondsToSelector:@selector(displayWithParameters:isCancelled:)] ? 1 : 0);
} else {
flags.implementsDrawParameters = ([c instancesRespondToSelector:@selector(drawParametersForAsyncLayer:)] ? 1 : 0);
flags.implementsInstanceDrawRect = ([c instancesRespondToSelector:@selector(drawRect:withParameters:isCancelled:isRasterizing:)] ? 1 : 0);
flags.implementsInstanceImageDisplay = ([c instancesRespondToSelector:@selector(displayWithParameters:isCancelled:)] ? 1 : 0);
}
return flags;
}
/**
* Returns ASDisplayNodeMethodOverrides for the given class
*
* @param c the class, required.
*
* @return ASDisplayNodeMethodOverrides.
*/
static ASDisplayNodeMethodOverrides GetASDisplayNodeMethodOverrides(Class c)
{
ASDisplayNodeCAssertNotNil(c, @"class is required");
ASDisplayNodeMethodOverrides overrides = ASDisplayNodeMethodOverrideNone;
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(touchesBegan:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesBegan;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(touchesMoved:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesMoved;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(touchesCancelled:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesCancelled;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(touchesEnded:withEvent:))) {
overrides |= ASDisplayNodeMethodOverrideTouchesEnded;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(layoutSpecThatFits:))) {
overrides |= ASDisplayNodeMethodOverrideLayoutSpecThatFits;
}
return overrides;
}
// At most a layoutSpecBlock or one of the three layout methods is overridden
#define __ASDisplayNodeCheckForLayoutMethodOverrides \
ASDisplayNodeAssert(_layoutSpecBlock != NULL || \
(ASDisplayNodeSubclassOverridesSelector(self.class, @selector(calculateSizeThatFits:)) ? 1 : 0) \
+ (ASDisplayNodeSubclassOverridesSelector(self.class, @selector(layoutSpecThatFits:)) ? 1 : 0) \
+ (ASDisplayNodeSubclassOverridesSelector(self.class, @selector(calculateLayoutThatFits:)) ? 1 : 0) <= 1, \
@"Subclass %@ must at least provide a layoutSpecBlock or override at most one of the three layout methods: calculateLayoutThatFits, layoutSpecThatFits or calculateSizeThatFits", NSStringFromClass(self.class))
+ (void)initialize
{
[super initialize];
if (self != [ASDisplayNode class]) {
// Subclasses should never override these. Use unused to prevent warnings
__unused NSString *classString = NSStringFromClass(self);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(calculatedSize)), @"Subclass %@ must not override calculatedSize method", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(calculatedLayout)), @"Subclass %@ must not override calculatedLayout method", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(measure:)), @"Subclass %@ must not override measure: method", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(measureWithSizeRange:)), @"Subclass %@ must not override measureWithSizeRange: method. Instead overwrite calculateLayoutThatFits:", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(layoutThatFits:)), @"Subclass %@ must not override layoutThatFits: method", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(layoutThatFits:parentSize:)), @"Subclass %@ must not override layoutThatFits:parentSize method", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(recursivelyClearContents)), @"Subclass %@ must not override recursivelyClearContents method", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(recursivelyClearFetchedData)), @"Subclass %@ must not override recursivelyClearFetchedData method", classString);
}
// Below we are pre-calculating values per-class and dynamically adding a method (_staticInitialize) to populate these values
// when each instance is constructed. These values don't change for each class, so there is significant performance benefit
// in doing it here. +initialize is guaranteed to be called before any instance method so it is safe to add this method here.
// Note that we take care to detect if the class overrides +respondsToSelector: or -respondsToSelector and take the slow path
// (recalculating for each instance) to make sure we are always correct.
BOOL classOverridesRespondsToSelector = ASSubclassOverridesClassSelector([NSObject class], self, @selector(respondsToSelector:));
BOOL instancesOverrideRespondsToSelector = ASSubclassOverridesSelector([NSObject class], self, @selector(respondsToSelector:));
struct ASDisplayNodeFlags flags = GetASDisplayNodeFlags(self, nil);
ASDisplayNodeMethodOverrides methodOverrides = GetASDisplayNodeMethodOverrides(self);
__unused Class initializeSelf = self;
IMP staticInitialize = imp_implementationWithBlock(^(ASDisplayNode *node) {
ASDisplayNodeAssert(node.class == initializeSelf, @"Node class %@ does not have a matching _staticInitialize method; check to ensure [super initialize] is called within any custom +initialize implementations! Overridden methods will not be called unless they are also implemented by superclass %@", node.class, initializeSelf);
node->_flags = (classOverridesRespondsToSelector || instancesOverrideRespondsToSelector) ? GetASDisplayNodeFlags(node.class, node) : flags;
node->_methodOverrides = (classOverridesRespondsToSelector) ? GetASDisplayNodeMethodOverrides(node.class) : methodOverrides;
});
class_replaceMethod(self, @selector(_staticInitialize), staticInitialize, "v:@");
#if DEBUG
// Check if subnodes where modified during layoutSpecThatFits:
if (self == [ASDisplayNode class] || ASSubclassOverridesSelector([ASDisplayNode class], self, @selector(layoutSpecThatFits:)))
{
__block IMP originalLayoutSpecThatFitsIMP = ASReplaceMethodWithBlock(self, @selector(layoutSpecThatFits:), ^(ASDisplayNode *_self, ASSizeRange sizeRange) {
NSArray *oldSubnodes = _self.subnodes;
ASLayoutSpec *layoutSpec = ((ASLayoutSpec *( *)(id, SEL, ASSizeRange))originalLayoutSpecThatFitsIMP)(_self, @selector(layoutSpecThatFits:), sizeRange);
NSArray *subnodes = _self.subnodes;
ASDisplayNodeAssert(oldSubnodes.count == subnodes.count, @"Adding or removing nodes in layoutSpecThatFits: is verboten.");
for (NSInteger i = 0; i < oldSubnodes.count; i++) {
ASDisplayNodeAssert(oldSubnodes[i] == subnodes[i], @"Adding and removing nodes in layoutSpecThatFits: is verboten.");
}
return layoutSpec;
});
}
#endif
}
+ (void)load
{
// Ensure this value is cached on the main thread before needed in the background.
ASScreenScale();
}
+ (BOOL)layerBackedNodesEnabled
{
return YES;
}
+ (Class)viewClass
{
return [_ASDisplayView class];
}
+ (Class)layerClass
{
return [_ASDisplayLayer class];
}
+ (void)scheduleNodeForRecursiveDisplay:(ASDisplayNode *)node
{
static dispatch_once_t onceToken;
static ASRunLoopQueue<ASDisplayNode *> *renderQueue;
dispatch_once(&onceToken, ^{
renderQueue = [[ASRunLoopQueue<ASDisplayNode *> alloc] initWithRunLoop:CFRunLoopGetMain()
andHandler:^(ASDisplayNode * _Nonnull dequeuedItem, BOOL isQueueDrained) {
[dequeuedItem _recursivelyTriggerDisplayAndBlock:NO];
if (isQueueDrained) {
CFAbsoluteTime timestamp = CFAbsoluteTimeGetCurrent();
[[NSNotificationCenter defaultCenter] postNotificationName:ASRenderingEngineDidDisplayScheduledNodesNotification
object:nil
userInfo:@{ASRenderingEngineDidDisplayNodesScheduledBeforeTimestamp: @(timestamp)}];
}
}];
});
[renderQueue enqueue:node];
}
#pragma mark - Lifecycle
- (void)_staticInitialize
{
ASDisplayNodeAssert(NO, @"_staticInitialize must be overridden");
}
- (void)_initializeInstance
{
[self _staticInitialize];
_eventLogHead = -1;
_contentsScaleForDisplay = ASScreenScale();
_environmentState = ASEnvironmentStateMakeDefault();
_calculatedDisplayNodeLayout = std::make_shared<ASDisplayNodeLayout>();
_defaultLayoutTransitionDuration = 0.2;
_defaultLayoutTransitionDelay = 0.0;
_defaultLayoutTransitionOptions = UIViewAnimationOptionBeginFromCurrentState;
_flags.canClearContentsOfLayer = YES;
_flags.canCallSetNeedsDisplayOfLayer = YES;
ASDisplayNodeLogEvent(self, @"init");
}
- (instancetype)init
{
if (!(self = [super init]))
return nil;
[self _initializeInstance];
return self;
}
- (instancetype)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;
}
- (instancetype)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;
}
- (instancetype)initWithViewBlock:(ASDisplayNodeViewBlock)viewBlock
{
return [self initWithViewBlock:viewBlock didLoadBlock:nil];
}
- (instancetype)initWithViewBlock:(ASDisplayNodeViewBlock)viewBlock didLoadBlock:(ASDisplayNodeDidLoadBlock)didLoadBlock
{
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;
if (didLoadBlock != nil) {
_onDidLoadBlocks = [NSMutableArray arrayWithObject:didLoadBlock];
}
return self;
}
- (instancetype)initWithLayerBlock:(ASDisplayNodeLayerBlock)layerBlock
{
return [self initWithLayerBlock:layerBlock didLoadBlock:nil];
}
- (instancetype)initWithLayerBlock:(ASDisplayNodeLayerBlock)layerBlock didLoadBlock:(ASDisplayNodeDidLoadBlock)didLoadBlock
{
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;
if (didLoadBlock != nil) {
_onDidLoadBlocks = [NSMutableArray arrayWithObject:didLoadBlock];
}
return self;
}
- (void)onDidLoad:(ASDisplayNodeDidLoadBlock)body
{
ASDN::MutexLocker l(__instanceLock__);
if ([self _isNodeLoaded]) {
ASDisplayNodeFailAssert(@"Attempt to call %@ on node after it was loaded. Node: %@", NSStringFromSelector(_cmd), self);
return;
}
if (_onDidLoadBlocks == nil) {
_onDidLoadBlocks = [NSMutableArray arrayWithObject:body];
} else {
[_onDidLoadBlocks addObject:body];
}
}
- (void)dealloc
{
ASDisplayNodeAssertMainThread();
// Synchronous nodes may not be able to call the hierarchy notifications, so only enforce for regular nodes.
ASDisplayNodeAssert(_flags.synchronous || !ASInterfaceStateIncludesVisible(_interfaceState), @"Node should always be marked invisible before deallocating. Node: %@", self);
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;
_layer = nil;
// TODO: Remove this? If supernode isn't already nil, this method isn't dealloc-safe anyway.
[self __setSupernode:nil];
_pendingViewState = nil;
_pendingDisplayNodes = nil;
}
#pragma mark - Core
- (void)__unloadNode
{
ASDisplayNodeAssertMainThread();
ASDisplayNodeAssert([self isNodeLoaded], @"Implementation shouldn't call __unloadNode if not loaded: %@", self);
ASDisplayNodeAssert(_flags.synchronous == NO, @"Node created using -initWithViewBlock:/-initWithLayerBlock: cannot be unloaded. Node: %@", self);
ASDN::MutexLocker l(__instanceLock__);
if (_flags.layerBacked)
_pendingViewState = [_ASPendingState pendingViewStateFromLayer:_layer];
else
_pendingViewState = [_ASPendingState pendingViewStateFromView:_view];
[_view removeFromSuperview];
_view = nil;
if (_flags.layerBacked)
_layer.delegate = nil;
[_layer removeFromSuperlayer];
_layer = nil;
}
- (void)__loadNode
{
[self layer];
}
- (BOOL)__shouldLoadViewOrLayer
{
return !(_hierarchyState & ASHierarchyStateRasterized);
}
- (UIView *)_viewToLoad
{
UIView *view;
ASDN::MutexLocker l(__instanceLock__);
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];
}
// Update flags related to special handling of UIImageView layers. More details on the flags
if (_flags.synchronous && [_viewClass isSubclassOfClass:[UIImageView class]]) {
_flags.canClearContentsOfLayer = NO;
_flags.canCallSetNeedsDisplayOfLayer = NO;
}
return view;
}
- (CALayer *)_layerToLoad
{
CALayer *layer;
ASDN::MutexLocker l(__instanceLock__);
ASDisplayNodeAssert(_flags.layerBacked, @"_layerToLoad is only for layer-backed nodes");
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(__instanceLock__);
if (self._isDeallocating) {
return;
}
if (![self __shouldLoadViewOrLayer]) {
return;
}
if (isLayerBacked) {
TIME_SCOPED(_debugTimeToCreateView);
_layer = [self _layerToLoad];
static int ASLayerDelegateAssociationKey;
/**
* CALayer's .delegate property is documented to be weak, but the implementation is actually assign.
* Because our layer may survive longer than the node (e.g. if someone else retains it, or if the node
* begins deallocation on a background thread and it waiting for the -dealloc call to reach main), the only
* way to avoid a dangling pointer is to use a weak proxy.
*/
ASWeakProxy *instance = [ASWeakProxy weakProxyWithTarget:self];
_layer.delegate = (id<CALayerDelegate>)instance;
objc_setAssociatedObject(_layer, &ASLayerDelegateAssociationKey, instance, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} else {
TIME_SCOPED(_debugTimeToCreateView);
_view = [self _viewToLoad];
_view.asyncdisplaykit_node = self;
_layer = _view.layer;
}
_layer.asyncdisplaykit_node = self;
self.asyncLayer.asyncDelegate = self;
{
TIME_SCOPED(_debugTimeToApplyPendingState);
[self _applyPendingStateToViewOrLayer];
}
{
TIME_SCOPED(_debugTimeToAddSubnodeViews);
[self _addSubnodeViewsAndLayers];
}
{
TIME_SCOPED(_debugTimeForDidLoad);
[self __didLoad];
}
}
#if ASDISPLAYNODE_EVENTLOG_ENABLE
- (void)_logEventWithBacktrace:(NSArray<NSString *> *)backtrace format:(NSString *)format, ...
{
va_list args;
va_start(args, format);
ASTraceEvent *event = [[ASTraceEvent alloc] initWithObject:self
backtrace:backtrace
format:format
arguments:args];
va_end(args);
ASDN::MutexLocker l(__instanceLock__);
// Create the array if needed.
if (_eventLog == nil) {
_eventLog = [NSMutableArray arrayWithCapacity:ASDISPLAYNODE_EVENTLOG_CAPACITY];
}
// Increment the head index.
_eventLogHead = (_eventLogHead + 1) % ASDISPLAYNODE_EVENTLOG_CAPACITY;
if (_eventLogHead < _eventLog.count) {
[_eventLog replaceObjectAtIndex:_eventLogHead withObject:event];
} else {
[_eventLog insertObject:event atIndex:_eventLogHead];
}
}
- (NSArray<ASTraceEvent *> *)eventLog
{
ASDN::MutexLocker l(__instanceLock__);
NSUInteger tail = (_eventLogHead + 1);
NSUInteger count = _eventLog.count;
NSMutableArray<ASTraceEvent *> *result = [NSMutableArray array];
// Start from `tail` and go through array, wrapping around when we exceed end index.
for (NSUInteger actualIndex = 0; actualIndex < ASDISPLAYNODE_EVENTLOG_CAPACITY; actualIndex++) {
NSInteger ringIndex = (tail + actualIndex) % ASDISPLAYNODE_EVENTLOG_CAPACITY;
if (ringIndex < count) {
[result addObject:_eventLog[ringIndex]];
}
}
return result;
}
#endif
- (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(__instanceLock__);
return [_layer isKindOfClass:[_ASDisplayLayer class]] ? (_ASDisplayLayer *)_layer : nil;
}
- (BOOL)isNodeLoaded
{
if (ASDisplayNodeThreadIsMain()) {
// Because the view and layer can only be created and destroyed on Main, that is also the only thread
// where the state of this property can change. As an optimization, we can avoid locking.
return [self _isNodeLoaded];
} else {
ASDN::MutexLocker l(__instanceLock__);
return [self _isNodeLoaded];
}
}
- (BOOL)_isNodeLoaded
{
return (_view != nil || (_layer != nil && _flags.layerBacked));
}
- (NSString *)name
{
ASDN::MutexLocker l(__instanceLock__);
return _name;
}
- (void)setName:(NSString *)name
{
ASDN::MutexLocker l(__instanceLock__);
if (!ASObjectIsEqual(_name, name)) {
_name = [name copy];
}
}
- (BOOL)isSynchronous
{
return _flags.synchronous;
}
- (void)setSynchronous:(BOOL)flag
{
_flags.synchronous = flag;
}
- (void)setLayerBacked:(BOOL)isLayerBacked
{
if (![self.class layerBackedNodesEnabled]) return;
ASDN::MutexLocker l(__instanceLock__);
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(__instanceLock__);
return _flags.layerBacked;
}
#pragma mark - Style
- (ASLayoutElementStyle *)style
{
ASDN::MutexLocker l(__instanceLock__);
if (_style == nil) {
_style = [[ASLayoutElementStyle alloc] init];
}
return _style;
}
#pragma mark - Layout
- (ASLayout *)layoutThatFits:(ASSizeRange)constrainedSize
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return [self measureWithSizeRange:constrainedSize];
#pragma clang diagnostic pop
}
- (ASLayout *)layoutThatFits:(ASSizeRange)constrainedSize parentSize:(CGSize)parentSize
{
ASDN::MutexLocker l(__instanceLock__);
if ([self shouldCalculateLayoutWithConstrainedSize:constrainedSize parentSize:parentSize] == NO) {
ASDisplayNodeAssertNotNil(_calculatedDisplayNodeLayout->layout, @"-[ASDisplayNode layoutThatFits:parentSize:] _layout should not be nil! %@", self);
return _calculatedDisplayNodeLayout->layout ? : [ASLayout layoutWithLayoutElement:self size:{0, 0}];
}
[self cancelLayoutTransition];
// Prepare for layout transition
auto previousLayout = _calculatedDisplayNodeLayout;
auto pendingLayout = std::make_shared<ASDisplayNodeLayout>(
[self calculateLayoutThatFits:constrainedSize restrictedToSize:self.style.size relativeToParentSize:parentSize],
constrainedSize,
parentSize
);
_pendingLayoutTransition = [[ASLayoutTransition alloc] initWithNode:self
pendingLayout:pendingLayout
previousLayout:previousLayout];
// Only complete the pending layout transition if the node is not a subnode of a node that is currently
// in a layout transition
if (ASHierarchyStateIncludesLayoutPending(_hierarchyState) == NO) {
// Complete the pending layout transition immediately
[self _completePendingLayoutTransition];
}
ASDisplayNodeAssertNotNil(pendingLayout->layout, @"-[ASDisplayNode layoutThatFits:parentSize:] newLayout should not be nil! %@", self);
return pendingLayout->layout;
}
- (BOOL)shouldCalculateLayoutWithConstrainedSize:(ASSizeRange)constrainedSize parentSize:(CGSize)parentSize
{
ASDN::MutexLocker l(__instanceLock__);
// Don't remeasure if in layout pending state and a new transition already started
if (ASHierarchyStateIncludesLayoutPending(_hierarchyState)) {
ASLayoutElementContext context = ASLayoutElementGetCurrentContext();
if (ASLayoutElementContextIsNull(context) || _pendingTransitionID != context.transitionID) {
return NO;
}
}
// Check if display node layout is still valid
return _calculatedDisplayNodeLayout->isValidForConstrainedSizeParentSize(constrainedSize, parentSize) == NO;
}
- (ASLayoutElementType)layoutElementType
{
return ASLayoutElementTypeDisplayNode;
}
- (BOOL)canLayoutAsynchronous
{
return !self.isNodeLoaded;
}
#pragma mark - Automatic Hierarchy
- (BOOL)automaticallyManagesSubnodes
{
ASDN::MutexLocker l(__instanceLock__);
return _automaticallyManagesSubnodes;
}
- (void)setAutomaticallyManagesSubnodes:(BOOL)automaticallyManagesSubnodes
{
ASDN::MutexLocker l(__instanceLock__);
_automaticallyManagesSubnodes = automaticallyManagesSubnodes;
}
#pragma mark - Layout Transition
- (void)transitionLayoutWithAnimation:(BOOL)animated
shouldMeasureAsync:(BOOL)shouldMeasureAsync
measurementCompletion:(void(^)())completion
{
if (_calculatedDisplayNodeLayout->layout == nil) {
// No measure pass happened before, it's not possible to reuse the constrained size for the transition
// Using CGSizeZero for the sizeRange can cause negative values in client layout code.
return;
}
[self invalidateCalculatedLayout];
[self transitionLayoutWithSizeRange:_calculatedDisplayNodeLayout->constrainedSize
animated:animated
shouldMeasureAsync:shouldMeasureAsync
measurementCompletion:completion];
}
- (void)transitionLayoutWithSizeRange:(ASSizeRange)constrainedSize
animated:(BOOL)animated
shouldMeasureAsync:(BOOL)shouldMeasureAsync
measurementCompletion:(void(^)())completion
{
// Passed constrainedSize is the the same as the node's current constrained size it's a noop
ASDisplayNodeAssertMainThread();
if ([self shouldCalculateLayoutWithConstrainedSize:constrainedSize parentSize:constrainedSize.max] == NO) {
return;
}
{
ASDN::MutexLocker l(__instanceLock__);
ASDisplayNodeAssert(ASHierarchyStateIncludesLayoutPending(_hierarchyState) == NO, @"Can't start a transition when one of the supernodes is performing one.");
}
int32_t transitionID = [self _startNewTransition];
// Move all subnodes in a pending state
ASDisplayNodePerformBlockOnEverySubnode(self, NO, ^(ASDisplayNode * _Nonnull node) {
ASDisplayNodeAssert([node _isTransitionInProgress] == NO, @"Can't start a transition when one of the subnodes is performing one.");
node.hierarchyState |= ASHierarchyStateLayoutPending;
node.pendingTransitionID = transitionID;
});
void (^transitionBlock)(void) = ^{
if ([self _shouldAbortTransitionWithID:transitionID]) {
return;
}
ASLayout *newLayout;
{
ASLayoutElementSetCurrentContext(ASLayoutElementContextMake(transitionID, NO));
ASDN::MutexLocker l(__instanceLock__);
BOOL automaticallyManagesSubnodesDisabled = (self.automaticallyManagesSubnodes == NO);
self.automaticallyManagesSubnodes = YES; // Temporary flag for 1.9.x
newLayout = [self calculateLayoutThatFits:constrainedSize
restrictedToSize:self.style.size
relativeToParentSize:constrainedSize.max];
if (automaticallyManagesSubnodesDisabled) {
self.automaticallyManagesSubnodes = NO; // Temporary flag for 1.9.x
}
ASLayoutElementClearCurrentContext();
}
if ([self _shouldAbortTransitionWithID:transitionID]) {
return;
}
ASPerformBlockOnMainThread(^{
// Grab __instanceLock__ here to make sure this transition isn't invalidated
// right after it passed the validation test and before it proceeds
ASDN::MutexLocker l(__instanceLock__);
if ([self _shouldAbortTransitionWithID:transitionID]) {
return;
}
// Update display node layout
auto previousLayout = _calculatedDisplayNodeLayout;
auto pendingLayout = std::make_shared<ASDisplayNodeLayout>(
newLayout,
constrainedSize,
constrainedSize.max
);
[self setCalculatedDisplayNodeLayout:pendingLayout];
// Apply complete layout transitions for all subnodes
ASDisplayNodePerformBlockOnEverySubnode(self, NO, ^(ASDisplayNode * _Nonnull node) {
[node _completePendingLayoutTransition];
node.hierarchyState &= (~ASHierarchyStateLayoutPending);
});
[self _finishOrCancelTransition];
// Measurement pass completion
if (completion) {
completion();
}
// Setup pending layout transition for animation
_pendingLayoutTransition = [[ASLayoutTransition alloc] initWithNode:self
pendingLayout:pendingLayout
previousLayout:previousLayout];
// Setup context for pending layout transition. we need to hold a strong reference to the context
_pendingLayoutTransitionContext = [[_ASTransitionContext alloc] initWithAnimation:animated
layoutDelegate:_pendingLayoutTransition
completionDelegate:self];
// Apply the subnode insertion immediately to be able to animate the nodes
[_pendingLayoutTransition applySubnodeInsertions];
// Kick off animating the layout transition
[self animateLayoutTransition:_pendingLayoutTransitionContext];
});
};
if (shouldMeasureAsync) {
ASPerformBlockOnBackgroundThread(transitionBlock);
} else {
transitionBlock();
}
}
- (void)cancelLayoutTransition
{
ASDN::MutexLocker l(__instanceLock__);
if ([self _isTransitionInProgress]) {
// Cancel transition in progress
[self _finishOrCancelTransition];
// Tell subnodes to exit layout pending state and clear related properties
ASDisplayNodePerformBlockOnEverySubnode(self, NO, ^(ASDisplayNode * _Nonnull node) {
node.hierarchyState &= (~ASHierarchyStateLayoutPending);
});
}
}
- (BOOL)_isTransitionInProgress
{
ASDN::MutexLocker l(__instanceLock__);
return _transitionInProgress;
}
/// Starts a new transition and returns the transition id
- (int32_t)_startNewTransition
{
ASDN::MutexLocker l(__instanceLock__);
_transitionInProgress = YES;
_transitionID = OSAtomicAdd32(1, &_transitionID);
return _transitionID;
}
- (void)_finishOrCancelTransition
{
ASDN::MutexLocker l(__instanceLock__);
_transitionInProgress = NO;
}
- (BOOL)_shouldAbortTransitionWithID:(int32_t)transitionID
{
ASDN::MutexLocker l(__instanceLock__);
return (!_transitionInProgress || _transitionID != transitionID);
}
#pragma mark Layout Transition API
- (void)setDefaultLayoutTransitionDuration:(NSTimeInterval)defaultLayoutTransitionDuration
{
ASDN::MutexLocker l(__instanceLock__);
_defaultLayoutTransitionDuration = defaultLayoutTransitionDuration;
}
- (NSTimeInterval)defaultLayoutTransitionDuration
{
ASDN::MutexLocker l(__instanceLock__);
return _defaultLayoutTransitionDuration;
}
- (void)setDefaultLayoutTransitionDelay:(NSTimeInterval)defaultLayoutTransitionDelay
{
ASDN::MutexLocker l(__instanceLock__);
_defaultLayoutTransitionDelay = defaultLayoutTransitionDelay;
}
- (NSTimeInterval)defaultLayoutTransitionDelay