/
DemoTextViewController.m
560 lines (438 loc) · 17.1 KB
/
DemoTextViewController.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//
// DemoTextViewController.m
// CoreTextExtensions
//
// Created by Oliver Drobnik on 1/9/11.
// Copyright 2011 Drobnik.com. All rights reserved.
//
#import "DemoTextViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <MediaPlayer/MediaPlayer.h>
@interface DemoTextViewController ()
- (void)_segmentedControlChanged:(id)sender;
- (void)linkPushed:(DTLinkButton *)button;
- (void)linkLongPressed:(UILongPressGestureRecognizer *)gesture;
- (void)debugButton:(UIBarButtonItem *)sender;
@property (nonatomic, strong) NSMutableSet *mediaPlayers;
@end
@implementation DemoTextViewController
#pragma mark NSObject
- (id)init {
if ((self = [super init])) {
NSArray *items = [[NSArray alloc] initWithObjects:@"View", @"Ranges", @"Chars", @"HTML", nil];
_segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
_segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
_segmentedControl.selectedSegmentIndex = 0;
[_segmentedControl addTarget:self action:@selector(_segmentedControlChanged:) forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = _segmentedControl;
// toolbar
#if 0 // DTWebArchive moved to separate project late 2011
UIBarButtonItem *spacer = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
UIBarButtonItem *paste = [[[UIBarButtonItem alloc] initWithTitle:@"Paste" style:UIBarButtonItemStyleBordered target:self action:@selector(paste:)] autorelease];
UIBarButtonItem *copy = [[[UIBarButtonItem alloc] initWithTitle:@"Copy" style:UIBarButtonItemStyleBordered target:self action:@selector(copy:)] autorelease];
#endif
UIBarButtonItem *debug = [[UIBarButtonItem alloc] initWithTitle:@"Debug Frames" style:UIBarButtonItemStyleBordered target:self action:@selector(debugButton:)];
NSArray *toolbarItems = [NSArray arrayWithObjects:/*paste, copy, spacer, */debug, nil];
[self setToolbarItems:toolbarItems];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
#pragma mark UIViewController
- (void)loadView {
[super loadView];
CGRect frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height);
// Create chars view
_charsView = [[UITextView alloc] initWithFrame:frame];
_charsView.editable = NO;
_charsView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:_charsView];
// Create range view
_rangeView = [[UITextView alloc] initWithFrame:frame];
_rangeView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_rangeView.editable = NO;
[self.view addSubview:_rangeView];
// Create html view
_htmlView = [[UITextView alloc] initWithFrame:frame];
_htmlView.editable = NO;
_htmlView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:_htmlView];
// Create text view
[DTAttributedTextContentView setLayerClass:[CATiledLayer class]];
_textView = [[DTAttributedTextView alloc] initWithFrame:frame];
_textView.textDelegate = self;
_textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:_textView];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Load HTML data
NSString *readmePath = [[NSBundle mainBundle] pathForResource:_fileName ofType:nil];
NSString *html = [NSString stringWithContentsOfFile:readmePath encoding:NSUTF8StringEncoding error:NULL];
NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
// Create attributed string from HTML
CGSize maxImageSize = CGSizeMake(self.view.bounds.size.width - 20.0, self.view.bounds.size.height - 20.0);
// example for setting a willFlushCallback, that gets called before elements are written to the generated attributed string
void (^callBackBlock)(DTHTMLElement *element) = ^(DTHTMLElement *element) {
// if an element is larger than twice the font size put it in it's own block
if (element.displayStyle == DTHTMLElementDisplayStyleInline && element.textAttachment.displaySize.height > 2.0 * element.fontDescriptor.pointSize)
{
element.displayStyle = DTHTMLElementDisplayStyleBlock;
}
};
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:1.0], NSTextSizeMultiplierDocumentOption, [NSValue valueWithCGSize:maxImageSize], DTMaxImageSize,
@"Times New Roman", DTDefaultFontFamily, @"purple", DTDefaultLinkColor, callBackBlock, DTWillFlushBlockCallBack, nil];
NSAttributedString *string = [[NSAttributedString alloc] initWithHTMLData:data options:options documentAttributes:NULL];
// Display string
_textView.contentView.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
_textView.contentView.shouldDrawLinks = NO; // we draw them in DTLinkButton
_textView.attributedString = string;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
CGRect bounds = self.view.bounds;
_textView.frame = bounds;
[self _segmentedControlChanged:nil];
[_textView setContentInset:UIEdgeInsetsMake(0, 0, 44, 0)];
[_textView setScrollIndicatorInsets:UIEdgeInsetsMake(0, 0, 44, 0)];
[self.navigationController setToolbarHidden:NO animated:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// now the bar is up so we can autoresize again
_textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
- (void)viewWillDisappear:(BOOL)animated;
{
[self.navigationController setToolbarHidden:YES animated:YES];
// stop all playing media
for (MPMoviePlayerController *player in self.mediaPlayers)
{
[player stop];
}
[super viewWillDisappear:animated];
}
#pragma mark Private Methods
- (void)updateDetailViewForIndex:(NSUInteger)index
{
switch (index)
{
case 1:
{
NSMutableString *dumpOutput = [[NSMutableString alloc] init];
NSDictionary *attributes = nil;
NSRange effectiveRange = NSMakeRange(0, 0);
if ([_textView.attributedString length])
{
while ((attributes = [_textView.attributedString attributesAtIndex:effectiveRange.location effectiveRange:&effectiveRange]))
{
[dumpOutput appendFormat:@"Range: (%d, %d), %@\n\n", effectiveRange.location, effectiveRange.length, attributes];
effectiveRange.location += effectiveRange.length;
if (effectiveRange.location >= [_textView.attributedString length])
{
break;
}
}
}
_rangeView.text = dumpOutput;
break;
}
case 2:
{
// Create characters view
NSMutableString *dumpOutput = [[NSMutableString alloc] init];
NSData *dump = [[_textView.attributedString string] dataUsingEncoding:NSUTF8StringEncoding];
for (NSInteger i = 0; i < [dump length]; i++)
{
char *bytes = (char *)[dump bytes];
char b = bytes[i];
[dumpOutput appendFormat:@"%i: %x %c\n", i, b, b];
}
_charsView.text = dumpOutput;
break;
}
case 3:
{
_htmlView.text = [_textView.attributedString htmlString];
break;
}
}
}
- (void)_segmentedControlChanged:(id)sender {
UIScrollView *selectedView = _textView;
switch (_segmentedControl.selectedSegmentIndex) {
case 1:
selectedView = _rangeView;
break;
case 2:
selectedView = _charsView;
break;
case 3:
{
selectedView = _htmlView;
break;
}
}
// refresh only this tab
[self updateDetailViewForIndex:_segmentedControl.selectedSegmentIndex];
[self.view bringSubviewToFront:selectedView];
[selectedView flashScrollIndicators];
}
#pragma mark Custom Views on Text
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttributedString:(NSAttributedString *)string frame:(CGRect)frame
{
NSDictionary *attributes = [string attributesAtIndex:0 effectiveRange:NULL];
NSURL *URL = [attributes objectForKey:DTLinkAttribute];
NSString *identifier = [attributes objectForKey:DTGUIDAttribute];
DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:frame];
button.URL = URL;
button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
button.GUID = identifier;
// we draw the contents ourselves
button.attributedString = string;
// make a version with different text color
NSMutableAttributedString *highlightedString = [string mutableCopy];
NSRange range = NSMakeRange(0, highlightedString.length);
NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:(__bridge id)[UIColor redColor].CGColor forKey:(id)kCTForegroundColorAttributeName];
[highlightedString addAttributes:highlightedAttributes range:range];
button.highlightedAttributedString = highlightedString;
// use normal push action for opening URL
[button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];
// demonstrate combination with long press
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(linkLongPressed:)];
[button addGestureRecognizer:longPress];
return button;
}
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame
{
if (attachment.contentType == DTTextAttachmentTypeVideoURL)
{
NSURL *url = (id)attachment.contentURL;
// we could customize the view that shows before playback starts
UIView *grayView = [[UIView alloc] initWithFrame:frame];
grayView.backgroundColor = [DTColor blackColor];
// find a player for this URL if we already got one
MPMoviePlayerController *player = nil;
for (player in self.mediaPlayers)
{
if ([player.contentURL isEqual:url])
{
break;
}
}
if (!player)
{
player = [[MPMoviePlayerController alloc] initWithContentURL:url];
[self.mediaPlayers addObject:player];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_4_2
NSString *airplayAttr = [attachment.attributes objectForKey:@"x-webkit-airplay"];
if ([airplayAttr isEqualToString:@"allow"])
{
if ([player respondsToSelector:@selector(setAllowsAirPlay:)])
{
player.allowsAirPlay = YES;
}
}
#endif
NSString *controlsAttr = [attachment.attributes objectForKey:@"controls"];
if (controlsAttr)
{
player.controlStyle = MPMovieControlStyleEmbedded;
}
else
{
player.controlStyle = MPMovieControlStyleNone;
}
NSString *loopAttr = [attachment.attributes objectForKey:@"loop"];
if (loopAttr)
{
player.repeatMode = MPMovieRepeatModeOne;
}
else
{
player.repeatMode = MPMovieRepeatModeNone;
}
NSString *autoplayAttr = [attachment.attributes objectForKey:@"autoplay"];
if (autoplayAttr)
{
player.shouldAutoplay = YES;
}
else
{
player.shouldAutoplay = NO;
}
[player prepareToPlay];
player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
player.view.frame = grayView.bounds;
[grayView addSubview:player.view];
return grayView;
}
else if (attachment.contentType == DTTextAttachmentTypeImage)
{
// if the attachment has a hyperlinkURL then this is currently ignored
DTLazyImageView *imageView = [[DTLazyImageView alloc] initWithFrame:frame];
imageView.delegate = self;
if (attachment.contents)
{
imageView.image = attachment.contents;
}
// url for deferred loading
imageView.url = attachment.contentURL;
// if there is a hyperlink then add a link button on top of this image
if (attachment.hyperLinkURL)
{
// NOTE: this is a hack, you probably want to use your own image view and touch handling
// also, this treats an image with a hyperlink by itself because we don't have the GUID of the link parts
imageView.userInteractionEnabled = YES;
DTLinkButton *button = (DTLinkButton *)[self attributedTextContentView:attributedTextContentView viewForLink:attachment.hyperLinkURL identifier:attachment.hyperLinkGUID frame:imageView.bounds];
[imageView addSubview:button];
}
return imageView;
}
else if (attachment.contentType == DTTextAttachmentTypeIframe)
{
frame.origin.x += 50;
DTWebVideoView *videoView = [[DTWebVideoView alloc] initWithFrame:frame];
videoView.attachment = attachment;
return videoView;
}
else if (attachment.contentType == DTTextAttachmentTypeObject)
{
// somecolorparameter has a HTML color
UIColor *someColor = [UIColor colorWithHTMLName:[attachment.attributes objectForKey:@"somecolorparameter"]];
UIView *someView = [[UIView alloc] initWithFrame:frame];
someView.backgroundColor = someColor;
someView.layer.borderWidth = 1;
someView.layer.borderColor = [UIColor blackColor].CGColor;
return someView;
}
return nil;
}
- (BOOL)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView shouldDrawBackgroundForTextBlock:(DTTextBlock *)textBlock frame:(CGRect)frame context:(CGContextRef)context forLayoutFrame:(DTCoreTextLayoutFrame *)layoutFrame
{
UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:10];
CGColorRef color = [textBlock.backgroundColor CGColor];
if (color)
{
CGContextSetFillColorWithColor(context, color);
CGContextAddPath(context, [roundedRect CGPath]);
CGContextFillPath(context);
CGContextAddPath(context, [roundedRect CGPath]);
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1);
CGContextStrokePath(context);
return NO;
}
return YES; // draw standard background
}
#pragma mark Actions
- (void)linkPushed:(DTLinkButton *)button
{
NSURL *URL = button.URL;
if ([[UIApplication sharedApplication] canOpenURL:[URL absoluteURL]])
{
[[UIApplication sharedApplication] openURL:[URL absoluteURL]];
}
else
{
if (![URL host] && ![URL path])
{
// possibly a local anchor link
NSString *fragment = [URL fragment];
if (fragment)
{
[_textView scrollToAnchorNamed:fragment animated:NO];
}
}
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != actionSheet.cancelButtonIndex)
{
[[UIApplication sharedApplication] openURL:[self.lastActionLink absoluteURL]];
}
}
- (void)linkLongPressed:(UILongPressGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan)
{
DTLinkButton *button = (id)[gesture view];
button.highlighted = NO;
self.lastActionLink = button.URL;
if ([[UIApplication sharedApplication] canOpenURL:[button.URL absoluteURL]])
{
UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:[[button.URL absoluteURL] description] delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Open in Safari", nil];
[action showFromRect:button.frame inView:button.superview animated:YES];
}
}
}
- (void)debugButton:(UIBarButtonItem *)sender
{
_textView.contentView.drawDebugFrames = !_textView.contentView.drawDebugFrames;
[DTCoreTextLayoutFrame setShouldDrawDebugFrames:_textView.contentView.drawDebugFrames];
[self.view setNeedsDisplay];
}
#if 0 // DTWebArchive split out late 2011
- (void)paste:(id)sender
{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
DTWebArchive *webArchive = [pasteboard webArchive];
if (webArchive)
{
CGSize maxImageSize = CGSizeMake(self.view.bounds.size.width - 20.0, self.view.bounds.size.height - 20.0);
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:1.0], NSTextSizeMultiplierDocumentOption, [NSValue valueWithCGSize:maxImageSize], DTMaxImageSize,
@"Times New Roman", DTDefaultFontFamily, @"purple", DTDefaultLinkColor, baseURL, NSBaseURLDocumentOption, nil];
NSAttributedString *attrString = [[[NSAttributedString alloc] initWithWebArchive:webArchive options:options documentAttributes:NULL] autorelease];
_textView.attributedString = attrString;
}
}
- (void)copy:(id)sender
{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
// web archive contains rich text
DTWebArchive *webArchive = [_textView.attributedString webArchive];
[pasteboard setWebArchive:webArchive];
// PS: in real life you also want to put put a plain text copy in pasteboard for apps that don't take rich text
}
#endif
#pragma mark DTLazyImageViewDelegate
- (void)lazyImageView:(DTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size {
NSURL *url = lazyImageView.url;
CGSize imageSize = size;
NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
// update all attachments that matchin this URL (possibly multiple images with same size)
for (DTTextAttachment *oneAttachment in [_textView.contentView.layoutFrame textAttachmentsWithPredicate:pred])
{
oneAttachment.originalSize = imageSize;
if (!CGSizeEqualToSize(imageSize, oneAttachment.displaySize))
{
oneAttachment.displaySize = imageSize;
}
}
// redo layout
// here we're layouting the entire string, might be more efficient to only relayout the paragraphs that contain these attachments
[_textView.contentView relayoutText];
}
#pragma mark Properties
- (NSMutableSet *)mediaPlayers
{
if (!mediaPlayers)
{
mediaPlayers = [[NSMutableSet alloc] init];
}
return mediaPlayers;
}
@synthesize fileName = _fileName;
@synthesize lastActionLink;
@synthesize mediaPlayers;
@synthesize baseURL;
@end