forked from bumptech/JTextView
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJTextView.m
executable file
·538 lines (423 loc) · 18.9 KB
/
JTextView.m
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
//
// JTextView.m
// JKit
//
// Created by Jeremy Tregunna on 10-10-24.
// Copyright (c) 2010 Jeremy Tregunna. All rights reserved.
//
#import <CoreText/CoreText.h>
#import "JTextView.h"
static CGFloat const kJTextViewPaddingSize = 2.0f;
static NSString* const kJTextViewDataDetectorLinkKey = @"kJTextViewDataDetectorLinkKey";
static NSString* const kJTextViewDataDetectorPhoneNumberKey = @"kJTextViewDataDetectorPhoneNumberKey";
static NSString* const kJTextViewDataDetectorDateKey = @"kJTextViewDataDetectorDateKey";
static NSString* const kJTextViewDataDetectorAddressKey = @"kJTextViewDataDetectorAddressKey";
static NSString* const kJTextViewLinkAttributeName = @"kJTextViewLinkAttributeName";
static NSString* const kJTextViewDataDetectorHashTag = @"kJTextViewDataDetectorHashTag";
@interface JTextView (PrivateMethods)
- (void)dataDetectorPassInRange:(NSRange)range;
- (void)dataDetectorPassInRange:(NSRange)range withAttributedString:(NSMutableAttributedString *)attributedString;
- (void)receivedTap:(UITapGestureRecognizer*)recognizer;
- (void)setup;
- (void)setGraphicsContext:(CGContextRef)context;
@end
@interface JTextView () <UIGestureRecognizerDelegate>
@property (nonatomic, copy) dispatch_block_t tapRecognizedBlock;
@end
@implementation JTextView {
BOOL _maximumTextSizeChanged;
}
@synthesize tapRecognizedBlock = _tapRecognizedBlock;
@synthesize attributedText = _textStore;
@synthesize font = _font;
@synthesize textColor = _textColor;
@synthesize editable = _editable;
@synthesize dataDetectorTypes = _dataDetectorTypes;
@synthesize textViewDelegate = _textViewDelegate;
@synthesize text = _text;
@synthesize linkColor = _linkColor;
@synthesize shouldUnderlineLinks = _shouldUnderlineLinks;
@synthesize maximumTextSize = _maximumTextSize;
#pragma mark -
#pragma mark Object creation and destruction
- (id)initWithFrame:(CGRect)frame
{
if((self = [super initWithFrame:frame]))
{
[self setup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if(self) {
[self setup];
}
return self;
}
- (void)setup {
self.backgroundColor = [UIColor whiteColor];
_textStore = [[NSMutableAttributedString alloc] init];
_textColor = [UIColor blackColor];
_font = [[UIFont systemFontOfSize:[UIFont systemFontSize]] retain];
_editable = NO;
_dataDetectorTypes = UIDataDetectorTypeLink;
caret = [[JTextCaret alloc] initWithFrame:CGRectZero];
_maximumTextSize = self.bounds.size;
UITapGestureRecognizer* tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(receivedTap:)] autorelease];
tap.delegate = self;
[self addGestureRecognizer:tap];
}
- (void)dealloc
{
if(textFrame != NULL)
{
CFRelease(textFrame);
}
if(_graphicsContext != NULL)
{
CGContextRelease(_graphicsContext);
_graphicsContext = NULL;
}
if(_tapRecognizedBlock != nil) {
Block_release(_tapRecognizedBlock);
_tapRecognizedBlock = nil;
}
[_linkColor release], _linkColor = nil;
[_font release], _font = nil;
[_textStore release], _textStore = nil;
[caret release], caret = nil;
[super dealloc];
}
#pragma mark -
#pragma mark Responder chain
- (BOOL)canBecomeFirstResponder
{
return self.editable;
}
#pragma mark -
#pragma mark Setters
- (void)setGraphicsContext:(CGContextRef)context
{
if(context != NULL && context != _graphicsContext)
{
if(_graphicsContext != NULL)
{
CGContextRelease(_graphicsContext);
}
_graphicsContext = CGContextRetain(context);
}
}
-(void)setFrame:(CGRect)frame {
if(!CGRectEqualToRect(frame, self.frame)) {
if(!_maximumTextSizeChanged) {
_maximumTextSize = frame.size;
}
[super setFrame:frame];
}
}
- (void)setMaximumTextSize:(CGSize)maximumTextSize {
if(!CGSizeEqualToSize(_maximumTextSize, maximumTextSize)) {
_maximumTextSize = maximumTextSize;
_maximumTextSizeChanged = YES;
[self setNeedsDisplay];
}
}
#pragma mark -
#pragma mark Text drawing
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[self setGraphicsContext:context];
NSMutableAttributedString *textStringToDraw = [self.attributedText mutableCopy];
[self.backgroundColor set];
CGContextFillRect(context, rect);
CGFloat width = CGRectGetWidth(rect);
CGSize textSize = [textStringToDraw.string sizeWithFont:self.font
constrainedToSize:self.maximumTextSize
lineBreakMode:UILineBreakModeWordWrap];
NSRange textRange = NSMakeRange(0, textStringToDraw.length);
CTFontRef font = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL);
[textStringToDraw addAttribute:(NSString*)kCTFontAttributeName value:(id)font range:textRange];
if(font != NULL)
{
CFRelease(font);
}
if(!self.editable)
[self dataDetectorPassInRange:textRange withAttributedString:textStringToDraw];
CGContextTranslateCTM(context, 0, textSize.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0, 1.0));
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)textStringToDraw);
if(textFrame != NULL)
{
CFRelease(textFrame);
}
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, width, textSize.height));
textFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
if(framesetter != NULL)
{
CFRelease(framesetter);
}
[_textStore setAttributedString:textStringToDraw];
CTFrameDraw(textFrame, context);
}
#pragma mark -
#pragma mark UIKeyInput delegate methods
- (BOOL)hasText
{
if(self.attributedText.length > 0)
return YES;
return NO;
}
- (NSString *)text {
return [self.attributedText string];
}
- (void)setText:(NSString *)text {
if(![text isEqualToString:[self.attributedText string]]) {
self.attributedText = [[[NSMutableAttributedString alloc] initWithString:text] autorelease];
[self setNeedsDisplay];
}
}
- (void)insertText:(NSString*)aString
{
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:aString];
[self.attributedText appendAttributedString:attributedString];
[attributedString release];
[self setNeedsDisplay];
}
- (void)deleteBackward
{
if(self.attributedText.length != 0)
{
NSRange range = NSMakeRange(self.attributedText.length - 1, 1);
[self.attributedText deleteCharactersInRange:range];
[self setNeedsDisplay];
}
}
#pragma mark -
#pragma mark Data detectors
- (void)dataDetectorPassInRange:(NSRange)range
{
[self dataDetectorPassInRange:range withAttributedString:self.attributedText];
}
- (void)dataDetectorPassInRange:(NSRange)range withAttributedString:(NSMutableAttributedString *)attributedString
{
if (self.dataDetectorTypes == UIDataDetectorTypeNone) return;
NSError* error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#[a-zA-Z0-9]+"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSAssert(error == nil, @"Problem creating the link detector: %@", [error localizedDescription]);
NSString* string = [attributedString string];
[regex enumerateMatchesInString:string options:0 range:range usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
// [detector enumerateMatchesInString:string options:0 range:range usingBlock:^(NSTextCheckingResult* match, NSMatchingFlags flags, BOOL* stop){
NSRange matchRange = [match range];
// No way to call into Calendar, so don't detect dates
UIColor *linkColor = (_linkColor != nil) ? _linkColor : [UIColor blueColor];
//This sentinel attribute will tell us that this is a link.
[attributedString addAttribute:kJTextViewLinkAttributeName
value:[NSNull null]
range:matchRange];
[attributedString addAttribute:(NSString*)kCTForegroundColorAttributeName
value:(id)linkColor.CGColor
range:matchRange];
// if(_shouldUnderlineLinks) {
[attributedString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
range:matchRange];
// }
[attributedString addAttribute:kJTextViewDataDetectorHashTag value:[string substringWithRange:matchRange] range:matchRange];
// [self.textViewDelegate jTextView:self didReceiveURL:[string substringWithRange:matchRange] range:matchRange];
}];
NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSAssert(error == nil, @"Problem creating the link detector: %@", [error localizedDescription]);
//NSString* string = [attributedString string];
[detector enumerateMatchesInString:string options:0 range:range usingBlock:^(NSTextCheckingResult* match, NSMatchingFlags flags, BOOL* stop){
NSRange matchRange = [match range];
// No way to call into Calendar, so don't detect dates
if([match resultType] != NSTextCheckingTypeDate)
{
UIColor *linkColor = (_linkColor != nil) ? _linkColor : [UIColor blueColor];
//This sentinel attribute will tell us that this is a link.
[attributedString addAttribute:kJTextViewLinkAttributeName
value:[NSNull null]
range:matchRange];
[attributedString addAttribute:(NSString*)kCTForegroundColorAttributeName
value:(id)linkColor.CGColor
range:matchRange];
if(_shouldUnderlineLinks) {
[attributedString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
range:matchRange];
}
}
switch([match resultType])
{
case NSTextCheckingTypeLink:
{
NSURL* url = [match URL];
if([self.textViewDelegate respondsToSelector:@selector(jTextView:didReceiveURL:range:)])
[self.textViewDelegate jTextView:self didReceiveURL:url range:matchRange];
else
[attributedString addAttribute:kJTextViewDataDetectorLinkKey value:url range:matchRange];
break;
}
case NSTextCheckingTypePhoneNumber:
{
NSString* phoneNumber = [match phoneNumber];
if([self.textViewDelegate respondsToSelector:@selector(jTextView:didReceivePhoneNumber:range:)])
[self.textViewDelegate jTextView:self didReceivePhoneNumber:phoneNumber range:matchRange];
else
[attributedString addAttribute:kJTextViewDataDetectorPhoneNumberKey value:phoneNumber range:matchRange];
break;
}
case NSTextCheckingTypeAddress:
{
NSDictionary* addressComponents = [match addressComponents];
if([self.textViewDelegate respondsToSelector:@selector(jTextView:didReceiveAddress:range:)])
[self.textViewDelegate jTextView:self didReceiveAddress:addressComponents range:matchRange];
else
[attributedString addAttribute:kJTextViewDataDetectorAddressKey value:addressComponents range:matchRange];
break;
}
case NSTextCheckingTypeDate:
{
//NSDate* date = [match date];
//[self.attributedText addAttribute:kJTextViewDataDetectorDateKey value:date range:matchRange];
break;
}
}
}];
}
#pragma mark -
#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
self.tapRecognizedBlock = nil;
CGPoint point = [touch locationInView:self];
// NSLog(@"----------------------");
// NSLog(@"Touch point: x:%f y:%f", point.x, point.y);
CGContextRef context = _graphicsContext;
NSArray* tempLines = (NSArray*)CTFrameGetLines(textFrame);
CFIndex lineCount = [tempLines count];//CFArrayGetCount(lines);
NSMutableArray* lines = [NSMutableArray arrayWithCapacity:lineCount];
for(id elem in [tempLines reverseObjectEnumerator])
[lines addObject:elem];
CGPoint origins[lineCount];
CTFrameGetLineOrigins(textFrame, CFRangeMake(0, 0), origins);
for(CFIndex idx = 0; idx < lineCount; idx++)
{
CTLineRef line = CFArrayGetValueAtIndex((CFArrayRef)lines, idx);
CGRect bounds = CTLineGetImageBounds(line, context);
if(CGRectIsNull(bounds))
{
NSLog(@"Invalid arguments supplied to CTLineGetImageBounds.");
continue;
}
CGPoint origin = bounds.origin;
origin.y += origins[idx].y;
bounds.origin = origin;
if(!CGRectContainsPoint(bounds, point))
{
continue;
}
CFArrayRef runs = CTLineGetGlyphRuns(line);
for(CFIndex j = 0; j < CFArrayGetCount(runs); j++)
{
CTRunRef run = CFArrayGetValueAtIndex(runs, j);
NSDictionary* attributes = (NSDictionary*)CTRunGetAttributes(run);
NSURL* url = [attributes objectForKey:kJTextViewDataDetectorLinkKey];
NSString* phoneNumber = [attributes objectForKey:kJTextViewDataDetectorPhoneNumberKey];
NSDictionary* addressComponents = [attributes objectForKey:kJTextViewDataDetectorAddressKey];
NSString *hashTag = [attributes objectForKey:kJTextViewDataDetectorHashTag];
// CFRange runRange = CTRunGetStringRange(run);
CGRect runBounds;
CGFloat ascent;//height above the baseline
CGFloat descent;//height below the baseline
runBounds.size.width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, NULL);
runBounds.size.height = ascent + descent;
CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, NULL);
// runBounds.origin.x = origins[idx].x + self.frame.origin.x + xOffset;
// runBounds.origin.y = origins[idx].y + self.frame.origin.y;
runBounds.origin.x = origins[idx].x + xOffset;
runBounds.origin.y = origins[idx].y;
runBounds.origin.y -= descent;
// NSLog(@"Run bounds: x:%f y:%f h:%f w:%f", runBounds.origin.x, runBounds.origin.y, runBounds.size.height, runBounds.size.width);
if(CGRectContainsPoint(runBounds, point)){
if(url){
self.tapRecognizedBlock = ^{
if([_textViewDelegate respondsToSelector:@selector(jTextView:didSelectLink:)]){
[_textViewDelegate jTextView:self didSelectLink:url];
}
};
return YES;
}else if(phoneNumber){
phoneNumber = [phoneNumber stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// The following code may be switched to if we absolutely need to remove everything but the numbers.
//NSMutableString* strippedPhoneNumber = [NSMutableString stringWithCapacity:[phoneNumber length]]; // Can't be longer than that
//for(NSUInteger i = 0; i < [phoneNumber length]; i++)
//{
// if(isdigit([phoneNumber characterAtIndex:i]))
// [strippedPhoneNumber appendFormat:@"%c", [phoneNumber characterAtIndex:i]];
//}
//NSLog(@"*** phoneNumber = %@; strippedPhoneNumber = %@", phoneNumber, strippedPhoneNumber);
self.tapRecognizedBlock = ^{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNumber]];
[[UIApplication sharedApplication] openURL:url];
};
return YES;
}else if(addressComponents){
self.tapRecognizedBlock = ^{
NSMutableString* address = [NSMutableString string];
NSString* temp = nil;
if((temp = [addressComponents objectForKey:NSTextCheckingStreetKey])) [address appendString:temp];
if((temp = [addressComponents objectForKey:NSTextCheckingCityKey])) [address appendString:[NSString stringWithFormat:@"%@%@", ([address length] > 0) ? @", " : @"", temp]];
if((temp = [addressComponents objectForKey:NSTextCheckingStateKey])) [address appendString:[NSString stringWithFormat:@"%@%@", ([address length] > 0) ? @", " : @"", temp]];
if((temp = [addressComponents objectForKey:NSTextCheckingZIPKey])) [address appendString:[NSString stringWithFormat:@" %@", temp]];
if((temp = [addressComponents objectForKey:NSTextCheckingCountryKey])) [address appendString:[NSString stringWithFormat:@"%@%@", ([address length] > 0) ? @", " : @"", temp]];
NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
};
return YES;
}else if(hashTag){
self.tapRecognizedBlock = ^{
if([self.textViewDelegate respondsToSelector:@selector(jTextView:didSelectHashTag:)])
[self.textViewDelegate jTextView:self didSelectHashTag:hashTag];
};
return YES;
}
}
}
}
return NO;
}
#pragma mark Touch handling
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if(!self.tapRecognizedBlock) {
[self.nextResponder touchesBegan:touches withEvent:event];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
if(!self.tapRecognizedBlock) {
[self.nextResponder touchesCancelled:touches withEvent:event];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if(!self.tapRecognizedBlock) {
[self.nextResponder touchesEnded:touches withEvent:event];
}
}
- (void)receivedTap:(UITapGestureRecognizer*)recognizer
{
if(self.editable)
{
[self becomeFirstResponder];
return;
}
if(_tapRecognizedBlock) {
_tapRecognizedBlock();
self.tapRecognizedBlock = nil;
}
}
@end