forked from TextureGroup/Texture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathASDisplayNode.mm
3860 lines (3212 loc) · 133 KB
/
ASDisplayNode.mm
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
// Texture
//
// Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
// Changes after 4/13/2017 are: Copyright (c) Pinterest, Inc. All rights reserved.
// Licensed under Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0
//
#import <AsyncDisplayKit/ASDisplayNodeInternal.h>
#import <AsyncDisplayKit/ASDisplayNode+Ancestry.h>
#import <AsyncDisplayKit/ASDisplayNode+Beta.h>
#import <AsyncDisplayKit/ASDisplayNode+LayoutSpec.h>
#import <AsyncDisplayKit/AsyncDisplayKit+Debug.h>
#import <AsyncDisplayKit/ASLayoutSpec+Subclasses.h>
#import <AsyncDisplayKit/ASCellNode+Internal.h>
#import <objc/runtime.h>
#include <string>
#import <AsyncDisplayKit/_ASAsyncTransaction.h>
#import <AsyncDisplayKit/_ASAsyncTransactionContainer+Private.h>
#import <AsyncDisplayKit/_ASCoreAnimationExtras.h>
#import <AsyncDisplayKit/_ASDisplayLayer.h>
#import <AsyncDisplayKit/_ASDisplayView.h>
#import <AsyncDisplayKit/_ASPendingState.h>
#import <AsyncDisplayKit/_ASScopeTimer.h>
#import <AsyncDisplayKit/ASDimension.h>
#import <AsyncDisplayKit/ASDisplayNodeExtras.h>
#import <AsyncDisplayKit/ASDisplayNodeInternal.h>
#import <AsyncDisplayKit/ASDisplayNodeCornerLayerDelegate.h>
#import <AsyncDisplayKit/ASDisplayNode+FrameworkPrivate.h>
#import <AsyncDisplayKit/ASDisplayNode+InterfaceState.h>
#import <AsyncDisplayKit/ASDisplayNode+Subclasses.h>
#import <AsyncDisplayKit/ASEqualityHelpers.h>
#import <AsyncDisplayKit/ASGraphicsContext.h>
#import <AsyncDisplayKit/ASInternalHelpers.h>
#import <AsyncDisplayKit/ASLayoutElementStylePrivate.h>
#import <AsyncDisplayKit/ASLayoutSpec.h>
#import <AsyncDisplayKit/ASLayoutSpecPrivate.h>
#import <AsyncDisplayKit/ASLog.h>
#import <AsyncDisplayKit/ASMainThreadDeallocation.h>
#import <AsyncDisplayKit/ASNodeController+Beta.h>
#import <AsyncDisplayKit/ASRunLoopQueue.h>
#import <AsyncDisplayKit/ASSignpost.h>
#import <AsyncDisplayKit/ASTraitCollection.h>
#import <AsyncDisplayKit/ASWeakProxy.h>
#import <AsyncDisplayKit/ASResponderChainEnumerator.h>
#import <AsyncDisplayKit/ASTipsController.h>
// 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
// This is trying to merge non-rangeManaged with rangeManaged, so both range-managed and standalone nodes wait before firing their exit-visibility handlers, as UIViewController transitions now do rehosting at both start & end of animation.
// Enable this will mitigate interface updating state when coalescing disabled.
// TODO(wsdwsd0829): Rework enabling code to ensure that interface state behavior is not altered when ASCATransactionQueue is disabled.
#define ENABLE_NEW_EXIT_HIERARCHY_BEHAVIOR 0
static ASDisplayNodeNonFatalErrorBlock _nonFatalErrorBlock = nil;
// Forward declare CALayerDelegate protocol as the iOS 10 SDK moves CALayerDelegate from an informal 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, CALayerDelegate, _ASDisplayLayerDelegate, ASCATransactionQueueObserving>
/**
* See ASDisplayNodeInternal.h for ivars
*/
@end
@implementation ASDisplayNode
@dynamic layoutElementType;
@synthesize threadSafeBounds = _threadSafeBounds;
static std::atomic_bool suppressesInvalidCollectionUpdateExceptions = ATOMIC_VAR_INIT(NO);
static std::atomic_bool storesUnflattenedLayouts = ATOMIC_VAR_INIT(NO);
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 ASDisplayNodeNeedsSpecialPropertiesHandling(BOOL isSynchronous, BOOL isLayerBacked)
{
return isSynchronous && !isLayerBacked;
}
_ASPendingState *ASDisplayNodeGetPendingState(ASDisplayNode *node)
{
ASLockScope(node);
_ASPendingState *result = node->_pendingViewState;
if (result == nil) {
result = [[_ASPendingState alloc] init];
node->_pendingViewState = result;
}
return result;
}
void StubImplementationWithNoArgs(id receiver) {}
void StubImplementationWithSizeRange(id receiver, ASSizeRange sr) {}
void StubImplementationWithTwoInterfaceStates(id receiver, ASInterfaceState s0, ASInterfaceState s1) {}
/**
* 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);
} else {
flags.implementsDrawParameters = ([c instancesRespondToSelector:@selector(drawParametersForAsyncLayer:)] ? 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;
// Handling touches
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;
}
// Responder chain
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(canBecomeFirstResponder))) {
overrides |= ASDisplayNodeMethodOverrideCanBecomeFirstResponder;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(becomeFirstResponder))) {
overrides |= ASDisplayNodeMethodOverrideBecomeFirstResponder;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(canResignFirstResponder))) {
overrides |= ASDisplayNodeMethodOverrideCanResignFirstResponder;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(resignFirstResponder))) {
overrides |= ASDisplayNodeMethodOverrideResignFirstResponder;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(isFirstResponder))) {
overrides |= ASDisplayNodeMethodOverrideIsFirstResponder;
}
// Layout related methods
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(layoutSpecThatFits:))) {
overrides |= ASDisplayNodeMethodOverrideLayoutSpecThatFits;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(calculateLayoutThatFits:)) ||
ASDisplayNodeSubclassOverridesSelector(c, @selector(calculateLayoutThatFits:
restrictedToSize:
relativeToParentSize:))) {
overrides |= ASDisplayNodeMethodOverrideCalcLayoutThatFits;
}
if (ASDisplayNodeSubclassOverridesSelector(c, @selector(calculateSizeThatFits:))) {
overrides |= ASDisplayNodeMethodOverrideCalcSizeThatFits;
}
return overrides;
}
+ (void)initialize
{
#if ASDISPLAYNODE_ASSERTIONS_ENABLED
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(layoutThatFits:)), @"Subclass %@ must not override layoutThatFits: method. Instead override calculateLayoutThatFits:.", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(layoutThatFits:parentSize:)), @"Subclass %@ must not override layoutThatFits:parentSize method. Instead override calculateLayoutThatFits:.", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(recursivelyClearContents)), @"Subclass %@ must not override recursivelyClearContents method.", classString);
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(recursivelyClearPreloadedData)), @"Subclass %@ must not override recursivelyClearFetchedData method.", classString);
} else {
// Check if subnodes where modified during the creation of the layout
__block IMP originalLayoutSpecThatFitsIMP = ASReplaceMethodWithBlock(self, @selector(_locked_layoutElementThatFits:), ^(ASDisplayNode *_self, ASSizeRange sizeRange) {
NSArray *oldSubnodes = _self.subnodes;
ASLayoutSpec *layoutElement = ((ASLayoutSpec *( *)(id, SEL, ASSizeRange))originalLayoutSpecThatFitsIMP)(_self, @selector(_locked_layoutElementThatFits:), sizeRange);
NSArray *subnodes = _self.subnodes;
ASDisplayNodeAssert(oldSubnodes.count == subnodes.count, @"Adding or removing nodes in layoutSpecBlock or layoutSpecThatFits: is not allowed and can cause unexpected behavior.");
for (NSInteger i = 0; i < oldSubnodes.count; i++) {
ASDisplayNodeAssert(oldSubnodes[i] == subnodes[i], @"Adding or removing nodes in layoutSpecBlock or layoutSpecThatFits: is not allowed and can cause unexpected behavior.");
}
return layoutElement;
});
}
#endif
// 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:@");
// Add stub implementations for global methods that the client didn't
// implement in a category. We do this instead of hard-coding empty
// implementations to avoid a linker warning when it merges categories.
// Note: addMethod will not do anything if a method already exists.
if (self == ASDisplayNode.class) {
IMP noArgsImp = (IMP)StubImplementationWithNoArgs;
class_addMethod(self, @selector(baseDidInit), noArgsImp, "v@:");
class_addMethod(self, @selector(baseWillDealloc), noArgsImp, "v@:");
class_addMethod(self, @selector(didLoad), noArgsImp, "v@:");
class_addMethod(self, @selector(layoutDidFinish), noArgsImp, "v@:");
class_addMethod(self, @selector(didEnterPreloadState), noArgsImp, "v@:");
class_addMethod(self, @selector(didExitPreloadState), noArgsImp, "v@:");
class_addMethod(self, @selector(didEnterDisplayState), noArgsImp, "v@:");
class_addMethod(self, @selector(didExitDisplayState), noArgsImp, "v@:");
class_addMethod(self, @selector(didEnterVisibleState), noArgsImp, "v@:");
class_addMethod(self, @selector(didExitVisibleState), noArgsImp, "v@:");
class_addMethod(self, @selector(hierarchyDisplayDidFinish), noArgsImp, "v@:");
class_addMethod(self, @selector(asyncTraitCollectionDidChange), noArgsImp, "v@:");
class_addMethod(self, @selector(calculatedLayoutDidChange), noArgsImp, "v@:");
auto type0 = "v@:" + std::string(@encode(ASSizeRange));
class_addMethod(self, @selector(willCalculateLayout:), (IMP)StubImplementationWithSizeRange, type0.c_str());
auto interfaceStateType = std::string(@encode(ASInterfaceState));
auto type1 = "v@:" + interfaceStateType + interfaceStateType;
class_addMethod(self, @selector(interfaceStateDidChange:fromState:), (IMP)StubImplementationWithTwoInterfaceStates, type1.c_str());
}
}
#if !AS_INITIALIZE_FRAMEWORK_MANUALLY
+ (void)load
{
ASInitializeFrameworkMainThread();
}
#endif
+ (Class)viewClass
{
return [_ASDisplayView class];
}
+ (Class)layerClass
{
return [_ASDisplayLayer class];
}
#pragma mark - Lifecycle
- (void)_staticInitialize
{
ASDisplayNodeAssert(NO, @"_staticInitialize must be overridden");
}
- (void)_initializeInstance
{
[self _staticInitialize];
#if ASEVENTLOG_ENABLE
_eventLog = [[ASEventLog alloc] initWithObject:self];
#endif
_viewClass = [self.class viewClass];
_layerClass = [self.class layerClass];
BOOL isSynchronous = ![_viewClass isSubclassOfClass:[_ASDisplayView class]]
|| ![_layerClass isSubclassOfClass:[_ASDisplayLayer class]];
setFlag(Synchronous, isSynchronous);
_contentsScaleForDisplay = ASScreenScale();
_drawingPriority = ASDefaultTransactionPriority;
_primitiveTraitCollection = ASPrimitiveTraitCollectionMakeDefault();
_layoutVersion = 1;
_defaultLayoutTransitionDuration = 0.2;
_defaultLayoutTransitionDelay = 0.0;
_defaultLayoutTransitionOptions = UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionTransitionNone;
_flags.canClearContentsOfLayer = YES;
_flags.canCallSetNeedsDisplayOfLayer = YES;
_fallbackSafeAreaInsets = UIEdgeInsetsZero;
_fallbackInsetsLayoutMarginsFromSafeArea = YES;
_isViewControllerRoot = NO;
_automaticallyRelayoutOnSafeAreaChanges = NO;
_automaticallyRelayoutOnLayoutMarginsChanges = NO;
[self baseDidInit];
ASDisplayNodeLogEvent(self, @"init");
}
- (instancetype)init
{
if (!(self = [super init]))
return nil;
[self _initializeInstance];
return self;
}
- (instancetype)initWithViewClass:(Class)viewClass
{
if (!(self = [self init]))
return nil;
ASDisplayNodeAssert([viewClass isSubclassOfClass:[UIView class]], @"should initialize with a subclass of UIView");
_viewClass = viewClass;
setFlag(Synchronous, ![viewClass isSubclassOfClass:[_ASDisplayView class]]);
return self;
}
- (instancetype)initWithLayerClass:(Class)layerClass
{
if (!(self = [self init])) {
return nil;
}
ASDisplayNodeAssert([layerClass isSubclassOfClass:[CALayer class]], @"should initialize with a subclass of CALayer");
_layerClass = layerClass;
_flags.layerBacked = YES;
setFlag(Synchronous, ![layerClass isSubclassOfClass:[_ASDisplayLayer class]]);
return self;
}
- (instancetype)initWithViewBlock:(ASDisplayNodeViewBlock)viewBlock
{
return [self initWithViewBlock:viewBlock didLoadBlock:nil];
}
- (instancetype)initWithViewBlock:(ASDisplayNodeViewBlock)viewBlock didLoadBlock:(ASDisplayNodeDidLoadBlock)didLoadBlock
{
if (!(self = [self init])) {
return nil;
}
[self setViewBlock:viewBlock];
if (didLoadBlock != nil) {
[self onDidLoad:didLoadBlock];
}
return self;
}
- (instancetype)initWithLayerBlock:(ASDisplayNodeLayerBlock)layerBlock
{
return [self initWithLayerBlock:layerBlock didLoadBlock:nil];
}
- (instancetype)initWithLayerBlock:(ASDisplayNodeLayerBlock)layerBlock didLoadBlock:(ASDisplayNodeDidLoadBlock)didLoadBlock
{
if (!(self = [self init])) {
return nil;
}
[self setLayerBlock:layerBlock];
if (didLoadBlock != nil) {
[self onDidLoad:didLoadBlock];
}
return self;
}
ASSynthesizeLockingMethodsWithMutex(__instanceLock__);
- (void)setViewBlock:(ASDisplayNodeViewBlock)viewBlock
{
ASDisplayNodeAssertFalse(self.nodeLoaded);
ASDisplayNodeAssertNotNil(viewBlock, @"should initialize with a valid block that returns a UIView");
_viewBlock = viewBlock;
setFlag(Synchronous, YES);
}
- (void)setLayerBlock:(ASDisplayNodeLayerBlock)layerBlock
{
ASDisplayNodeAssertFalse(self.nodeLoaded);
ASDisplayNodeAssertNotNil(layerBlock, @"should initialize with a valid block that returns a CALayer");
_layerBlock = layerBlock;
_flags.layerBacked = YES;
setFlag(Synchronous, YES);
}
- (ASDisplayNodeMethodOverrides)methodOverrides
{
return _methodOverrides;
}
- (void)onDidLoad:(ASDisplayNodeDidLoadBlock)body
{
ASDN::UniqueLock l(__instanceLock__);
if ([self _locked_isNodeLoaded]) {
ASDisplayNodeAssertThreadAffinity(self);
l.unlock();
body(self);
return;
} else if (_onDidLoadBlocks == nil) {
_onDidLoadBlocks = [NSMutableArray arrayWithObject:body];
} else {
[_onDidLoadBlocks addObject:body];
}
}
- (void)dealloc
{
_flags.isDeallocating = YES;
[self baseWillDealloc];
// Synchronous nodes may not be able to call the hierarchy notifications, so only enforce for regular nodes.
ASDisplayNodeAssert(checkFlag(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];
[self scheduleIvarsForMainThreadDeallocation];
// TODO: Remove this? If supernode isn't already nil, this method isn't dealloc-safe anyway.
[self _setSupernode:nil];
}
#pragma mark - Loading
- (BOOL)_locked_shouldLoadViewOrLayer
{
ASAssertLocked(__instanceLock__);
return !_flags.isDeallocating && !(_hierarchyState & ASHierarchyStateRasterized);
}
- (UIView *)_locked_viewToLoad
{
ASAssertLocked(__instanceLock__);
UIView *view = nil;
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 {
view = [[_viewClass alloc] init];
}
// Special handling of wrapping UIKit components
if (checkFlag(Synchronous)) {
[self checkResponderCompatibility];
// UIImageView layers. More details on the flags
if ([_viewClass isSubclassOfClass:[UIImageView class]]) {
_flags.canClearContentsOfLayer = NO;
_flags.canCallSetNeedsDisplayOfLayer = NO;
}
// UIActivityIndicator
if ([_viewClass isSubclassOfClass:[UIActivityIndicatorView class]]
|| [_viewClass isSubclassOfClass:[UIVisualEffectView class]]) {
self.opaque = NO;
}
// CAEAGLLayer
if([[view.layer class] isSubclassOfClass:[CAEAGLLayer class]]){
_flags.canClearContentsOfLayer = NO;
}
}
return view;
}
- (CALayer *)_locked_layerToLoad
{
ASAssertLocked(__instanceLock__);
ASDisplayNodeAssert(_flags.layerBacked, @"_layerToLoad is only for layer-backed nodes");
CALayer *layer = nil;
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 {
layer = [[_layerClass alloc] init];
}
return layer;
}
- (void)_locked_loadViewOrLayer
{
ASAssertLocked(__instanceLock__);
if (_flags.layerBacked) {
TIME_SCOPED(_debugTimeToCreateView);
_layer = [self _locked_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 _locked_viewToLoad];
_view.asyncdisplaykit_node = self;
_layer = _view.layer;
}
_layer.asyncdisplaykit_node = self;
self._locked_asyncLayer.asyncDelegate = self;
}
- (void)_didLoad
{
ASDisplayNodeAssertMainThread();
ASAssertUnlocked(__instanceLock__);
ASDisplayNodeLogEvent(self, @"didLoad");
as_log_verbose(ASNodeLog(), "didLoad %@", self);
TIME_SCOPED(_debugTimeForDidLoad);
[self didLoad];
__instanceLock__.lock();
const auto onDidLoadBlocks = ASTransferStrong(_onDidLoadBlocks);
__instanceLock__.unlock();
for (ASDisplayNodeDidLoadBlock block in onDidLoadBlocks) {
block(self);
}
[self enumerateInterfaceStateDelegates:^(id<ASInterfaceStateDelegate> del) {
[del nodeDidLoad];
}];
}
- (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 _loaded(self);
} else {
ASDN::MutexLocker l(__instanceLock__);
return [self _locked_isNodeLoaded];
}
}
- (BOOL)_locked_isNodeLoaded
{
ASAssertLocked(__instanceLock__);
return _loaded(self);
}
#pragma mark - Misc Setter / Getter
- (UIView *)view
{
ASDN::UniqueLock l(__instanceLock__);
ASDisplayNodeAssert(!_flags.layerBacked, @"Call to -view undefined on layer-backed nodes");
BOOL isLayerBacked = _flags.layerBacked;
if (isLayerBacked) {
return nil;
}
if (_view != nil) {
return _view;
}
if (![self _locked_shouldLoadViewOrLayer]) {
return nil;
}
// Loading a view needs to happen on the main thread
ASDisplayNodeAssertMainThread();
[self _locked_loadViewOrLayer];
// FIXME: Ideally we'd call this as soon as the node receives -setNeedsLayout
// but automatic subnode management would require us to modify the node tree
// in the background on a loaded node, which isn't currently supported.
if (_pendingViewState.hasSetNeedsLayout) {
// Need to unlock before calling setNeedsLayout to avoid deadlocks.
l.unlock();
[self __setNeedsLayout];
l.lock();
}
[self _locked_applyPendingStateToViewOrLayer];
// The following methods should not be called with a lock
l.unlock();
// No need for the lock as accessing the subviews or layers are always happening on main
[self _addSubnodeViewsAndLayers];
// A subclass hook should never be called with a lock
[self _didLoad];
return _view;
}
- (CALayer *)layer
{
ASDN::UniqueLock l(__instanceLock__);
if (_layer != nil) {
return _layer;
}
if (![self _locked_shouldLoadViewOrLayer]) {
return nil;
}
// Loading a layer needs to happen on the main thread
ASDisplayNodeAssertMainThread();
[self _locked_loadViewOrLayer];
CALayer *layer = _layer;
// FIXME: Ideally we'd call this as soon as the node receives -setNeedsLayout
// but automatic subnode management would require us to modify the node tree
// in the background on a loaded node, which isn't currently supported.
if (_pendingViewState.hasSetNeedsLayout) {
// Need to unlock before calling setNeedsLayout to avoid deadlocks.
l.unlock();
[self __setNeedsLayout];
l.lock();
}
[self _locked_applyPendingStateToViewOrLayer];
// The following methods should not be called with a lock
l.unlock();
// No need for the lock as accessing the subviews or layers are always happening on main
[self _addSubnodeViewsAndLayers];
// A subclass hook should never be called with a lock
[self _didLoad];
return layer;
}
// Returns nil if the layer is not an _ASDisplayLayer; will not create the layer if nil.
- (_ASDisplayLayer *)asyncLayer
{
ASDN::MutexLocker l(__instanceLock__);
return [self _locked_asyncLayer];
}
- (_ASDisplayLayer *)_locked_asyncLayer
{
ASAssertLocked(__instanceLock__);
return [_layer isKindOfClass:[_ASDisplayLayer class]] ? (_ASDisplayLayer *)_layer : nil;
}
- (BOOL)isSynchronous
{
return checkFlag(Synchronous);
}
- (void)setLayerBacked:(BOOL)isLayerBacked
{
// Only call this if assertions are enabled – it could be expensive.
ASDisplayNodeAssert(!isLayerBacked || self.supportsLayerBacking, @"Node %@ does not support layer backing.", self);
ASDN::MutexLocker l(__instanceLock__);
if (_flags.layerBacked == isLayerBacked) {
return;
}
if ([self _locked_isNodeLoaded]) {
ASDisplayNodeFailAssert(@"Cannot change layerBacked after view/layer has loaded.");
return;
}
_flags.layerBacked = isLayerBacked;
}
- (BOOL)isLayerBacked
{
ASDN::MutexLocker l(__instanceLock__);
return _flags.layerBacked;
}
- (BOOL)supportsLayerBacking
{
ASDN::MutexLocker l(__instanceLock__);
return !checkFlag(Synchronous) && !_flags.viewEverHadAGestureRecognizerAttached && _viewClass == [_ASDisplayView class] && _layerClass == [_ASDisplayLayer class];
}
- (BOOL)shouldAnimateSizeChanges
{
ASDN::MutexLocker l(__instanceLock__);
return _flags.shouldAnimateSizeChanges;
}
- (void)setShouldAnimateSizeChanges:(BOOL)shouldAnimateSizeChanges
{
ASDN::MutexLocker l(__instanceLock__);
_flags.shouldAnimateSizeChanges = shouldAnimateSizeChanges;
}
- (CGRect)threadSafeBounds
{
ASDN::MutexLocker l(__instanceLock__);
return [self _locked_threadSafeBounds];
}
- (CGRect)_locked_threadSafeBounds
{
ASAssertLocked(__instanceLock__);
return _threadSafeBounds;
}
- (void)setThreadSafeBounds:(CGRect)newBounds
{
ASDN::MutexLocker l(__instanceLock__);
_threadSafeBounds = newBounds;
}
- (void)nodeViewDidAddGestureRecognizer
{
ASDN::MutexLocker l(__instanceLock__);
_flags.viewEverHadAGestureRecognizerAttached = YES;
}
- (UIEdgeInsets)fallbackSafeAreaInsets
{
ASDN::MutexLocker l(__instanceLock__);
return _fallbackSafeAreaInsets;
}
- (void)setFallbackSafeAreaInsets:(UIEdgeInsets)insets
{
BOOL needsManualUpdate;
BOOL updatesLayoutMargins;
{
ASDN::MutexLocker l(__instanceLock__);
ASDisplayNodeAssertThreadAffinity(self);
if (UIEdgeInsetsEqualToEdgeInsets(insets, _fallbackSafeAreaInsets)) {
return;
}
_fallbackSafeAreaInsets = insets;
needsManualUpdate = !AS_AT_LEAST_IOS11 || _flags.layerBacked;
updatesLayoutMargins = needsManualUpdate && [self _locked_insetsLayoutMarginsFromSafeArea];
}
if (needsManualUpdate) {
[self safeAreaInsetsDidChange];
}
if (updatesLayoutMargins) {
[self layoutMarginsDidChange];
}
}
- (void)_fallbackUpdateSafeAreaOnChildren
{
ASDisplayNodeAssertThreadAffinity(self);
UIEdgeInsets insets = self.safeAreaInsets;
CGRect bounds = self.bounds;
for (ASDisplayNode *child in self.subnodes) {
if (AS_AT_LEAST_IOS11 && !child.layerBacked) {
// In iOS 11 view-backed nodes already know what their safe area is.
continue;
}
if (child.viewControllerRoot) {
// Its safe area is controlled by a view controller. Don't override it.
continue;
}
CGRect childFrame = child.frame;
UIEdgeInsets childInsets = UIEdgeInsetsMake(MAX(insets.top - (CGRectGetMinY(childFrame) - CGRectGetMinY(bounds)), 0),
MAX(insets.left - (CGRectGetMinX(childFrame) - CGRectGetMinX(bounds)), 0),
MAX(insets.bottom - (CGRectGetMaxY(bounds) - CGRectGetMaxY(childFrame)), 0),
MAX(insets.right - (CGRectGetMaxX(bounds) - CGRectGetMaxX(childFrame)), 0));
child.fallbackSafeAreaInsets = childInsets;
}
}
- (BOOL)isViewControllerRoot
{
ASDN::MutexLocker l(__instanceLock__);
return _isViewControllerRoot;
}
- (void)setViewControllerRoot:(BOOL)flag
{
ASDN::MutexLocker l(__instanceLock__);
_isViewControllerRoot = flag;
}
- (BOOL)automaticallyRelayoutOnSafeAreaChanges
{
ASDN::MutexLocker l(__instanceLock__);
return _automaticallyRelayoutOnSafeAreaChanges;
}
- (void)setAutomaticallyRelayoutOnSafeAreaChanges:(BOOL)flag
{
ASDN::MutexLocker l(__instanceLock__);
_automaticallyRelayoutOnSafeAreaChanges = flag;
}
- (BOOL)automaticallyRelayoutOnLayoutMarginsChanges
{
ASDN::MutexLocker l(__instanceLock__);
return _automaticallyRelayoutOnLayoutMarginsChanges;
}
- (void)setAutomaticallyRelayoutOnLayoutMarginsChanges:(BOOL)flag
{
ASDN::MutexLocker l(__instanceLock__);
_automaticallyRelayoutOnLayoutMarginsChanges = flag;
}
- (void)__setNodeController:(ASNodeController *)controller
{
// See docs for why we don't lock.
if (controller.shouldInvertStrongReference) {
_strongNodeController = controller;
_weakNodeController = nil;
} else {
_weakNodeController = controller;
_strongNodeController = nil;
}
}
#pragma mark - UIResponder
#define HANDLE_NODE_RESPONDER_METHOD(__sel) \
/* All responder methods should be called on the main thread */ \
ASDisplayNodeAssertMainThread(); \
if (checkFlag(Synchronous)) { \
/* If the view is not a _ASDisplayView subclass (Synchronous) just call through to the view as we
expect it's a non _ASDisplayView subclass that will respond */ \
return [_view __sel]; \
} else { \
if (ASSubclassOverridesSelector([_ASDisplayView class], _viewClass, @selector(__sel))) { \
/* If the subclass overwrites canBecomeFirstResponder just call through
to it as we expect it will handle it */ \
return [_view __sel]; \
} else { \
/* Call through to _ASDisplayView's superclass to get it handled */ \
return [(_ASDisplayView *)_view __##__sel]; \
} \
} \
- (void)checkResponderCompatibility
{
#if ASDISPLAYNODE_ASSERTIONS_ENABLED
// There are certain cases we cannot handle and are not supported:
// 1. If the _view class is not a subclass of _ASDisplayView
if (checkFlag(Synchronous)) {
// 2. At least one UIResponder methods are overwritten in the node subclass
NSString *message = @"Overwritting %@ and having a backing view that is not an _ASDisplayView is not supported.";
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self.class, @selector(canBecomeFirstResponder)), ([NSString stringWithFormat:message, @"canBecomeFirstResponder"]));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self.class, @selector(becomeFirstResponder)), ([NSString stringWithFormat:message, @"becomeFirstResponder"]));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self.class, @selector(canResignFirstResponder)), ([NSString stringWithFormat:message, @"canResignFirstResponder"]));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self.class, @selector(resignFirstResponder)), ([NSString stringWithFormat:message, @"resignFirstResponder"]));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self.class, @selector(isFirstResponder)), ([NSString stringWithFormat:message, @"isFirstResponder"]));
}
#endif
}
- (BOOL)__canBecomeFirstResponder
{
if (_view == nil) {
// By default we return NO if not view is created yet
return NO;
}
HANDLE_NODE_RESPONDER_METHOD(canBecomeFirstResponder);
}
- (BOOL)__becomeFirstResponder
{
// Note: This implicitly loads the view if it hasn't been loaded yet.
[self view];
if (![self canBecomeFirstResponder]) {
return NO;
}
HANDLE_NODE_RESPONDER_METHOD(becomeFirstResponder);
}
- (BOOL)__canResignFirstResponder
{
if (_view == nil) {
// By default we return YES if no view is created yet
return YES;
}
HANDLE_NODE_RESPONDER_METHOD(canResignFirstResponder);
}
- (BOOL)__resignFirstResponder
{
// Note: This implicitly loads the view if it hasn't been loaded yet.
[self view];
if (![self canResignFirstResponder]) {
return NO;
}
HANDLE_NODE_RESPONDER_METHOD(resignFirstResponder);
}
- (BOOL)__isFirstResponder
{
if (_view == nil) {
// If no view is created yet we can just return NO as it's unlikely it's the first responder
return NO;
}
HANDLE_NODE_RESPONDER_METHOD(isFirstResponder);
}