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
2927 lines (2415 loc) · 97.2 KB
/
ASDisplayNode.mm
File metadata and controls
2927 lines (2415 loc) · 97.2 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 "ASDisplayNodeInternal.h"
#import "ASDisplayNode+Subclasses.h"
#import "ASDisplayNode+FrameworkPrivate.h"
#import "ASDisplayNode+Beta.h"
#import <objc/runtime.h>
#import <deque>
#import "_ASAsyncTransaction.h"
#import "_ASAsyncTransactionContainer+Private.h"
#import "_ASPendingState.h"
#import "_ASDisplayView.h"
#import "_ASScopeTimer.h"
#import "_ASCoreAnimationExtras.h"
#import "ASDisplayNodeLayoutContext.h"
#import "ASDisplayNodeExtras.h"
#import "ASTraitCollection.h"
#import "ASEqualityHelpers.h"
#import "ASRunLoopQueue.h"
#import "ASEnvironmentInternal.h"
#import "ASInternalHelpers.h"
#import "ASLayout.h"
#import "ASLayoutSpec.h"
#import "ASCellNode.h"
NSInteger const ASDefaultDrawingPriority = ASDefaultTransactionPriority;
NSString * const ASRenderingEngineDidDisplayScheduledNodesNotification = @"ASRenderingEngineDidDisplayScheduledNodes";
NSString * const ASRenderingEngineDidDisplayNodesScheduledBeforeTimestamp = @"ASRenderingEngineDidDisplayNodesScheduledBeforeTimestamp";
@interface ASDisplayNode () <UIGestureRecognizerDelegate, _ASDisplayLayerDelegate, _ASTransitionContextCompletionDelegate>
/**
*
* See ASDisplayNodeInternal.h for ivars
*
*/
- (void)_staticInitialize;
@end
//#define LOG(...) NSLog(__VA_ARGS__)
#define LOG(...)
// 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
// these dynamic properties all defined in ASLayoutOptionsPrivate.m
@dynamic spacingAfter, spacingBefore, flexGrow, flexShrink, flexBasis, alignSelf, ascender, descender, sizeRange, layoutPosition;
@synthesize name = _name;
@synthesize preferredFrameSize = _preferredFrameSize;
@synthesize isFinalLayoutable = _isFinalLayoutable;
@synthesize threadSafeBounds = _threadSafeBounds;
static BOOL usesImplicitHierarchyManagement = NO;
+ (BOOL)usesImplicitHierarchyManagement
{
return usesImplicitHierarchyManagement;
}
+ (void)setUsesImplicitHierarchyManagement:(BOOL)enabled
{
usesImplicitHierarchyManagement = enabled;
}
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->_propertyLock);
_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
{
if (self != [ASDisplayNode class]) {
// Subclasses should never override these
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(calculatedSize)), @"Subclass %@ must not override calculatedSize method", NSStringFromClass(self));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(calculatedLayout)), @"Subclass %@ must not override calculatedLayout method", NSStringFromClass(self));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(measure:)), @"Subclass %@ must not override measure method", NSStringFromClass(self));
ASDisplayNodeAssert(!ASDisplayNodeSubclassOverridesSelector(self, @selector(measureWithSizeRange:)), @"Subclass %@ must not override measureWithSizeRange 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));
}
// 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);
IMP staticInitialize = imp_implementationWithBlock(^(ASDisplayNode *node) {
node->_flags = (classOverridesRespondsToSelector || instancesOverrideRespondsToSelector) ? GetASDisplayNodeFlags(node.class, node) : flags;
node->_methodOverrides = (classOverridesRespondsToSelector) ? GetASDisplayNodeMethodOverrides(node.class) : methodOverrides;
});
class_replaceMethod(self, @selector(_staticInitialize), staticInitialize, "v:@");
}
+ (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) {
CFAbsoluteTime timestamp = isQueueDrained ? CFAbsoluteTimeGetCurrent() : 0;
[dequeuedItem _recursivelyTriggerDisplayAndBlock:NO];
if (isQueueDrained) {
[[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];
_contentsScaleForDisplay = ASScreenScale();
_displaySentinel = [[ASSentinel alloc] init];
_preferredFrameSize = CGSizeZero;
_environmentState = ASEnvironmentStateMakeDefault();
}
- (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;
_nodeLoadedBlock = didLoadBlock;
_flags.synchronous = YES;
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;
_nodeLoadedBlock = didLoadBlock;
_flags.synchronous = YES;
_flags.layerBacked = YES;
return self;
}
- (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; interfaceState: %lu, %@", (unsigned long)_interfaceState, 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;
if (_flags.layerBacked)
_layer.delegate = nil;
_layer = nil;
[self __setSupernode:nil];
_pendingViewState = nil;
_displaySentinel = nil;
_pendingDisplayNodes = nil;
}
#pragma mark - Core
- (void)__unloadNode
{
ASDisplayNodeAssertThreadAffinity(self);
ASDisplayNodeAssert([self isNodeLoaded], @"Implementation shouldn't call __unloadNode if not loaded: %@", self);
ASDN::MutexLocker l(_propertyLock);
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);
}
- (BOOL)__shouldSize
{
return YES;
}
- (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);
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(_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;
self.asyncLayer.asyncDelegate = self;
{
TIME_SCOPED(_debugTimeToApplyPendingState);
[self _applyPendingStateToViewOrLayer];
}
{
TIME_SCOPED(_debugTimeToAddSubnodeViews);
[self _addSubnodeViewsAndLayers];
}
{
TIME_SCOPED(_debugTimeForDidLoad);
[self __didLoad];
}
}
- (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
{
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 (_view != nil || (_layer != nil && _flags.layerBacked));
} else {
ASDN::MutexLocker l(_propertyLock);
return (_view != nil || (_layer != nil && _flags.layerBacked));
}
}
- (NSString *)name
{
ASDN::MutexLocker l(_propertyLock);
return _name;
}
- (void)setName:(NSString *)name
{
ASDN::MutexLocker l(_propertyLock);
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(_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 - Layout measurement calculation
- (CGSize)measure:(CGSize)constrainedSize
{
return [self measureWithSizeRange:ASSizeRangeMake(CGSizeZero, constrainedSize)].size;
}
- (ASLayout *)measureWithSizeRange:(ASSizeRange)constrainedSize
{
ASDN::MutexLocker l(_propertyLock);
if (! [self shouldMeasureWithSizeRange:constrainedSize]) {
return _layout;
}
[self cancelLayoutTransitionsInProgress];
ASLayout *previousLayout = _layout;
ASSizeRange previousConstrainedSize = _constrainedSize;
ASLayout *newLayout = [self calculateLayoutThatFits:constrainedSize];
if (ASHierarchyStateIncludesLayoutPending(_hierarchyState)) {
_pendingLayoutContext = [[ASDisplayNodeLayoutContext alloc] initWithNode:self
pendingLayout:newLayout
pendingConstrainedSize:constrainedSize
previousLayout:previousLayout
previousConstrainedSize:previousConstrainedSize];
} else {
ASDisplayNodeLayoutContext *layoutContext;
if (self.usesImplicitHierarchyManagement) {
layoutContext = [[ASDisplayNodeLayoutContext alloc] initWithNode:self
pendingLayout:newLayout
pendingConstrainedSize:constrainedSize
previousLayout:previousLayout
previousConstrainedSize:previousConstrainedSize];
}
[self applyLayout:newLayout constrainedSize:constrainedSize layoutContext:layoutContext];
[self _completeLayoutCalculation];
}
return newLayout;
}
- (BOOL)shouldMeasureWithSizeRange:(ASSizeRange)constrainedSize
{
ASDN::MutexLocker l(_propertyLock);
if (![self __shouldSize]) {
return NO;
}
if (ASHierarchyStateIncludesLayoutPending(_hierarchyState)) {
ASLayoutableContext context = ASLayoutableGetCurrentContext();
if (ASLayoutableContextIsNull(context) || _pendingTransitionID != context.transitionID) {
return NO;
}
}
// only calculate the size if
// - we haven't already
// - the constrained size range is different
return (!_flags.isMeasured || !ASSizeRangeEqualToSizeRange(constrainedSize, _constrainedSize));
}
#pragma mark - Layout Transition
- (void)transitionLayoutWithAnimation:(BOOL)animated
shouldMeasureAsync:(BOOL)shouldMeasureAsync
measurementCompletion:(void(^)())completion
{
ASSizeRange currentConstrainedSize = _constrainedSize;
[self invalidateCalculatedLayout];
[self transitionLayoutWithSizeRange:currentConstrainedSize
animated:animated
shouldMeasureAsync:shouldMeasureAsync
measurementCompletion:completion];
}
- (void)transitionLayoutWithSizeRange:(ASSizeRange)constrainedSize
animated:(BOOL)animated
shouldMeasureAsync:(BOOL)shouldMeasureAsync
measurementCompletion:(void(^)())completion
{
ASDisplayNodeAssertMainThread();
if (! [self shouldMeasureWithSizeRange:constrainedSize]) {
return;
}
{
ASDN::MutexLocker l(_propertyLock);
ASDisplayNodeAssert(ASHierarchyStateIncludesLayoutPending(_hierarchyState) == NO, @"Can't start a transition when one of the supernodes is performing one.");
}
int32_t transitionID = [self _startNewTransition];
ASDisplayNodePerformBlockOnEverySubnode(self, ^(ASDisplayNode * _Nonnull node) {
ASDisplayNodeAssert([node _hasTransitionInProgress] == NO, @"Can't start a transition when one of the subnodes is performing one.");
node.hierarchyState |= ASHierarchyStateLayoutPending;
node.pendingTransitionID = transitionID;
});
void (^transitionBlock)() = ^{
if ([self _shouldAbortTransitionWithID:transitionID]) {
return;
}
ASLayout *newLayout;
{
ASLayoutableSetCurrentContext(ASLayoutableContextMake(transitionID, NO));
ASDN::MutexLocker l(_propertyLock);
BOOL disableImplicitHierarchyManagement = self.usesImplicitHierarchyManagement == NO;
self.usesImplicitHierarchyManagement = YES; // Temporary flag for 1.9.x
newLayout = [self calculateLayoutThatFits:constrainedSize];
if (disableImplicitHierarchyManagement) {
self.usesImplicitHierarchyManagement = NO; // Temporary flag for 1.9.x
}
ASLayoutableClearCurrentContext();
}
if ([self _shouldAbortTransitionWithID:transitionID]) {
return;
}
ASPerformBlockOnMainThread(^{
// Grab _propertyLock here to make sure this transition isn't invalidated
// right after it passed the validation test and before it proceeds
ASDN::MutexLocker l(_propertyLock);
if ([self _shouldAbortTransitionWithID:transitionID]) {
return;
}
ASLayout *previousLayout = _layout;
ASSizeRange previousConstrainedSize = _constrainedSize;
[self applyLayout:newLayout constrainedSize:constrainedSize layoutContext:nil];
ASDisplayNodePerformBlockOnEverySubnode(self, ^(ASDisplayNode * _Nonnull node) {
[node applyPendingLayoutContext];
[node _completeLayoutCalculation];
node.hierarchyState &= (~ASHierarchyStateLayoutPending);
});
[self _finishOrCancelTransition];
if (completion) {
completion();
}
_pendingLayoutContext = [[ASDisplayNodeLayoutContext alloc] initWithNode:self
pendingLayout:newLayout
pendingConstrainedSize:constrainedSize
previousLayout:previousLayout
previousConstrainedSize:previousConstrainedSize];
[_pendingLayoutContext applySubnodeInsertions];
_transitionContext = [[_ASTransitionContext alloc] initWithAnimation:animated
layoutDelegate:_pendingLayoutContext
completionDelegate:self];
[self animateLayoutTransition:_transitionContext];
});
};
if (shouldMeasureAsync) {
ASPerformBlockOnBackgroundThread(transitionBlock);
} else {
transitionBlock();
}
}
- (void)_completeLayoutCalculation
{
ASDN::MutexLocker l(_propertyLock);
[self calculatedLayoutDidChange];
// We generate placeholders at measureWithSizeRange: time so that a node is guaranteed to have a placeholder ready to go.
// This is also because measurement is usually asynchronous, but placeholders need to be set up synchronously.
// First measurement is guaranteed to be before the node is onscreen, so we can create the image async. but still have it appear sync.
if (_placeholderEnabled && [self _displaysAsynchronously] && self.contents == nil) {
// Zero-sized nodes do not require a placeholder.
CGSize layoutSize = (_layout ? _layout.size : CGSizeZero);
if (CGSizeEqualToSize(layoutSize, CGSizeZero)) {
return;
}
if (!_placeholderImage) {
_placeholderImage = [self placeholderImage];
}
}
}
- (void)calculatedLayoutDidChange
{
// subclass override
}
- (void)cancelLayoutTransitionsInProgress
{
ASDN::MutexLocker l(_propertyLock);
if ([self _hasTransitionInProgress]) {
// Cancel transition in progress
[self _finishOrCancelTransition];
// Tell subnodes to exit layout pending state and clear related properties
ASDisplayNodePerformBlockOnEverySubnode(self, ^(ASDisplayNode * _Nonnull node) {
node.hierarchyState &= (~ASHierarchyStateLayoutPending);
});
}
}
- (BOOL)usesImplicitHierarchyManagement
{
ASDN::MutexLocker l(_propertyLock);
return _usesImplicitHierarchyManagement ? : [[self class] usesImplicitHierarchyManagement];
}
- (void)setUsesImplicitHierarchyManagement:(BOOL)value
{
ASDN::MutexLocker l(_propertyLock);
_usesImplicitHierarchyManagement = value;
}
- (BOOL)_hasTransitionInProgress
{
ASDN::MutexLocker l(_propertyLock);
return _transitionInProgress;
}
/// Starts a new transition and returns the transition id
- (int32_t)_startNewTransition
{
ASDN::MutexLocker l(_propertyLock);
_transitionInProgress = YES;
_transitionID = OSAtomicAdd32(1, &_transitionID);
return _transitionID;
}
- (void)_finishOrCancelTransition
{
ASDN::MutexLocker l(_propertyLock);
_transitionInProgress = NO;
}
- (BOOL)_shouldAbortTransitionWithID:(int32_t)transitionID
{
ASDN::MutexLocker l(_propertyLock);
return (!_transitionInProgress || _transitionID != transitionID);
}
- (void)animateLayoutTransition:(id<ASContextTransitioning>)context
{
[self __layoutSublayouts];
[context completeTransition:YES];
}
- (void)didCompleteLayoutTransition:(id<ASContextTransitioning>)context
{
[_pendingLayoutContext applySubnodeRemovals];
[self _completeLayoutCalculation];
_pendingLayoutContext = nil;
}
#pragma mark - _ASTransitionContextCompletionDelegate
- (void)transitionContext:(_ASTransitionContext *)context didComplete:(BOOL)didComplete
{
[self didCompleteLayoutTransition:context];
_transitionContext = nil;
}
#pragma mark - Asynchronous display
- (BOOL)displaysAsynchronously
{
ASDN::MutexLocker l(_propertyLock);
return [self _displaysAsynchronously];
}
/**
* Core implementation of -displaysAsynchronously.
* Must be called with _propertyLock held.
*/
- (BOOL)_displaysAsynchronously
{
ASDisplayNodeAssertThreadAffinity(self);
return _flags.synchronous == NO && _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
{
ASDN::MutexLocker l(_propertyLock);
ASDisplayNodeAssert(!((_hierarchyState & ASHierarchyStateRasterized) && _flags.shouldRasterizeDescendants),
@"Subnode of a rasterized node should not have redundant shouldRasterizeDescendants enabled");
return _flags.shouldRasterizeDescendants;
}
- (void)setShouldRasterizeDescendants:(BOOL)shouldRasterize
{
ASDisplayNodeAssertThreadAffinity(self);
{
ASDN::MutexLocker l(_propertyLock);
if (_flags.shouldRasterizeDescendants == shouldRasterize)
return;
_flags.shouldRasterizeDescendants = shouldRasterize;
}
if (self.isNodeLoaded) {
// Recursively tear down or build up subnodes.
// TODO: When disabling rasterization, preserve rasterized backing store as placeholderImage
// while the newly materialized subtree finishes rendering. Then destroy placeholderImage to save memory.
[self recursivelyClearContents];
ASDisplayNodePerformBlockOnEverySubnode(self, ^(ASDisplayNode *node) {
if (shouldRasterize) {
[node enterHierarchyState:ASHierarchyStateRasterized];
[node __unloadNode];
} else {
[node exitHierarchyState:ASHierarchyStateRasterized];
[node __loadNode];
}
});
if (!shouldRasterize) {
// At this point all of our subnodes have their layers or views recreated, but we haven't added
// them to ours yet. This is because our node is already loaded, and the above recursion
// is only performed on our subnodes -- not self.
[self _addSubnodeViewsAndLayers];
}
if (self.interfaceState & ASInterfaceStateVisible) {
// TODO: Change this to recursivelyEnsureDisplay - but need a variant that does not skip
// nodes that have shouldBypassEnsureDisplay set (such as image nodes) so they are rasterized.
[self recursivelyDisplayImmediately];
}
} else {
ASDisplayNodePerformBlockOnEverySubnode(self, ^(ASDisplayNode *node) {
if (shouldRasterize) {
[node enterHierarchyState:ASHierarchyStateRasterized];
} else {
[node exitHierarchyState:ASHierarchyStateRasterized];
}
});
}
}
- (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)applyPendingViewState
{
ASDisplayNodeAssertMainThread();
ASDN::MutexLocker l(_propertyLock);
// FIXME: Ideally we'd call this as soon as the node receives -setNeedsLayout
// but implicit hierarchy management would require us to modify the node tree
// in the background on a loaded node, which isn't currently supported.
if (_pendingViewState.hasSetNeedsLayout) {
[self __setNeedsLayout];
}
if (self.layerBacked) {
[_pendingViewState applyToLayer:self.layer];
} else {
BOOL specialPropertiesHandling = ASDisplayNodeNeedsSpecialPropertiesHandlingForFlags(_flags);
[_pendingViewState applyToView:self.view withSpecialPropertiesHandling:specialPropertiesHandling];
}
[_pendingViewState clearChanges];
}