forked from GeekTree0101/Texture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathASTextNode2.mm
1512 lines (1262 loc) · 51.4 KB
/
ASTextNode2.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
//
// ASTextNode2.mm
// Texture
//
// Copyright (c) Pinterest, Inc. All rights reserved.
// Licensed under Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0
//
#import <AsyncDisplayKit/ASTextNode2.h>
#import <AsyncDisplayKit/ASTextNode.h> // Definition of ASTextNodeDelegate
#import <tgmath.h>
#import <deque>
#import <AsyncDisplayKit/_ASDisplayLayer.h>
#import <AsyncDisplayKit/ASDisplayNode+FrameworkPrivate.h>
#import <AsyncDisplayKit/ASDisplayNode+Subclasses.h>
#import <AsyncDisplayKit/ASDisplayNodeExtras.h>
#import <AsyncDisplayKit/ASDisplayNodeInternal.h>
#import <AsyncDisplayKit/ASHighlightOverlayLayer.h>
#import <AsyncDisplayKit/ASTextKitRenderer+Positioning.h>
#import <AsyncDisplayKit/ASEqualityHelpers.h>
#import <AsyncDisplayKit/ASTextLayout.h>
@interface ASTextCacheValue : NSObject {
@package
AS::Mutex _m;
std::deque<std::tuple<CGSize, ASTextLayout *>> _layouts;
}
@end
@implementation ASTextCacheValue
@end
/**
* If set, we will record all values set to attributedText into an array
* and once we get 2000, we'll write them all out into a plist file.
*
* This is useful for gathering realistic text data sets from apps for performance
* testing.
*/
#define AS_TEXTNODE2_RECORD_ATTRIBUTED_STRINGS 0
/**
* If it can't find a compatible layout, this method creates one.
*
* NOTE: Be careful to copy `text` if needed.
*/
static NS_RETURNS_RETAINED ASTextLayout *ASTextNodeCompatibleLayoutWithContainerAndText(ASTextContainer *container, NSAttributedString *text) {
static dispatch_once_t onceToken;
static AS::Mutex *layoutCacheLock;
static NSCache<NSAttributedString *, ASTextCacheValue *> *textLayoutCache;
dispatch_once(&onceToken, ^{
layoutCacheLock = new AS::Mutex();
textLayoutCache = [[NSCache alloc] init];
});
layoutCacheLock->lock();
ASTextCacheValue *cacheValue = [textLayoutCache objectForKey:text];
if (cacheValue == nil) {
cacheValue = [[ASTextCacheValue alloc] init];
[textLayoutCache setObject:cacheValue forKey:[text copy]];
}
// Lock the cache item for the rest of the method. Only after acquiring can we release the NSCache.
AS::MutexLocker lock(cacheValue->_m);
layoutCacheLock->unlock();
CGRect containerBounds = (CGRect){ .size = container.size };
{
for (const auto &t : cacheValue->_layouts) {
CGSize constrainedSize = std::get<0>(t);
ASTextLayout *layout = std::get<1>(t);
CGSize layoutSize = layout.textBoundingSize;
// 1. CoreText can return frames that are narrower than the constrained width, for obvious reasons.
// 2. CoreText can return frames that are slightly wider than the constrained width, for some reason.
// We have to trust that somehow it's OK to try and draw within our size constraint, despite the return value.
// 3. Thus, those two values (constrained width & returned width) form a range, where
// intermediate values in that range will be snapped. Thus, we can use a given layout as long as our
// width is in that range, between the min and max of those two values.
CGRect minRect = CGRectMake(0, 0, MIN(layoutSize.width, constrainedSize.width), MIN(layoutSize.height, constrainedSize.height));
if (!CGRectContainsRect(containerBounds, minRect)) {
continue;
}
CGRect maxRect = CGRectMake(0, 0, MAX(layoutSize.width, constrainedSize.width), MAX(layoutSize.height, constrainedSize.height));
if (!CGRectContainsRect(maxRect, containerBounds)) {
continue;
}
if (!CGSizeEqualToSize(container.size, constrainedSize)) {
continue;
}
// Now check container params.
ASTextContainer *otherContainer = layout.container;
if (!UIEdgeInsetsEqualToEdgeInsets(container.insets, otherContainer.insets)) {
continue;
}
if (!ASObjectIsEqual(container.exclusionPaths, otherContainer.exclusionPaths)) {
continue;
}
if (container.maximumNumberOfRows != otherContainer.maximumNumberOfRows) {
continue;
}
if (container.truncationType != otherContainer.truncationType) {
continue;
}
if (!ASObjectIsEqual(container.truncationToken, otherContainer.truncationToken)) {
continue;
}
// TODO: When we get a cache hit, move this entry to the front (LRU).
return layout;
}
}
// Cache Miss. Compute the text layout.
ASTextLayout *layout = [ASTextLayout layoutWithContainer:container text:text];
// Store the result in the cache.
{
// This is a critical section. However we also must hold the lock until this point, in case
// another thread requests this cache item while a layout is being calculated, so they don't race.
cacheValue->_layouts.push_front(std::make_tuple(container.size, layout));
if (cacheValue->_layouts.size() > 3) {
cacheValue->_layouts.pop_back();
}
}
return layout;
}
static const NSTimeInterval ASTextNodeHighlightFadeOutDuration = 0.15;
static const NSTimeInterval ASTextNodeHighlightFadeInDuration = 0.1;
static const CGFloat ASTextNodeHighlightLightOpacity = 0.11;
static const CGFloat ASTextNodeHighlightDarkOpacity = 0.22;
static NSString *ASTextNodeTruncationTokenAttributeName = @"ASTextNodeTruncationAttribute";
#if AS_ENABLE_TEXTNODE
#define AS_TN2_CLASSNAME ASTextNode2
#else
#define AS_TN2_CLASSNAME ASTextNode
#endif
@interface AS_TN2_CLASSNAME () <UIGestureRecognizerDelegate>
@end
@implementation AS_TN2_CLASSNAME {
ASTextContainer *_textContainer;
CGSize _shadowOffset;
CGColorRef _shadowColor;
CGFloat _shadowOpacity;
CGFloat _shadowRadius;
NSAttributedString *_attributedText;
NSAttributedString *_truncationAttributedText;
NSAttributedString *_additionalTruncationMessage;
NSArray<NSNumber *> *_pointSizeScaleFactors;
NSLineBreakMode _truncationMode;
NSString *_highlightedLinkAttributeName;
id _highlightedLinkAttributeValue;
NSRange _highlightRange;
ASHighlightOverlayLayer *_activeHighlightLayer;
UIColor *_placeholderColor;
UILongPressGestureRecognizer *_longPressGestureRecognizer;
ASTextNodeHighlightStyle _highlightStyle;
BOOL _longPressCancelsTouches;
BOOL _passthroughNonlinkTouches;
BOOL _alwaysHandleTruncationTokenTap;
}
@dynamic placeholderEnabled;
static NSArray *DefaultLinkAttributeNames() {
static NSArray *names;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
names = @[ NSLinkAttributeName ];
});
return names;
}
- (instancetype)init
{
if (self = [super init]) {
_textContainer = [[ASTextContainer alloc] init];
// Load default values from superclass.
_shadowOffset = [super shadowOffset];
_shadowColor = CGColorRetain([super shadowColor]);
_shadowOpacity = [super shadowOpacity];
_shadowRadius = [super shadowRadius];
// Disable user interaction for text node by default.
self.userInteractionEnabled = NO;
self.needsDisplayOnBoundsChange = YES;
_textContainer.truncationType = ASTextTruncationTypeEnd;
// The common case is for a text node to be non-opaque and blended over some background.
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
self.linkAttributeNames = DefaultLinkAttributeNames();
// Accessibility
self.isAccessibilityElement = YES;
self.accessibilityTraits = self.defaultAccessibilityTraits;
// Placeholders
// Disabled by default in ASDisplayNode, but add a few options for those who toggle
// on the special placeholder behavior of ASTextNode.
_placeholderColor = ASDisplayNodeDefaultPlaceholderColor();
_placeholderInsets = UIEdgeInsetsMake(1.0, 0.0, 1.0, 0.0);
}
return self;
}
- (void)dealloc
{
CGColorRelease(_shadowColor);
}
#pragma mark - Description
- (NSString *)_plainStringForDescription
{
NSString *plainString = [[self.attributedText string] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
if (plainString.length > 50) {
plainString = [[plainString substringToIndex:50] stringByAppendingString:@"…"];
}
return plainString;
}
- (NSMutableArray<NSDictionary *> *)propertiesForDescription
{
NSMutableArray *result = [super propertiesForDescription];
NSString *plainString = [self _plainStringForDescription];
if (plainString.length > 0) {
[result insertObject:@{ @"text" : ASStringWithQuotesIfMultiword(plainString) } atIndex:0];
}
return result;
}
- (NSMutableArray<NSDictionary *> *)propertiesForDebugDescription
{
NSMutableArray *result = [super propertiesForDebugDescription];
NSString *plainString = [self _plainStringForDescription];
if (plainString.length > 0) {
[result insertObject:@{ @"text" : ASStringWithQuotesIfMultiword(plainString) } atIndex:0];
}
return result;
}
#pragma mark - ASDisplayNode
- (void)didLoad
{
[super didLoad];
// If we are view-backed and the delegate cares, support the long-press callback.
// Locking is not needed, as all instance variables used are main-thread-only.
SEL longPressCallback = @selector(textNode:longPressedLinkAttribute:value:atPoint:textRange:);
if (!self.isLayerBacked && [self.delegate respondsToSelector:longPressCallback]) {
_longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(_handleLongPress:)];
_longPressGestureRecognizer.cancelsTouchesInView = self.longPressCancelsTouches;
_longPressGestureRecognizer.delegate = self;
[self.view addGestureRecognizer:_longPressGestureRecognizer];
}
}
- (BOOL)supportsLayerBacking
{
if (!super.supportsLayerBacking) {
return NO;
}
ASLockScopeSelf();
// If the text contains any links, return NO.
NSAttributedString *attributedText = _attributedText;
NSRange range = NSMakeRange(0, attributedText.length);
for (NSString *linkAttributeName in _linkAttributeNames) {
__block BOOL hasLink = NO;
[attributedText enumerateAttribute:linkAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value == nil) {
return;
}
hasLink = YES;
*stop = YES;
}];
if (hasLink) {
return NO;
}
}
return YES;
}
- (NSString *)defaultAccessibilityLabel
{
ASLockScopeSelf();
return _attributedText.string;
}
- (UIAccessibilityTraits)defaultAccessibilityTraits
{
return UIAccessibilityTraitStaticText;
}
#pragma mark - Layout and Sizing
- (void)setTextContainerInset:(UIEdgeInsets)textContainerInset
{
ASLockScopeSelf();
if (ASCompareAssignCustom(_textContainer.insets, textContainerInset, UIEdgeInsetsEqualToEdgeInsets)) {
[self setNeedsLayout];
}
}
- (UIEdgeInsets)textContainerInset
{
// textContainer is invariant and has an atomic accessor.
return _textContainer.insets;
}
- (void)setTextContainerLinePositionModifier:(id<ASTextLinePositionModifier>)modifier
{
ASLockedSelfCompareAssignObjects(_textContainer.linePositionModifier, modifier);
}
- (id<ASTextLinePositionModifier>)textContainerLinePositionModifier
{
ASLockScopeSelf();
return _textContainer.linePositionModifier;
}
- (CGSize)calculateSizeThatFits:(CGSize)constrainedSize
{
ASDisplayNodeAssert(constrainedSize.width >= 0, @"Constrained width for text (%f) is too narrow", constrainedSize.width);
ASDisplayNodeAssert(constrainedSize.height >= 0, @"Constrained height for text (%f) is too short", constrainedSize.height);
ASLockScopeSelf();
_textContainer.size = constrainedSize;
[self _ensureTruncationText];
// If the constrained size has a max/inf value on the text's forward direction, the text node is calculating its intrinsic size.
// Need to consider both width and height when determining if it is calculating instrinsic size. Even the constrained width is provided, the height can be inf
// it may provide a text that is longer than the width and require a wordWrapping line break mode and looking for the height to be calculated.
BOOL isCalculatingIntrinsicSize = (_textContainer.size.width >= ASTextContainerMaxSize.width) || (_textContainer.size.height >= ASTextContainerMaxSize.height);
NSMutableAttributedString *mutableText = [_attributedText mutableCopy];
[self prepareAttributedString:mutableText isForIntrinsicSize:isCalculatingIntrinsicSize];
ASTextLayout *layout = ASTextNodeCompatibleLayoutWithContainerAndText(_textContainer, mutableText);
if (layout.truncatedLine != nil && layout.truncatedLine.size.width > layout.textBoundingSize.width) {
return (CGSize) {MIN(constrainedSize.width, layout.truncatedLine.size.width), layout.textBoundingSize.height};
}
return layout.textBoundingSize;
}
#pragma mark - Modifying User Text
// Returns the ascender of the first character in attributedString by also including the line height if specified in paragraph style.
+ (CGFloat)ascenderWithAttributedString:(NSAttributedString *)attributedString
{
UIFont *font = [attributedString attribute:NSFontAttributeName atIndex:0 effectiveRange:NULL];
NSParagraphStyle *paragraphStyle = [attributedString attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:NULL];
if (!paragraphStyle) {
return font.ascender;
}
CGFloat lineHeight = MAX(font.lineHeight, paragraphStyle.minimumLineHeight);
if (paragraphStyle.maximumLineHeight > 0) {
lineHeight = MIN(lineHeight, paragraphStyle.maximumLineHeight);
}
return lineHeight + font.descender;
}
- (NSAttributedString *)attributedText
{
ASLockScopeSelf();
return _attributedText;
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
if (attributedText == nil) {
attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:nil];
}
// Many accessors in this method will acquire the lock (including ASDisplayNode methods).
// Holding it for the duration of the method is more efficient in this case.
ASLockScopeSelf();
NSAttributedString *oldAttributedText = _attributedText;
if (!ASCompareAssignCopy(_attributedText, attributedText)) {
return;
}
// Since truncation text matches style of attributedText, invalidate it now.
[self _locked_invalidateTruncationText];
NSUInteger length = attributedText.length;
if (length > 0) {
ASLayoutElementStyle *style = [self _locked_style];
style.ascender = [[self class] ascenderWithAttributedString:attributedText];
style.descender = [[attributedText attribute:NSFontAttributeName atIndex:attributedText.length - 1 effectiveRange:NULL] descender];
}
// Tell the display node superclasses that the cached layout is incorrect now
[self setNeedsLayout];
// Force display to create renderer with new size and redisplay with new string
[self setNeedsDisplay];
// Accessiblity
self.accessibilityLabel = self.defaultAccessibilityLabel;
// We update the isAccessibilityElement setting if this node is not switching between strings.
if (oldAttributedText.length == 0 || length == 0) {
// We're an accessibility element by default if there is a string.
self.isAccessibilityElement = (length != 0);
}
#if AS_TEXTNODE2_RECORD_ATTRIBUTED_STRINGS
[ASTextNode _registerAttributedText:_attributedText];
#endif
}
#pragma mark - Text Layout
- (void)setExclusionPaths:(NSArray *)exclusionPaths
{
ASLockScopeSelf();
_textContainer.exclusionPaths = exclusionPaths;
[self setNeedsLayout];
[self setNeedsDisplay];
}
- (NSArray *)exclusionPaths
{
ASLockScopeSelf();
return _textContainer.exclusionPaths;
}
- (void)prepareAttributedString:(NSMutableAttributedString *)attributedString isForIntrinsicSize:(BOOL)isForIntrinsicSize
{
ASLockScopeSelf();
NSLineBreakMode innerMode;
switch (_truncationMode) {
case NSLineBreakByWordWrapping:
case NSLineBreakByCharWrapping:
case NSLineBreakByClipping:
innerMode = _truncationMode;
break;
default:
innerMode = NSLineBreakByWordWrapping;
}
// Apply/Fix paragraph style if needed
[attributedString enumerateAttribute:NSParagraphStyleAttributeName inRange:NSMakeRange(0, attributedString.length) options:kNilOptions usingBlock:^(NSParagraphStyle *style, NSRange range, BOOL * _Nonnull stop) {
BOOL applyTruncationMode = YES;
NSMutableParagraphStyle *paragraphStyle = nil;
// Only "left" and "justified" alignments are supported while calculating intrinsic size.
// Other alignments like "right", "center" and "natural" cause the size to be bigger than needed and thus should be ignored/overridden.
const BOOL forceLeftAlignment = (style != nil
&& isForIntrinsicSize
&& style.alignment != NSTextAlignmentLeft
&& style.alignment != NSTextAlignmentJustified);
if (style != nil) {
if (innerMode == style.lineBreakMode) {
applyTruncationMode = NO;
}
paragraphStyle = [style mutableCopy];
} else {
if (innerMode == NSLineBreakByWordWrapping) {
applyTruncationMode = NO;
}
paragraphStyle = [NSMutableParagraphStyle new];
}
if (!applyTruncationMode && !forceLeftAlignment) {
return;
}
paragraphStyle.lineBreakMode = innerMode;
if (applyTruncationMode) {
paragraphStyle.lineBreakMode = _truncationMode;
}
if (forceLeftAlignment) {
paragraphStyle.alignment = NSTextAlignmentLeft;
}
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
}];
// Apply shadow if needed
if (_shadowOpacity > 0 && (_shadowRadius != 0 || !CGSizeEqualToSize(_shadowOffset, CGSizeZero)) && CGColorGetAlpha(_shadowColor) > 0) {
NSShadow *shadow = [[NSShadow alloc] init];
if (_shadowOpacity != 1) {
CGColorRef shadowColorRef = CGColorCreateCopyWithAlpha(_shadowColor, _shadowOpacity * CGColorGetAlpha(_shadowColor));
shadow.shadowColor = [UIColor colorWithCGColor:shadowColorRef];
CGColorRelease(shadowColorRef);
} else {
shadow.shadowColor = [UIColor colorWithCGColor:_shadowColor];
}
shadow.shadowOffset = _shadowOffset;
shadow.shadowBlurRadius = _shadowRadius;
[attributedString addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(0, attributedString.length)];
}
}
#pragma mark - Drawing
- (NSObject *)drawParametersForAsyncLayer:(_ASDisplayLayer *)layer
{
ASTextContainer *copiedContainer;
NSMutableAttributedString *mutableText;
BOOL needsTintColor;
id bgColor;
{
// Wrapping all the other access here, because we can't lock while accessing tintColor.
ASLockScopeSelf();
[self _ensureTruncationText];
// Unlike layout, here we must copy the container since drawing is asynchronous.
copiedContainer = [_textContainer copy];
copiedContainer.size = self.bounds.size;
[copiedContainer makeImmutable];
mutableText = [_attributedText mutableCopy] ?: [[NSMutableAttributedString alloc] init];
[self prepareAttributedString:mutableText isForIntrinsicSize:NO];
needsTintColor = self.textColorFollowsTintColor && mutableText.length > 0;
bgColor = self.backgroundColor ?: [NSNull null];
}
// After all other attributes are set, apply tint color if needed and foreground color is not already specified
if (needsTintColor) {
// Apply tint color if specified and if foreground color is undefined for attributedString
NSRange limit = NSMakeRange(0, mutableText.length);
// Look for previous attributes that define foreground color
UIColor *attributeValue = (UIColor *)[mutableText attribute:NSForegroundColorAttributeName atIndex:limit.location effectiveRange:NULL];
// we need to unlock before accessing tintColor
UIColor *tintColor = self.tintColor;
if (attributeValue == nil && tintColor) {
// None are found, apply tint color if available. Fallback to "black" text color
[mutableText addAttributes:@{ NSForegroundColorAttributeName : tintColor } range:limit];
}
}
return @{
@"container": copiedContainer,
@"text": mutableText,
@"bgColor": bgColor
};
}
+ (void)drawRect:(CGRect)bounds withParameters:(NSDictionary *)layoutDict isCancelled:(NS_NOESCAPE asdisplaynode_iscancelled_block_t)isCancelledBlock isRasterizing:(BOOL)isRasterizing
{
ASTextContainer *container = layoutDict[@"container"];
NSAttributedString *text = layoutDict[@"text"];
UIColor *bgColor = layoutDict[@"bgColor"];
ASTextLayout *layout = ASTextNodeCompatibleLayoutWithContainerAndText(container, text);
if (isCancelledBlock()) {
return;
}
// Fill background color.
if (bgColor == (id)[NSNull null]) {
bgColor = nil;
}
// They may have already drawn into this context in the pre-context block
// so unfortunately we have to use the normal blend mode, not copy.
if (bgColor && CGColorGetAlpha(bgColor.CGColor) > 0) {
[bgColor setFill];
UIRectFillUsingBlendMode(bounds, kCGBlendModeNormal);
}
CGContextRef context = UIGraphicsGetCurrentContext();
ASDisplayNodeAssert(context, @"This is no good without a context.");
[layout drawInContext:context size:bounds.size point:bounds.origin view:nil layer:nil debug:[ASTextDebugOption sharedDebugOption] cancel:isCancelledBlock];
}
#pragma mark - Tint Color
- (void)tintColorDidChange
{
[super tintColorDidChange];
[self _setNeedsDisplayOnTintedTextColor];
}
- (void)_setNeedsDisplayOnTintedTextColor
{
BOOL textColorFollowsTintColor = NO;
{
AS::MutexLocker l(__instanceLock__);
textColorFollowsTintColor = _textColorFollowsTintColor;
}
if (textColorFollowsTintColor) {
[self setNeedsDisplay];
}
}
#pragma mark Interface State
- (void)didEnterHierarchy
{
[super didEnterHierarchy];
[self _setNeedsDisplayOnTintedTextColor];
}
#pragma mark - Attributes
- (id)linkAttributeValueAtPoint:(CGPoint)point
attributeName:(out NSString **)attributeNameOut
range:(out NSRange *)rangeOut
{
return [self _linkAttributeValueAtPoint:point
attributeName:attributeNameOut
range:rangeOut
inAdditionalTruncationMessage:NULL
forHighlighting:NO];
}
- (id)_linkAttributeValueAtPoint:(CGPoint)point
attributeName:(out NSString **)attributeNameOut
range:(out NSRange *)rangeOut
inAdditionalTruncationMessage:(out BOOL *)inAdditionalTruncationMessageOut
forHighlighting:(BOOL)highlighting
{
ASLockScopeSelf();
// TODO: The copy and application of size shouldn't be required, but it is currently.
// See discussion in https://github.com/TextureGroup/Texture/pull/396
ASTextContainer *containerCopy = [_textContainer copy];
containerCopy.size = self.calculatedSize;
ASTextLayout *layout = ASTextNodeCompatibleLayoutWithContainerAndText(containerCopy, _attributedText);
if ([self _locked_pointInsideAdditionalTruncationMessage:point withLayout:layout]) {
if (inAdditionalTruncationMessageOut != NULL) {
*inAdditionalTruncationMessageOut = YES;
}
return nil;
}
NSRange visibleRange = layout.visibleRange;
NSRange clampedRange = NSIntersectionRange(visibleRange, NSMakeRange(0, _attributedText.length));
// Search the 9 points of a 44x44 square around the touch until we find a link.
// Start from center, then do sides, then do top/bottom, then do corners.
static constexpr CGSize kRectOffsets[9] = {
{ 0, 0 },
{ -22, 0 }, { 22, 0 },
{ 0, -22 }, { 0, 22 },
{ -22, -22 }, { -22, 22 },
{ 22, -22 }, { 22, 22 }
};
for (const CGSize &offset : kRectOffsets) {
const CGPoint testPoint = CGPointMake(point.x + offset.width,
point.y + offset.height);
ASTextPosition *pos = [layout closestPositionToPoint:testPoint];
if (!pos || !NSLocationInRange(pos.offset, clampedRange)) {
continue;
}
for (NSString *attributeName in _linkAttributeNames) {
NSRange effectiveRange = NSMakeRange(0, 0);
id value = [_attributedText attribute:attributeName atIndex:pos.offset
longestEffectiveRange:&effectiveRange inRange:clampedRange];
if (value == nil) {
// Didn't find any links specified with this attribute.
continue;
}
// If highlighting, check with delegate first. If not implemented, assume YES.
if (highlighting
&& [_delegate respondsToSelector:@selector(textNode:shouldHighlightLinkAttribute:value:atPoint:)]
&& ![_delegate textNode:(ASTextNode *)self shouldHighlightLinkAttribute:attributeName
value:value atPoint:point]) {
continue;
}
*rangeOut = NSIntersectionRange(visibleRange, effectiveRange);
if (attributeNameOut != NULL) {
*attributeNameOut = attributeName;
}
return value;
}
}
return nil;
}
- (BOOL)_locked_pointInsideAdditionalTruncationMessage:(CGPoint)point withLayout:(ASTextLayout *)layout
{
// Check if the range is within the additional truncation range
BOOL inAdditionalTruncationMessage = NO;
CTLineRef truncatedCTLine = layout.truncatedLine.CTLine;
if (truncatedCTLine != NULL && _additionalTruncationMessage != nil) {
CFIndex stringIndexForPosition = CTLineGetStringIndexForPosition(truncatedCTLine, point);
if (stringIndexForPosition != kCFNotFound) {
CFIndex truncatedCTLineGlyphCount = CTLineGetGlyphCount(truncatedCTLine);
CTLineRef truncationTokenLine = CTLineCreateWithAttributedString((CFAttributedStringRef)_truncationAttributedText);
CFIndex truncationTokenLineGlyphCount = truncationTokenLine ? CTLineGetGlyphCount(truncationTokenLine) : 0;
if (truncationTokenLine) {
CFRelease(truncationTokenLine);
}
CTLineRef additionalTruncationTokenLine = CTLineCreateWithAttributedString((CFAttributedStringRef)_additionalTruncationMessage);
CFIndex additionalTruncationTokenLineGlyphCount = additionalTruncationTokenLine ? CTLineGetGlyphCount(additionalTruncationTokenLine) : 0;
if (additionalTruncationTokenLine) {
CFRelease(additionalTruncationTokenLine);
}
switch (_textContainer.truncationType) {
case ASTextTruncationTypeStart: {
CFIndex composedTruncationTextLineGlyphCount = truncationTokenLineGlyphCount + additionalTruncationTokenLineGlyphCount;
if (stringIndexForPosition > truncationTokenLineGlyphCount &&
stringIndexForPosition < composedTruncationTextLineGlyphCount) {
inAdditionalTruncationMessage = YES;
}
break;
}
case ASTextTruncationTypeMiddle: {
CFIndex composedTruncationTextLineGlyphCount = truncationTokenLineGlyphCount + additionalTruncationTokenLineGlyphCount;
CFIndex firstTruncatedTokenIndex = (truncatedCTLineGlyphCount - composedTruncationTextLineGlyphCount) / 2.0;
if ((firstTruncatedTokenIndex + truncationTokenLineGlyphCount) < stringIndexForPosition &&
stringIndexForPosition < (firstTruncatedTokenIndex + composedTruncationTextLineGlyphCount)) {
inAdditionalTruncationMessage = YES;
}
break;
}
case ASTextTruncationTypeEnd: {
if (stringIndexForPosition > (truncatedCTLineGlyphCount - additionalTruncationTokenLineGlyphCount)) {
inAdditionalTruncationMessage = YES;
}
break;
}
default:
// For now, assume that a tap inside this text, but outside the text range is a tap on the
// truncation token.
if (![layout textRangeAtPoint:point]) {
inAdditionalTruncationMessage = YES;
}
break;
}
}
}
return inAdditionalTruncationMessage;
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
ASDisplayNodeAssertMainThread();
ASLockScopeSelf(); // Protect usage of _highlight* ivars.
if (gestureRecognizer == _longPressGestureRecognizer) {
// Don't allow long press on truncation message
if ([self _pendingTruncationTap]) {
return NO;
}
// Ask our delegate if a long-press on an attribute is relevant
id<ASTextNodeDelegate> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(textNode:shouldLongPressLinkAttribute:value:atPoint:)]) {
return [delegate textNode:(ASTextNode *)self
shouldLongPressLinkAttribute:_highlightedLinkAttributeName
value:_highlightedLinkAttributeValue
atPoint:[gestureRecognizer locationInView:self.view]];
}
// Otherwise we are good to go.
return YES;
}
if (([self _pendingLinkTap] || [self _pendingTruncationTap])
&& [gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]
&& CGRectContainsPoint(self.threadSafeBounds, [gestureRecognizer locationInView:self.view])) {
return NO;
}
return [super gestureRecognizerShouldBegin:gestureRecognizer];
}
#pragma mark - Highlighting
- (ASTextNodeHighlightStyle)highlightStyle
{
ASLockScopeSelf();
return _highlightStyle;
}
- (void)setHighlightStyle:(ASTextNodeHighlightStyle)highlightStyle
{
ASLockScopeSelf();
_highlightStyle = highlightStyle;
}
- (NSRange)highlightRange
{
ASLockScopeSelf();
return _highlightRange;
}
- (void)setHighlightRange:(NSRange)highlightRange
{
[self setHighlightRange:highlightRange animated:NO];
}
- (void)setHighlightRange:(NSRange)highlightRange animated:(BOOL)animated
{
[self _setHighlightRange:highlightRange forAttributeName:nil value:nil animated:animated];
}
- (void)_setHighlightRange:(NSRange)highlightRange forAttributeName:(NSString *)highlightedAttributeName value:(id)highlightedAttributeValue animated:(BOOL)animated
{
ASDisplayNodeAssertMainThread();
ASLockScopeSelf(); // Protect usage of _highlight* ivars.
// Set these so that link tapping works.
_highlightedLinkAttributeName = highlightedAttributeName;
_highlightedLinkAttributeValue = highlightedAttributeValue;
if (!NSEqualRanges(highlightRange, _highlightRange) && ((0 != highlightRange.length) || (0 != _highlightRange.length))) {
_highlightRange = highlightRange;
if (_activeHighlightLayer) {
if (animated) {
__weak CALayer *weakHighlightLayer = _activeHighlightLayer;
_activeHighlightLayer = nil;
weakHighlightLayer.opacity = 0.0;
CFTimeInterval beginTime = CACurrentMediaTime();
CABasicAnimation *possibleFadeIn = (CABasicAnimation *)[weakHighlightLayer animationForKey:@"opacity"];
if (possibleFadeIn) {
// Calculate when we should begin fading out based on the end of the fade in animation,
// Also check to make sure that the new begin time hasn't already passed
CGFloat newBeginTime = (possibleFadeIn.beginTime + possibleFadeIn.duration);
if (newBeginTime > beginTime) {
beginTime = newBeginTime;
}
}
CABasicAnimation *fadeOut = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeOut.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
fadeOut.fromValue = possibleFadeIn.toValue ? : @(((CALayer *)weakHighlightLayer.presentationLayer).opacity);
fadeOut.toValue = @0.0;
fadeOut.fillMode = kCAFillModeBoth;
fadeOut.duration = ASTextNodeHighlightFadeOutDuration;
fadeOut.beginTime = beginTime;
dispatch_block_t prev = [CATransaction completionBlock];
[CATransaction setCompletionBlock:^{
[weakHighlightLayer removeFromSuperlayer];
}];
[weakHighlightLayer addAnimation:fadeOut forKey:fadeOut.keyPath];
[CATransaction setCompletionBlock:prev];
} else {
[_activeHighlightLayer removeFromSuperlayer];
_activeHighlightLayer = nil;
}
}
if (0 != highlightRange.length) {
// Find layer in hierarchy that allows us to draw highlighting on.
CALayer *highlightTargetLayer = self.layer;
while (highlightTargetLayer != nil) {
if (highlightTargetLayer.as_allowsHighlightDrawing) {
break;
}
highlightTargetLayer = highlightTargetLayer.superlayer;
}
if (highlightTargetLayer != nil) {
// TODO: The copy and application of size shouldn't be required, but it is currently.
// See discussion in https://github.com/TextureGroup/Texture/pull/396
ASTextContainer *textContainerCopy = [_textContainer copy];
textContainerCopy.size = self.calculatedSize;
ASTextLayout *layout = ASTextNodeCompatibleLayoutWithContainerAndText(textContainerCopy, _attributedText);
NSArray<ASTextSelectionRect *> *highlightRects = [layout selectionRectsWithoutStartAndEndForRange:[ASTextRange rangeWithRange:highlightRange]];
NSMutableArray *converted = [NSMutableArray arrayWithCapacity:highlightRects.count];
CALayer *layer = self.layer;
UIEdgeInsets shadowPadding = self.shadowPadding;
for (ASTextSelectionRect *rectValue in highlightRects) {
// Adjust shadow padding
CGRect rendererRect = ASTextNodeAdjustRenderRectForShadowPadding(rectValue.rect, shadowPadding);
CGRect highlightedRect = [layer convertRect:rendererRect toLayer:highlightTargetLayer];
// We set our overlay layer's frame to the bounds of the highlight target layer.
// Offset highlight rects to avoid double-counting target layer's bounds.origin.
highlightedRect.origin.x -= highlightTargetLayer.bounds.origin.x;
highlightedRect.origin.y -= highlightTargetLayer.bounds.origin.y;
[converted addObject:[NSValue valueWithCGRect:highlightedRect]];
}
ASHighlightOverlayLayer *overlayLayer = [[ASHighlightOverlayLayer alloc] initWithRects:converted];
overlayLayer.highlightColor = [[self class] _highlightColorForStyle:self.highlightStyle];
overlayLayer.frame = highlightTargetLayer.bounds;
overlayLayer.masksToBounds = NO;
overlayLayer.opacity = [[self class] _highlightOpacityForStyle:self.highlightStyle];
[highlightTargetLayer addSublayer:overlayLayer];
if (animated) {
CABasicAnimation *fadeIn = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeIn.fromValue = @0.0;
fadeIn.toValue = @(overlayLayer.opacity);
fadeIn.duration = ASTextNodeHighlightFadeInDuration;
fadeIn.beginTime = CACurrentMediaTime();
[overlayLayer addAnimation:fadeIn forKey:fadeIn.keyPath];
}
[overlayLayer setNeedsDisplay];
_activeHighlightLayer = overlayLayer;
}
}
}
}
- (void)_clearHighlightIfNecessary
{
ASDisplayNodeAssertMainThread();
if ([self _pendingLinkTap] || [self _pendingTruncationTap]) {
[self setHighlightRange:NSMakeRange(0, 0) animated:YES];
}
}
+ (CGColorRef)_highlightColorForStyle:(ASTextNodeHighlightStyle)style
{
return [UIColor colorWithWhite:(style == ASTextNodeHighlightStyleLight ? 0.0 : 1.0) alpha:1.0].CGColor;
}
+ (CGFloat)_highlightOpacityForStyle:(ASTextNodeHighlightStyle)style
{
return (style == ASTextNodeHighlightStyleLight) ? ASTextNodeHighlightLightOpacity : ASTextNodeHighlightDarkOpacity;
}
#pragma mark - Text rects
static CGRect ASTextNodeAdjustRenderRectForShadowPadding(CGRect rendererRect, UIEdgeInsets shadowPadding) {
rendererRect.origin.x -= shadowPadding.left;
rendererRect.origin.y -= shadowPadding.top;
return rendererRect;
}
- (NSArray *)rectsForTextRange:(NSRange)textRange
{
AS_TEXT_ALERT_UNIMPLEMENTED_FEATURE();
return @[];
}
- (NSArray *)highlightRectsForTextRange:(NSRange)textRange
{
AS_TEXT_ALERT_UNIMPLEMENTED_FEATURE();
return @[];
}
- (CGRect)trailingRect
{
AS_TEXT_ALERT_UNIMPLEMENTED_FEATURE();
return CGRectZero;
}
- (CGRect)frameForTextRange:(NSRange)textRange
{
AS_TEXT_ALERT_UNIMPLEMENTED_FEATURE();
return CGRectZero;
}