forked from facebookarchive/AsyncDisplayKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathASTextLayout.mm
3483 lines (3146 loc) · 137 KB
/
ASTextLayout.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
//
// ASTextLayout.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/ASTextLayout.h>
#import <AsyncDisplayKit/ASAssert.h>
#import <AsyncDisplayKit/ASConfigurationInternal.h>
#import <AsyncDisplayKit/ASTextUtilities.h>
#import <AsyncDisplayKit/ASTextAttribute.h>
#import <AsyncDisplayKit/NSAttributedString+ASText.h>
#import <AsyncDisplayKit/ASInternalHelpers.h>
const CGSize ASTextContainerMaxSize = (CGSize){0x100000, 0x100000};
typedef struct {
CGFloat head;
CGFloat foot;
} ASRowEdge;
static inline CGSize ASTextClipCGSize(CGSize size) {
if (size.width > ASTextContainerMaxSize.width) size.width = ASTextContainerMaxSize.width;
if (size.height > ASTextContainerMaxSize.height) size.height = ASTextContainerMaxSize.height;
return size;
}
static inline UIEdgeInsets UIEdgeInsetRotateVertical(UIEdgeInsets insets) {
UIEdgeInsets one;
one.top = insets.left;
one.left = insets.bottom;
one.bottom = insets.right;
one.right = insets.top;
return one;
}
/**
Sometimes CoreText may convert CGColor to UIColor for `kCTForegroundColorAttributeName`
attribute in iOS7. This should be a bug of CoreText, and may cause crash. Here's a workaround.
*/
static CGColorRef ASTextGetCGColor(CGColorRef color) {
static UIColor *defaultColor;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
defaultColor = [UIColor blackColor];
});
if (!color) return defaultColor.CGColor;
if ([((__bridge NSObject *)color) respondsToSelector:@selector(CGColor)]) {
return ((__bridge UIColor *)color).CGColor;
}
return color;
}
@implementation ASTextLinePositionSimpleModifier
- (void)modifyLines:(NSArray *)lines fromText:(NSAttributedString *)text inContainer:(ASTextContainer *)container {
if (container.verticalForm) {
for (NSUInteger i = 0, max = lines.count; i < max; i++) {
ASTextLine *line = lines[i];
CGPoint pos = line.position;
pos.x = container.size.width - container.insets.right - line.row * _fixedLineHeight - _fixedLineHeight * 0.9;
line.position = pos;
}
} else {
for (NSUInteger i = 0, max = lines.count; i < max; i++) {
ASTextLine *line = lines[i];
CGPoint pos = line.position;
pos.y = line.row * _fixedLineHeight + _fixedLineHeight * 0.9 + container.insets.top;
line.position = pos;
}
}
}
- (id)copyWithZone:(NSZone *)zone {
ASTextLinePositionSimpleModifier *one = [self.class new];
one.fixedLineHeight = _fixedLineHeight;
return one;
}
@end
@implementation ASTextContainer {
@package
BOOL _readonly; ///< used only in ASTextLayout.implementation
dispatch_semaphore_t _lock;
CGSize _size;
UIEdgeInsets _insets;
UIBezierPath *_path;
NSArray *_exclusionPaths;
BOOL _pathFillEvenOdd;
CGFloat _pathLineWidth;
BOOL _verticalForm;
NSUInteger _maximumNumberOfRows;
ASTextTruncationType _truncationType;
NSAttributedString *_truncationToken;
id<ASTextLinePositionModifier> _linePositionModifier;
}
- (NSString *)description
{
return [NSString
stringWithFormat:@"immutable: %@, insets: %@, size: %@", self->_readonly ? @"YES" : @"NO",
NSStringFromUIEdgeInsets(self->_insets), NSStringFromCGSize(self->_size)];
}
+ (instancetype)containerWithSize:(CGSize)size NS_RETURNS_RETAINED {
return [self containerWithSize:size insets:UIEdgeInsetsZero];
}
+ (instancetype)containerWithSize:(CGSize)size insets:(UIEdgeInsets)insets NS_RETURNS_RETAINED {
ASTextContainer *one = [self new];
one.size = ASTextClipCGSize(size);
one.insets = insets;
return one;
}
+ (instancetype)containerWithPath:(UIBezierPath *)path NS_RETURNS_RETAINED {
ASTextContainer *one = [self new];
one.path = path;
return one;
}
- (instancetype)init {
self = [super init];
if (!self) return nil;
_lock = dispatch_semaphore_create(1);
_pathFillEvenOdd = YES;
return self;
}
- (id)copyForced:(BOOL)forceCopy
{
dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
if (_readonly && !forceCopy) {
dispatch_semaphore_signal(_lock);
return self;
}
ASTextContainer *one = [self.class new];
one->_size = _size;
one->_insets = _insets;
one->_path = _path;
one->_exclusionPaths = [_exclusionPaths copy];
one->_pathFillEvenOdd = _pathFillEvenOdd;
one->_pathLineWidth = _pathLineWidth;
one->_verticalForm = _verticalForm;
one->_maximumNumberOfRows = _maximumNumberOfRows;
one->_truncationType = _truncationType;
one->_truncationToken = [_truncationToken copy];
one->_linePositionModifier = [(NSObject *)_linePositionModifier copy];
dispatch_semaphore_signal(_lock);
return one;
}
- (id)copyWithZone:(NSZone *)zone {
return [self copyForced:NO];
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return [self copyForced:YES];
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:[NSValue valueWithCGSize:_size] forKey:@"size"];
[aCoder encodeObject:[NSValue valueWithUIEdgeInsets:_insets] forKey:@"insets"];
[aCoder encodeObject:_path forKey:@"path"];
[aCoder encodeObject:_exclusionPaths forKey:@"exclusionPaths"];
[aCoder encodeBool:_pathFillEvenOdd forKey:@"pathFillEvenOdd"];
[aCoder encodeDouble:_pathLineWidth forKey:@"pathLineWidth"];
[aCoder encodeBool:_verticalForm forKey:@"verticalForm"];
[aCoder encodeInteger:_maximumNumberOfRows forKey:@"maximumNumberOfRows"];
[aCoder encodeInteger:_truncationType forKey:@"truncationType"];
[aCoder encodeObject:_truncationToken forKey:@"truncationToken"];
if ([_linePositionModifier respondsToSelector:@selector(encodeWithCoder:)] &&
[_linePositionModifier respondsToSelector:@selector(initWithCoder:)]) {
[aCoder encodeObject:_linePositionModifier forKey:@"linePositionModifier"];
}
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [self init];
_size = ((NSValue *)[aDecoder decodeObjectForKey:@"size"]).CGSizeValue;
_insets = ((NSValue *)[aDecoder decodeObjectForKey:@"insets"]).UIEdgeInsetsValue;
_path = [aDecoder decodeObjectForKey:@"path"];
_exclusionPaths = [aDecoder decodeObjectForKey:@"exclusionPaths"];
_pathFillEvenOdd = [aDecoder decodeBoolForKey:@"pathFillEvenOdd"];
_pathLineWidth = [aDecoder decodeDoubleForKey:@"pathLineWidth"];
_verticalForm = [aDecoder decodeBoolForKey:@"verticalForm"];
_maximumNumberOfRows = [aDecoder decodeIntegerForKey:@"maximumNumberOfRows"];
_truncationType = (ASTextTruncationType)[aDecoder decodeIntegerForKey:@"truncationType"];
_truncationToken = [aDecoder decodeObjectForKey:@"truncationToken"];
_linePositionModifier = [aDecoder decodeObjectForKey:@"linePositionModifier"];
return self;
}
- (void)makeImmutable
{
dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
_readonly = YES;
dispatch_semaphore_signal(_lock);
}
#define Getter(...) \
dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \
__VA_ARGS__; \
dispatch_semaphore_signal(_lock);
#define Setter(...) \
dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \
if (__builtin_expect(_readonly, NO)) { \
ASDisplayNodeFailAssert(@"Attempt to modify immutable text container."); \
dispatch_semaphore_signal(_lock); \
return; \
} \
__VA_ARGS__; \
dispatch_semaphore_signal(_lock);
- (CGSize)size {
Getter(CGSize size = _size) return size;
}
- (void)setSize:(CGSize)size {
Setter(if(!_path) _size = ASTextClipCGSize(size));
}
- (UIEdgeInsets)insets {
Getter(UIEdgeInsets insets = _insets) return insets;
}
- (void)setInsets:(UIEdgeInsets)insets {
Setter(if(!_path){
if (insets.top < 0) insets.top = 0;
if (insets.left < 0) insets.left = 0;
if (insets.bottom < 0) insets.bottom = 0;
if (insets.right < 0) insets.right = 0;
_insets = insets;
});
}
- (UIBezierPath *)path {
Getter(UIBezierPath *path = _path) return path;
}
- (void)setPath:(UIBezierPath *)path {
Setter(
_path = path.copy;
if (_path) {
CGRect bounds = _path.bounds;
CGSize size = bounds.size;
UIEdgeInsets insets = UIEdgeInsetsZero;
if (bounds.origin.x < 0) size.width += bounds.origin.x;
if (bounds.origin.x > 0) insets.left = bounds.origin.x;
if (bounds.origin.y < 0) size.height += bounds.origin.y;
if (bounds.origin.y > 0) insets.top = bounds.origin.y;
_size = size;
_insets = insets;
}
);
}
- (NSArray *)exclusionPaths {
Getter(NSArray *paths = _exclusionPaths) return paths;
}
- (void)setExclusionPaths:(NSArray *)exclusionPaths {
Setter(_exclusionPaths = exclusionPaths.copy);
}
- (BOOL)isPathFillEvenOdd {
Getter(BOOL is = _pathFillEvenOdd) return is;
}
- (void)setPathFillEvenOdd:(BOOL)pathFillEvenOdd {
Setter(_pathFillEvenOdd = pathFillEvenOdd);
}
- (CGFloat)pathLineWidth {
Getter(CGFloat width = _pathLineWidth) return width;
}
- (void)setPathLineWidth:(CGFloat)pathLineWidth {
Setter(_pathLineWidth = pathLineWidth);
}
- (BOOL)isVerticalForm {
Getter(BOOL v = _verticalForm) return v;
}
- (void)setVerticalForm:(BOOL)verticalForm {
Setter(_verticalForm = verticalForm);
}
- (NSUInteger)maximumNumberOfRows {
Getter(NSUInteger num = _maximumNumberOfRows) return num;
}
- (void)setMaximumNumberOfRows:(NSUInteger)maximumNumberOfRows {
Setter(_maximumNumberOfRows = maximumNumberOfRows);
}
- (ASTextTruncationType)truncationType {
Getter(ASTextTruncationType type = _truncationType) return type;
}
- (void)setTruncationType:(ASTextTruncationType)truncationType {
Setter(_truncationType = truncationType);
}
- (NSAttributedString *)truncationToken {
Getter(NSAttributedString *token = _truncationToken) return token;
}
- (void)setTruncationToken:(NSAttributedString *)truncationToken {
Setter(_truncationToken = truncationToken.copy);
}
- (void)setLinePositionModifier:(id<ASTextLinePositionModifier>)linePositionModifier {
Setter(_linePositionModifier = [(NSObject *)linePositionModifier copy]);
}
- (id<ASTextLinePositionModifier>)linePositionModifier {
Getter(id<ASTextLinePositionModifier> m = _linePositionModifier) return m;
}
#undef Getter
#undef Setter
@end
@interface ASTextLayout ()
@property (nonatomic) ASTextContainer *container;
@property (nonatomic) NSAttributedString *text;
@property (nonatomic) NSRange range;
@property (nonatomic) CTFrameRef frame;
@property (nonatomic) NSArray *lines;
@property (nonatomic) ASTextLine *truncatedLine;
@property (nonatomic) NSArray *attachments;
@property (nonatomic) NSArray *attachmentRanges;
@property (nonatomic) NSArray *attachmentRects;
@property (nonatomic) NSSet *attachmentContentsSet;
@property (nonatomic) NSUInteger rowCount;
@property (nonatomic) NSRange visibleRange;
@property (nonatomic) CGRect textBoundingRect;
@property (nonatomic) CGSize textBoundingSize;
@property (nonatomic) BOOL containsHighlight;
@property (nonatomic) BOOL needDrawBlockBorder;
@property (nonatomic) BOOL needDrawBackgroundBorder;
@property (nonatomic) BOOL needDrawShadow;
@property (nonatomic) BOOL needDrawUnderline;
@property (nonatomic) BOOL needDrawText;
@property (nonatomic) BOOL needDrawAttachment;
@property (nonatomic) BOOL needDrawInnerShadow;
@property (nonatomic) BOOL needDrawStrikethrough;
@property (nonatomic) BOOL needDrawBorder;
@property (nonatomic) NSUInteger *lineRowsIndex;
@property (nonatomic) ASRowEdge *lineRowsEdge; ///< top-left origin
@end
@implementation ASTextLayout
#pragma mark - Layout
- (instancetype)_init {
self = [super init];
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"lines: %ld, visibleRange:%@, textBoundingRect:%@",
(long)[self.lines count],
NSStringFromRange(self.visibleRange),
NSStringFromCGRect(self.textBoundingRect)];
}
+ (ASTextLayout *)layoutWithContainerSize:(CGSize)size text:(NSAttributedString *)text {
ASTextContainer *container = [ASTextContainer containerWithSize:size];
return [self layoutWithContainer:container text:text];
}
+ (ASTextLayout *)layoutWithContainer:(ASTextContainer *)container text:(NSAttributedString *)text {
return [self layoutWithContainer:container text:text range:NSMakeRange(0, text.length)];
}
+ (ASTextLayout *)layoutWithContainer:(ASTextContainer *)container text:(NSAttributedString *)text range:(NSRange)range {
ASTextLayout *layout = NULL;
CGPathRef cgPath = nil;
CGRect cgPathBox = {0};
BOOL isVerticalForm = NO;
BOOL rowMaySeparated = NO;
NSMutableDictionary *frameAttrs = nil;
CTFramesetterRef ctSetter = NULL;
CTFrameRef ctFrame = NULL;
CFArrayRef ctLines = nil;
CGPoint *lineOrigins = NULL;
NSUInteger lineCount = 0;
NSMutableArray *lines = nil;
NSMutableArray *attachments = nil;
NSMutableArray *attachmentRanges = nil;
NSMutableArray *attachmentRects = nil;
NSMutableSet *attachmentContentsSet = nil;
BOOL needTruncation = NO;
NSAttributedString *truncationToken = nil;
ASTextLine *truncatedLine = nil;
ASRowEdge *lineRowsEdge = NULL;
NSUInteger *lineRowsIndex = NULL;
NSRange visibleRange;
NSUInteger maximumNumberOfRows = 0;
BOOL constraintSizeIsExtended = NO;
CGRect constraintRectBeforeExtended = {0};
#define FAIL_AND_RETURN {\
if (cgPath) CFRelease(cgPath); \
if (ctSetter) CFRelease(ctSetter); \
if (ctFrame) CFRelease(ctFrame); \
if (lineOrigins) free(lineOrigins); \
if (lineRowsEdge) free(lineRowsEdge); \
if (lineRowsIndex) free(lineRowsIndex); \
return nil; }
container = [container copy];
if (!text || !container) return nil;
if (range.location + range.length > text.length) return nil;
[container makeImmutable];
maximumNumberOfRows = container.maximumNumberOfRows;
// It may use larger constraint size when create CTFrame with
// CTFramesetterCreateFrame in iOS 10.
BOOL needFixLayoutSizeBug = AS_AT_LEAST_IOS10;
layout = [[ASTextLayout alloc] _init];
layout.text = text;
layout.container = container;
layout.range = range;
isVerticalForm = container.verticalForm;
// set cgPath and cgPathBox
if (container.path == nil && container.exclusionPaths.count == 0) {
if (container.size.width <= 0 || container.size.height <= 0) FAIL_AND_RETURN
CGRect rect = (CGRect) {CGPointZero, container.size };
if (needFixLayoutSizeBug) {
constraintSizeIsExtended = YES;
constraintRectBeforeExtended = UIEdgeInsetsInsetRect(rect, container.insets);
constraintRectBeforeExtended = CGRectStandardize(constraintRectBeforeExtended);
if (container.isVerticalForm) {
rect.size.width = ASTextContainerMaxSize.width;
} else {
rect.size.height = ASTextContainerMaxSize.height;
}
}
rect = UIEdgeInsetsInsetRect(rect, container.insets);
rect = CGRectStandardize(rect);
cgPathBox = rect;
rect = CGRectApplyAffineTransform(rect, CGAffineTransformMakeScale(1, -1));
cgPath = CGPathCreateWithRect(rect, NULL); // let CGPathIsRect() returns true
} else if (container.path && CGPathIsRect(container.path.CGPath, &cgPathBox) && container.exclusionPaths.count == 0) {
CGRect rect = CGRectApplyAffineTransform(cgPathBox, CGAffineTransformMakeScale(1, -1));
cgPath = CGPathCreateWithRect(rect, NULL); // let CGPathIsRect() returns true
} else {
rowMaySeparated = YES;
CGMutablePathRef path = NULL;
if (container.path) {
path = CGPathCreateMutableCopy(container.path.CGPath);
} else {
CGRect rect = (CGRect) {CGPointZero, container.size };
rect = UIEdgeInsetsInsetRect(rect, container.insets);
CGPathRef rectPath = CGPathCreateWithRect(rect, NULL);
if (rectPath) {
path = CGPathCreateMutableCopy(rectPath);
CGPathRelease(rectPath);
}
}
if (path) {
[layout.container.exclusionPaths enumerateObjectsUsingBlock: ^(UIBezierPath *onePath, NSUInteger idx, BOOL *stop) {
CGPathAddPath(path, NULL, onePath.CGPath);
}];
cgPathBox = CGPathGetPathBoundingBox(path);
CGAffineTransform trans = CGAffineTransformMakeScale(1, -1);
CGMutablePathRef transPath = CGPathCreateMutableCopyByTransformingPath(path, &trans);
CGPathRelease(path);
path = transPath;
}
cgPath = path;
}
if (!cgPath) FAIL_AND_RETURN
// frame setter config
frameAttrs = [[NSMutableDictionary alloc] init];
if (container.isPathFillEvenOdd == NO) {
frameAttrs[(id)kCTFramePathFillRuleAttributeName] = @(kCTFramePathFillWindingNumber);
}
if (container.pathLineWidth > 0) {
frameAttrs[(id)kCTFramePathWidthAttributeName] = @(container.pathLineWidth);
}
if (container.isVerticalForm == YES) {
frameAttrs[(id)kCTFrameProgressionAttributeName] = @(kCTFrameProgressionRightToLeft);
}
/*
* Framesetter cache.
* Framesetters can only be used by one thread at a time.
* Create a CFSet with no callbacks (raw pointers) to keep track of which
* framesetters are in use on other threads. If the one for our string is already in use,
* just create a new one. This should be pretty rare.
*/
static pthread_mutex_t busyFramesettersLock = PTHREAD_MUTEX_INITIALIZER;
static NSCache<NSAttributedString *, id> *framesetterCache;
static CFMutableSetRef busyFramesetters;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (ASActivateExperimentalFeature(ASExperimentalFramesetterCache)) {
framesetterCache = [[NSCache alloc] init];
framesetterCache.name = @"org.TextureGroup.Texture.framesetterCache";
busyFramesetters = CFSetCreateMutable(NULL, 0, NULL);
}
});
BOOL haveCached = NO, useCached = NO;
if (framesetterCache) {
// Check if there's one in the cache.
ctSetter = (__bridge_retained CTFramesetterRef)[framesetterCache objectForKey:text];
if (ctSetter) {
haveCached = YES;
// Check-and-set busy on the cached one.
pthread_mutex_lock(&busyFramesettersLock);
BOOL busy = CFSetContainsValue(busyFramesetters, ctSetter);
if (!busy) {
CFSetAddValue(busyFramesetters, ctSetter);
useCached = YES;
}
pthread_mutex_unlock(&busyFramesettersLock);
// Release if it was busy.
if (busy) {
CFRelease(ctSetter);
ctSetter = NULL;
}
}
}
// Create a framesetter if needed.
if (!ctSetter) {
ctSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)text);
}
if (!ctSetter) FAIL_AND_RETURN
ctFrame = CTFramesetterCreateFrame(ctSetter, ASTextCFRangeFromNSRange(range), cgPath, (CFDictionaryRef)frameAttrs);
// Return to cache.
if (framesetterCache) {
if (useCached) {
// If reused: mark available.
pthread_mutex_lock(&busyFramesettersLock);
CFSetRemoveValue(busyFramesetters, ctSetter);
pthread_mutex_unlock(&busyFramesettersLock);
} else if (!haveCached) {
// If first framesetter, add to cache.
[framesetterCache setObject:(__bridge id)ctSetter forKey:text];
}
}
if (!ctFrame) FAIL_AND_RETURN
lines = [NSMutableArray new];
ctLines = CTFrameGetLines(ctFrame);
lineCount = CFArrayGetCount(ctLines);
if (lineCount > 0) {
lineOrigins = (CGPoint *)malloc(lineCount * sizeof(CGPoint));
if (lineOrigins == NULL) FAIL_AND_RETURN
CTFrameGetLineOrigins(ctFrame, CFRangeMake(0, lineCount), lineOrigins);
}
CGRect textBoundingRect = CGRectZero;
CGSize textBoundingSize = CGSizeZero;
NSInteger rowIdx = -1;
NSUInteger rowCount = 0;
CGRect lastRect = CGRectMake(0, -FLT_MAX, 0, 0);
CGPoint lastPosition = CGPointMake(0, -FLT_MAX);
if (isVerticalForm) {
lastRect = CGRectMake(FLT_MAX, 0, 0, 0);
lastPosition = CGPointMake(FLT_MAX, 0);
}
// calculate line frame
NSUInteger lineCurrentIdx = 0;
BOOL measuringBeyondConstraints = NO;
for (NSUInteger i = 0; i < lineCount; i++) {
CTLineRef ctLine = (CTLineRef)CFArrayGetValueAtIndex(ctLines, i);
CFArrayRef ctRuns = CTLineGetGlyphRuns(ctLine);
if (!ctRuns || CFArrayGetCount(ctRuns) == 0) continue;
// CoreText coordinate system
CGPoint ctLineOrigin = lineOrigins[i];
// UIKit coordinate system
CGPoint position;
position.x = cgPathBox.origin.x + ctLineOrigin.x;
position.y = cgPathBox.size.height + cgPathBox.origin.y - ctLineOrigin.y;
ASTextLine *line = [ASTextLine lineWithCTLine:ctLine position:position vertical:isVerticalForm];
[lines addObject:line];
}
// Give user a chance to modify the line's position.
[container.linePositionModifier modifyLines:lines fromText:text inContainer:container];
BOOL first = YES;
for (ASTextLine *line in lines) {
CGPoint position = line.position;
CGRect rect = line.bounds;
if (constraintSizeIsExtended) {
if (isVerticalForm) {
if (rect.origin.x + rect.size.width >
constraintRectBeforeExtended.origin.x +
constraintRectBeforeExtended.size.width) {
measuringBeyondConstraints = YES;
}
} else {
if (rect.origin.y + rect.size.height >
constraintRectBeforeExtended.origin.y +
constraintRectBeforeExtended.size.height) {
measuringBeyondConstraints = YES;
}
}
}
BOOL newRow = !measuringBeyondConstraints;
if (newRow && rowMaySeparated && position.x != lastPosition.x) {
if (isVerticalForm) {
if (rect.size.width > lastRect.size.width) {
if (rect.origin.x > lastPosition.x && lastPosition.x > rect.origin.x - rect.size.width) newRow = NO;
} else {
if (lastRect.origin.x > position.x && position.x > lastRect.origin.x - lastRect.size.width) newRow = NO;
}
} else {
if (rect.size.height > lastRect.size.height) {
if (rect.origin.y < lastPosition.y && lastPosition.y < rect.origin.y + rect.size.height) newRow = NO;
} else {
if (lastRect.origin.y < position.y && position.y < lastRect.origin.y + lastRect.size.height) newRow = NO;
}
}
}
if (newRow) rowIdx++;
lastRect = rect;
lastPosition = position;
line.index = lineCurrentIdx;
line.row = rowIdx;
rowCount = rowIdx + 1;
lineCurrentIdx ++;
if (first) {
first = NO;
textBoundingRect = rect;
} else if (!measuringBeyondConstraints) {
if (maximumNumberOfRows == 0 || rowIdx < maximumNumberOfRows) {
textBoundingRect = CGRectUnion(textBoundingRect, rect);
}
}
}
{
NSMutableArray<ASTextLine *> *removedLines = [NSMutableArray new];
if (rowCount > 0) {
if (maximumNumberOfRows > 0) {
if (rowCount > maximumNumberOfRows) {
needTruncation = YES;
rowCount = maximumNumberOfRows;
do {
ASTextLine *line = lines.lastObject;
if (!line) break;
if (line.row < rowCount) break; // we have removed down to an allowed # of lines now
[lines removeLastObject];
[removedLines addObject:line];
} while (1);
}
}
ASTextLine *lastLine = rowCount < lines.count ? lines[rowCount - 1] : lines.lastObject;
if (!needTruncation && lastLine.range.location + lastLine.range.length < text.length) {
needTruncation = YES;
while (lines.count > rowCount) {
ASTextLine *line = lines.lastObject;
[lines removeLastObject];
[removedLines addObject:line];
}
}
lineRowsEdge = (ASRowEdge *) calloc(rowCount, sizeof(ASRowEdge));
if (lineRowsEdge == NULL) FAIL_AND_RETURN
lineRowsIndex = (NSUInteger *) calloc(rowCount, sizeof(NSUInteger));
if (lineRowsIndex == NULL) FAIL_AND_RETURN
NSInteger lastRowIdx = -1;
CGFloat lastHead = 0;
CGFloat lastFoot = 0;
for (NSUInteger i = 0, max = lines.count; i < max; i++) {
ASTextLine *line = lines[i];
CGRect rect = line.bounds;
if ((NSInteger) line.row != lastRowIdx) {
if (lastRowIdx >= 0) {
lineRowsEdge[lastRowIdx] = (ASRowEdge) {.head = lastHead, .foot = lastFoot};
}
lastRowIdx = line.row;
lineRowsIndex[lastRowIdx] = i;
if (isVerticalForm) {
lastHead = rect.origin.x + rect.size.width;
lastFoot = lastHead - rect.size.width;
} else {
lastHead = rect.origin.y;
lastFoot = lastHead + rect.size.height;
}
} else {
if (isVerticalForm) {
lastHead = MAX(lastHead, rect.origin.x + rect.size.width);
lastFoot = MIN(lastFoot, rect.origin.x);
} else {
lastHead = MIN(lastHead, rect.origin.y);
lastFoot = MAX(lastFoot, rect.origin.y + rect.size.height);
}
}
}
lineRowsEdge[lastRowIdx] = (ASRowEdge) {.head = lastHead, .foot = lastFoot};
for (NSUInteger i = 1; i < rowCount; i++) {
ASRowEdge v0 = lineRowsEdge[i - 1];
ASRowEdge v1 = lineRowsEdge[i];
lineRowsEdge[i - 1].foot = lineRowsEdge[i].head = (v0.foot + v1.head) * 0.5;
}
}
{ // calculate bounding size
CGRect rect = textBoundingRect;
if (container.path) {
if (container.pathLineWidth > 0) {
CGFloat inset = container.pathLineWidth / 2;
rect = CGRectInset(rect, -inset, -inset);
}
} else {
rect = UIEdgeInsetsInsetRect(rect, ASTextUIEdgeInsetsInvert(container.insets));
}
rect = CGRectStandardize(rect);
CGSize size = rect.size;
if (container.verticalForm) {
size.width += container.size.width - (rect.origin.x + rect.size.width);
} else {
size.width += rect.origin.x;
}
size.height += rect.origin.y;
if (size.width < 0) size.width = 0;
if (size.height < 0) size.height = 0;
size.width = ceil(size.width);
size.height = ceil(size.height);
textBoundingSize = size;
}
visibleRange = ASTextNSRangeFromCFRange(CTFrameGetVisibleStringRange(ctFrame));
if (needTruncation) {
ASTextLine *lastLine = lines.lastObject;
NSRange lastRange = lastLine.range;
visibleRange.length = lastRange.location + lastRange.length - visibleRange.location;
// create truncated line
if (container.truncationType != ASTextTruncationTypeNone) {
CTLineRef truncationTokenLine = NULL;
if (container.truncationToken) {
truncationToken = container.truncationToken;
truncationTokenLine = CTLineCreateWithAttributedString((CFAttributedStringRef) truncationToken);
} else {
CFArrayRef runs = CTLineGetGlyphRuns(lastLine.CTLine);
NSUInteger runCount = CFArrayGetCount(runs);
NSMutableDictionary *attrs = nil;
if (runCount > 0) {
CTRunRef run = (CTRunRef) CFArrayGetValueAtIndex(runs, runCount - 1);
attrs = (id) CTRunGetAttributes(run);
attrs = attrs ? attrs.mutableCopy : [NSMutableArray new];
[attrs removeObjectsForKeys:[NSMutableAttributedString as_allDiscontinuousAttributeKeys]];
CTFontRef font = (__bridge CTFontRef) attrs[(id) kCTFontAttributeName];
CGFloat fontSize = font ? CTFontGetSize(font) : 12.0;
UIFont *uiFont = [UIFont systemFontOfSize:fontSize * 0.9];
if (uiFont) {
font = CTFontCreateWithName((__bridge CFStringRef) uiFont.fontName, uiFont.pointSize, NULL);
} else {
font = NULL;
}
if (font) {
attrs[(id) kCTFontAttributeName] = (__bridge id) (font);
uiFont = nil;
CFRelease(font);
}
CGColorRef color = (__bridge CGColorRef) (attrs[(id) kCTForegroundColorAttributeName]);
if (color && CFGetTypeID(color) == CGColorGetTypeID() && CGColorGetAlpha(color) == 0) {
// ignore clear color
[attrs removeObjectForKey:(id) kCTForegroundColorAttributeName];
}
if (!attrs) attrs = [NSMutableDictionary new];
}
truncationToken = [[NSAttributedString alloc] initWithString:ASTextTruncationToken attributes:attrs];
truncationTokenLine = CTLineCreateWithAttributedString((CFAttributedStringRef) truncationToken);
}
if (truncationTokenLine) {
CTLineTruncationType type = kCTLineTruncationEnd;
if (container.truncationType == ASTextTruncationTypeStart) {
type = kCTLineTruncationStart;
} else if (container.truncationType == ASTextTruncationTypeMiddle) {
type = kCTLineTruncationMiddle;
}
NSMutableAttributedString *lastLineText = [text attributedSubstringFromRange:lastLine.range].mutableCopy;
CGFloat truncatedWidth = lastLine.width;
CGFloat atLeastOneLine = lastLine.width;
CGRect cgPathRect = CGRectZero;
if (CGPathIsRect(cgPath, &cgPathRect)) {
if (isVerticalForm) {
truncatedWidth = cgPathRect.size.height;
} else {
truncatedWidth = cgPathRect.size.width;
}
}
int i = 0;
if (type != kCTLineTruncationStart) { // Middle or End/Tail wants to collect some text (at least one line's
// worth) preceding the truncated content, with which to construct a "truncated line".
i = (int)removedLines.count - 1;
while (atLeastOneLine < truncatedWidth && i >= 0) {
if (lastLineText.length > 0 && [lastLineText.string characterAtIndex:lastLineText.string.length - 1] == '\n') { // Explicit newlines are always "long enough".
[lastLineText deleteCharactersInRange:NSMakeRange(lastLineText.string.length - 1, 1)];
break;
}
[lastLineText appendAttributedString:[text attributedSubstringFromRange:removedLines[i].range]];
atLeastOneLine += removedLines[i--].width;
}
[lastLineText appendAttributedString:truncationToken];
}
if (type != kCTLineTruncationEnd && removedLines.count > 0) { // Middle or Start/Head wants to collect some
// text following the truncated content.
i = 0;
atLeastOneLine = removedLines[i].width;
while (atLeastOneLine < truncatedWidth && i < removedLines.count) {
atLeastOneLine += removedLines[i++].width;
}
for (i--; i >= 0; i--) {
NSAttributedString *nextLine = [text attributedSubstringFromRange:removedLines[i].range];
if ([nextLine.string characterAtIndex:nextLine.string.length - 1] == '\n') { // Explicit newlines are always "long enough".
lastLineText = [NSMutableAttributedString new];
} else {
[lastLineText appendAttributedString:nextLine];
}
}
if (type == kCTLineTruncationStart) {
[lastLineText insertAttributedString:truncationToken atIndex:0];
}
}
CTLineRef ctLastLineExtend = CTLineCreateWithAttributedString((CFAttributedStringRef) lastLineText);
if (ctLastLineExtend) {
CTLineRef ctTruncatedLine = CTLineCreateTruncatedLine(ctLastLineExtend, truncatedWidth, type, truncationTokenLine);
CFRelease(ctLastLineExtend);
if (ctTruncatedLine) {
truncatedLine = [ASTextLine lineWithCTLine:ctTruncatedLine position:lastLine.position vertical:isVerticalForm];
truncatedLine.index = lastLine.index;
truncatedLine.row = lastLine.row;
CFRelease(ctTruncatedLine);
}
}
CFRelease(truncationTokenLine);
}
}
}
}
if (isVerticalForm) {
NSCharacterSet *rotateCharset = ASTextVerticalFormRotateCharacterSet();
NSCharacterSet *rotateMoveCharset = ASTextVerticalFormRotateAndMoveCharacterSet();
void (^lineBlock)(ASTextLine *) = ^(ASTextLine *line){
CFArrayRef runs = CTLineGetGlyphRuns(line.CTLine);
if (!runs) return;
NSUInteger runCount = CFArrayGetCount(runs);
if (runCount == 0) return;
NSMutableArray *lineRunRanges = [NSMutableArray new];
line.verticalRotateRange = lineRunRanges;
for (NSUInteger r = 0; r < runCount; r++) {
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, r);
NSMutableArray *runRanges = [NSMutableArray new];
[lineRunRanges addObject:runRanges];
NSUInteger glyphCount = CTRunGetGlyphCount(run);
if (glyphCount == 0) continue;
CFIndex runStrIdx[glyphCount + 1];
CTRunGetStringIndices(run, CFRangeMake(0, 0), runStrIdx);
CFRange runStrRange = CTRunGetStringRange(run);
runStrIdx[glyphCount] = runStrRange.location + runStrRange.length;
CFDictionaryRef runAttrs = CTRunGetAttributes(run);
CTFontRef font = (CTFontRef)CFDictionaryGetValue(runAttrs, kCTFontAttributeName);
BOOL isColorGlyph = ASTextCTFontContainsColorBitmapGlyphs(font);
NSUInteger prevIdx = 0;
ASTextRunGlyphDrawMode prevMode = ASTextRunGlyphDrawModeHorizontal;
NSString *layoutStr = layout.text.string;
for (NSUInteger g = 0; g < glyphCount; g++) {
BOOL glyphRotate = 0, glyphRotateMove = NO;
CFIndex runStrLen = runStrIdx[g + 1] - runStrIdx[g];
if (isColorGlyph) {
glyphRotate = YES;
} else if (runStrLen == 1) {
unichar c = [layoutStr characterAtIndex:runStrIdx[g]];
glyphRotate = [rotateCharset characterIsMember:c];
if (glyphRotate) glyphRotateMove = [rotateMoveCharset characterIsMember:c];
} else if (runStrLen > 1){
NSString *glyphStr = [layoutStr substringWithRange:NSMakeRange(runStrIdx[g], runStrLen)];
BOOL glyphRotate = [glyphStr rangeOfCharacterFromSet:rotateCharset].location != NSNotFound;
if (glyphRotate) glyphRotateMove = [glyphStr rangeOfCharacterFromSet:rotateMoveCharset].location != NSNotFound;
}
ASTextRunGlyphDrawMode mode = glyphRotateMove ? ASTextRunGlyphDrawModeVerticalRotateMove : (glyphRotate ? ASTextRunGlyphDrawModeVerticalRotate : ASTextRunGlyphDrawModeHorizontal);
if (g == 0) {
prevMode = mode;
} else if (mode != prevMode) {
ASTextRunGlyphRange *aRange = [ASTextRunGlyphRange rangeWithRange:NSMakeRange(prevIdx, g - prevIdx) drawMode:prevMode];
[runRanges addObject:aRange];
prevIdx = g;
prevMode = mode;
}
}
if (prevIdx < glyphCount) {
ASTextRunGlyphRange *aRange = [ASTextRunGlyphRange rangeWithRange:NSMakeRange(prevIdx, glyphCount - prevIdx) drawMode:prevMode];
[runRanges addObject:aRange];
}
}
};
for (ASTextLine *line in lines) {
lineBlock(line);
}
if (truncatedLine) lineBlock(truncatedLine);
}
if (visibleRange.length > 0) {
layout.needDrawText = YES;
void (^block)(NSDictionary *attrs, NSRange range, BOOL *stop) = ^(NSDictionary *attrs, NSRange range, BOOL *stop) {
if (attrs[ASTextHighlightAttributeName]) layout.containsHighlight = YES;
if (attrs[ASTextBlockBorderAttributeName]) layout.needDrawBlockBorder = YES;
if (attrs[ASTextBackgroundBorderAttributeName]) layout.needDrawBackgroundBorder = YES;
if (attrs[ASTextShadowAttributeName] || attrs[NSShadowAttributeName]) layout.needDrawShadow = YES;
if (attrs[ASTextUnderlineAttributeName]) layout.needDrawUnderline = YES;
if (attrs[ASTextAttachmentAttributeName]) layout.needDrawAttachment = YES;
if (attrs[ASTextInnerShadowAttributeName]) layout.needDrawInnerShadow = YES;
if (attrs[ASTextStrikethroughAttributeName]) layout.needDrawStrikethrough = YES;
if (attrs[ASTextBorderAttributeName]) layout.needDrawBorder = YES;
};
[layout.text enumerateAttributesInRange:visibleRange options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:block];
if (truncatedLine) {
[truncationToken enumerateAttributesInRange:NSMakeRange(0, truncationToken.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:block];
}
}
for (NSUInteger i = 0, max = lines.count; i < max; i++) {
ASTextLine *line = lines[i];
if (truncatedLine && line.index == truncatedLine.index) line = truncatedLine;
if (line.attachments.count > 0) {
if (!attachments) {
attachments = [[NSMutableArray alloc] init];
attachmentRanges = [[NSMutableArray alloc] init];
attachmentRects = [[NSMutableArray alloc] init];
attachmentContentsSet = [[NSMutableSet alloc] init];
}
[attachments addObjectsFromArray:line.attachments];
[attachmentRanges addObjectsFromArray:line.attachmentRanges];
[attachmentRects addObjectsFromArray:line.attachmentRects];
for (ASTextAttachment *attachment in line.attachments) {
if (attachment.content) {
[attachmentContentsSet addObject:attachment.content];
}
}
}
}
layout.frame = ctFrame;
layout.lines = lines;
layout.truncatedLine = truncatedLine;
layout.attachments = attachments;
layout.attachmentRanges = attachmentRanges;
layout.attachmentRects = attachmentRects;
layout.attachmentContentsSet = attachmentContentsSet;
layout.rowCount = rowCount;