/
DTHTMLAttributedStringBuilder.m
1089 lines (854 loc) · 27.9 KB
/
DTHTMLAttributedStringBuilder.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
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
//
// DTHTMLAttributedStringBuilder.m
// DTCoreText
//
// Created by Oliver Drobnik on 21.01.12.
// Copyright (c) 2012 Drobnik.com. All rights reserved.
//
#import "DTHTMLAttributedStringBuilder.h"
#import "DTCoreTextConstants.h"
#import "DTCSSStylesheet.h"
#import "DTCoreTextFontDescriptor.h"
#import "DTCoreTextParagraphStyle.h"
#import "DTTextAttachment.h"
#import "DTColor+HTML.h"
#import "DTImage+HTML.h"
#import "NSString+HTML.h"
#import "NSString+CSS.h"
#import "NSMutableString+HTML.h"
@interface DTHTMLAttributedStringBuilder ()
- (void)_registerTagStartHandlers;
- (void)_registerTagEndHandlers;
- (void)_flushCurrentTagContent:(NSString *)tagContent;
- (void)_flushListPrefix;
@end
@implementation DTHTMLAttributedStringBuilder
{
NSData *_data;
NSDictionary *_options;
// settings for parsing
CGFloat textScale;
DTColor *defaultLinkColor;
DTCSSStylesheet *_globalStyleSheet;
NSURL *baseURL;
DTCoreTextFontDescriptor *defaultFontDescriptor;
DTCoreTextParagraphStyle *defaultParagraphStyle;
// parsing state, accessed from inside blocks
NSMutableAttributedString *tmpString;
NSMutableString *_currentTagContents;
DTHTMLElement *currentTag;
BOOL needsListItemStart;
BOOL needsNewLineBefore;
BOOL outputHasNewline;
BOOL currentTagIsEmpty; // YES for each opened tag, NO for anything flushed including hr, br, img -> adds an extra NL for <p></p>
// GCD
dispatch_queue_t _stringAssemblyQueue;
dispatch_group_t _stringAssemblyGroup;
dispatch_queue_t _stringParsingQueue;
dispatch_group_t _stringParsingGroup;
// lookup table for blocks that deal with begin and end tags
NSMutableDictionary *_tagStartHandlers;
NSMutableDictionary *_tagEndHandlers;
DTHTMLAttributedStringBuilderWillFlushCallback _willFlushCallback;
}
- (id)initWithHTML:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)dict
{
self = [super init];
if (self)
{
_data = data;
_options = options;
// documentAttributes ignored for now
// register default handlers
[self _registerTagStartHandlers];
[self _registerTagEndHandlers];
//GCD setup
_stringAssemblyQueue = dispatch_queue_create("DTHTMLAttributedStringBuilder", 0);
_stringAssemblyGroup = dispatch_group_create();
_stringParsingQueue = dispatch_queue_create("DTHTMLAttributedStringBuilderParser", 0);
_stringParsingGroup = dispatch_group_create();
}
return self;
}
- (void)dealloc
{
dispatch_release(_stringAssemblyQueue);
dispatch_release(_stringAssemblyGroup);
dispatch_release(_stringParsingQueue);
dispatch_release(_stringParsingGroup);
}
- (BOOL)buildString
{
// only with valid data
if (![_data length])
{
return NO;
}
// Specify the appropriate text encoding for the passed data, default is UTF8
NSString *textEncodingName = [_options objectForKey:NSTextEncodingNameDocumentOption];
NSStringEncoding encoding = NSUTF8StringEncoding; // default
if (textEncodingName)
{
CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)textEncodingName);
encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
}
// custom option to scale text
textScale = [[_options objectForKey:NSTextSizeMultiplierDocumentOption] floatValue];
if (!textScale)
{
textScale = 1.0f;
}
// use baseURL from options if present
baseURL = [_options objectForKey:NSBaseURLDocumentOption];
// Make it a string
NSString *htmlString;
if (encoding == NSUTF8StringEncoding)
{
// this method can fix malformed UTF8
htmlString = [[NSString alloc] initWithPotentiallyMalformedUTF8Data:_data];
}
else
{
// use the specified encoding
htmlString = [[NSString alloc] initWithData:_data encoding:encoding];
}
if (!htmlString)
{
return NO;
}
// the combined style sheet for entire document
_globalStyleSheet = [DTCSSStylesheet defaultStyleSheet];
// do we have a default style sheet passed as option?
DTCSSStylesheet *defaultStylesheet = [_options objectForKey:DTDefaultStyleSheet];
if (defaultStylesheet)
{
// merge the default styles to the combined style sheet
[_globalStyleSheet mergeStylesheet:defaultStylesheet];
}
// for performance we will return this mutable string
tmpString = [[NSMutableAttributedString alloc] init];
needsListItemStart = NO;
needsNewLineBefore = NO;
// we cannot skip any characters, NLs turn into spaces and multi-spaces get compressed to singles
NSScanner *scanner = [NSScanner scannerWithString:htmlString];
scanner.charactersToBeSkipped = nil;
// base tag with font defaults
defaultFontDescriptor = [[DTCoreTextFontDescriptor alloc] initWithFontAttributes:nil];
defaultFontDescriptor.pointSize = 12.0f * textScale;
NSString *defaultFontFamily = [_options objectForKey:DTDefaultFontFamily];
if (defaultFontFamily)
{
defaultFontDescriptor.fontFamily = defaultFontFamily;
}
else
{
defaultFontDescriptor.fontFamily = @"Times New Roman";
}
defaultLinkColor = [_options objectForKey:DTDefaultLinkColor];
if (defaultLinkColor)
{
if ([defaultLinkColor isKindOfClass:[NSString class]])
{
// convert from string to color
defaultLinkColor = [DTColor colorWithHTMLName:(NSString *)defaultLinkColor];
}
// get hex code for t he passed color
NSString *colorHex = [defaultLinkColor htmlHexString];
// overwrite the style
NSString *styleBlock = [NSString stringWithFormat:@"a {color:#%@;}", colorHex];
[_globalStyleSheet parseStyleBlock:styleBlock];
}
// default is to have A underlined
NSNumber *linkDecorationDefault = [_options objectForKey:DTDefaultLinkDecoration];
if (linkDecorationDefault)
{
if (![linkDecorationDefault boolValue])
{
// remove default decoration
[_globalStyleSheet parseStyleBlock:@"a {text-decoration:none;}"];
}
}
// default paragraph style
defaultParagraphStyle = [DTCoreTextParagraphStyle defaultParagraphStyle];
NSNumber *defaultLineHeightMultiplierNum = [_options objectForKey:DTDefaultLineHeightMultiplier];
if (defaultLineHeightMultiplierNum)
{
CGFloat defaultLineHeightMultiplier = [defaultLineHeightMultiplierNum floatValue];
defaultParagraphStyle.lineHeightMultiple = defaultLineHeightMultiplier;
}
NSNumber *defaultTextAlignmentNum = [_options objectForKey:DTDefaultTextAlignment];
if (defaultTextAlignmentNum)
{
defaultParagraphStyle.alignment = (CTTextAlignment)[defaultTextAlignmentNum integerValue];
}
NSNumber *defaultFirstLineHeadIndent = [_options objectForKey:DTDefaultFirstLineHeadIndent];
if (defaultFirstLineHeadIndent)
{
defaultParagraphStyle.firstLineHeadIndent = [defaultFirstLineHeadIndent integerValue];
}
NSNumber *defaultHeadIndent = [_options objectForKey:DTDefaultHeadIndent];
if (defaultHeadIndent)
{
defaultParagraphStyle.headIndent = [defaultHeadIndent integerValue];
}
NSNumber *defaultListIndent = [_options objectForKey:DTDefaultListIndent];
if (defaultListIndent)
{
defaultParagraphStyle.listIndent = [defaultListIndent integerValue];
}
DTHTMLElement *defaultTag = [[DTHTMLElement alloc] init];
defaultTag.fontDescriptor = defaultFontDescriptor;
defaultTag.paragraphStyle = defaultParagraphStyle;
defaultTag.textScale = textScale;
id defaultColor = [_options objectForKey:DTDefaultTextColor];
if (defaultColor)
{
if ([defaultColor isKindOfClass:[DTColor class]])
{
// already a DTColor
defaultTag.textColor = defaultColor;
}
else
{
// need to convert first
defaultTag.textColor = [DTColor colorWithHTMLName:defaultColor];
}
}
currentTag = defaultTag; // our defaults are the root
// create a parser
DTHTMLParser *parser = [[DTHTMLParser alloc] initWithData:_data encoding:encoding];
parser.delegate = (id)self;
__block BOOL result;
dispatch_group_async(_stringParsingGroup, _stringParsingQueue, ^{ result = [parser parse]; });
// wait until all string assembly is complete
dispatch_group_wait(_stringParsingGroup, DISPATCH_TIME_FOREVER);
dispatch_group_wait(_stringAssemblyGroup, DISPATCH_TIME_FOREVER);
return result;
}
- (NSAttributedString *)generatedAttributedString
{
return tmpString;
}
#pragma mark GCD
- (void)_registerTagStartHandlers
{
_tagStartHandlers = [[NSMutableDictionary alloc] init];
void (^imgBlock)(void) = ^
{
// float causes the image to be its own block
if (currentTag.floatStyle != DTHTMLElementFloatStyleNone)
{
currentTag.displayStyle = DTHTMLElementDisplayStyleBlock;
}
// hide contents of recognized tag
currentTag.tagContentInvisible = YES;
// make appropriate attachment
DTTextAttachment *attachment = [DTTextAttachment textAttachmentWithElement:currentTag options:_options];
// add it to tag
currentTag.textAttachment = attachment;
// to avoid much too much space before the image
currentTag.paragraphStyle.lineHeightMultiple = 1;
// specifiying line height interfers with correct positioning
currentTag.paragraphStyle.minimumLineHeight = 0;
currentTag.paragraphStyle.maximumLineHeight = 0;
// caller gets opportunity to modify image tag before it is written
if (_willFlushCallback)
{
_willFlushCallback(currentTag);
}
// maybe the image is forced to show as block, then we want a newline before and after
if (currentTag.displayStyle == DTHTMLElementDisplayStyleBlock)
{
needsNewLineBefore = YES;
}
if (needsNewLineBefore)
{
if ([tmpString length] && !outputHasNewline)
{
[tmpString appendNakedString:@"\n"];
outputHasNewline = YES;
}
needsNewLineBefore = NO;
}
// add it to output
[tmpString appendAttributedString:[currentTag attributedString]];
outputHasNewline = NO;
currentTagIsEmpty = NO;
};
[_tagStartHandlers setObject:[imgBlock copy] forKey:@"img"];
void (^blockquoteBlock)(void) = ^
{
currentTag.paragraphStyle.headIndent += 25.0 * textScale;
currentTag.paragraphStyle.firstLineHeadIndent = currentTag.paragraphStyle.headIndent;
currentTag.paragraphStyle.paragraphSpacing = defaultFontDescriptor.pointSize;
};
[_tagStartHandlers setObject:[blockquoteBlock copy] forKey:@"blockquote"];
void (^objectBlock)(void) = ^
{
// hide contents of recognized tag
currentTag.tagContentInvisible = YES;
// make appropriate attachment
DTTextAttachment *attachment = [DTTextAttachment textAttachmentWithElement:currentTag options:_options];
// add it to tag
currentTag.textAttachment = attachment;
// to avoid much too much space before the image
currentTag.paragraphStyle.lineHeightMultiple = 1;
// caller gets opportunity to modify object tag before it is written
if (_willFlushCallback)
{
_willFlushCallback(currentTag);
}
// maybe the image is forced to show as block, then we want a newline before and after
if (currentTag.displayStyle == DTHTMLElementDisplayStyleBlock)
{
needsNewLineBefore = YES;
}
if (needsNewLineBefore)
{
if ([tmpString length] && !outputHasNewline)
{
[tmpString appendNakedString:@"\n"];
outputHasNewline = YES;
}
needsNewLineBefore = NO;
}
// add it to output
[tmpString appendAttributedString:[currentTag attributedString]];
outputHasNewline = NO;
currentTagIsEmpty = NO;
};
[_tagStartHandlers setObject:[objectBlock copy] forKey:@"object"];
[_tagStartHandlers setObject:[objectBlock copy] forKey:@"video"];
[_tagStartHandlers setObject:[objectBlock copy] forKey:@"iframe"];
void (^aBlock)(void) = ^
{
if (currentTag.isColorInherited || !currentTag.textColor)
{
currentTag.textColor = defaultLinkColor;
currentTag.isColorInherited = NO;
}
// remove line breaks and whitespace in links
NSString *cleanString = [[currentTag attributeForKey:@"href"] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
cleanString = [cleanString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSURL *link = [NSURL URLWithString:cleanString];
// deal with relative URL
if (![link scheme])
{
if ([cleanString length])
{
link = [NSURL URLWithString:cleanString relativeToURL:baseURL];
if (!link)
{
// NSURL did not like the link, so let's encode it
cleanString = [cleanString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
link = [NSURL URLWithString:cleanString relativeToURL:baseURL];
}
}
else
{
link = baseURL;
}
}
currentTag.link = link;
};
[_tagStartHandlers setObject:[aBlock copy] forKey:@"a"];
void (^liBlock)(void) = ^
{
needsListItemStart = YES;
currentTag.paragraphStyle.paragraphSpacing = 0;
currentTag.paragraphStyle.firstLineHeadIndent = currentTag.paragraphStyle.headIndent;
currentTag.paragraphStyle.headIndent += currentTag.paragraphStyle.listIndent;
// first tab is to right-align bullet, numbering against
CGFloat tabOffset = currentTag.paragraphStyle.headIndent - 5.0f*textScale;
[currentTag.paragraphStyle addTabStopAtPosition:tabOffset alignment:kCTRightTextAlignment];
// second tab is for the beginning of first line after bullet
[currentTag.paragraphStyle addTabStopAtPosition:currentTag.paragraphStyle.headIndent alignment: kCTLeftTextAlignment];
};
[_tagStartHandlers setObject:[liBlock copy] forKey:@"li"];
void (^listBlock)(void) = ^
{
#if TARGET_OS_IPHONE
if (needsListItemStart)
{
// we have an opening but not have flushed text since
needsNewLineBefore = YES;
currentTag.paragraphStyle.paragraphSpacing = 0;
if (needsNewLineBefore)
{
if (!outputHasNewline)
{
[tmpString appendString:@"\n"];
outputHasNewline = YES;
}
needsNewLineBefore = NO;
}
// output the prefix
[self _flushListPrefix];
}
#endif
needsNewLineBefore = YES;
// create the appropriate list style from CSS
NSDictionary *styles = [currentTag styles];
DTCSSListStyle *newListStyle = [[DTCSSListStyle alloc] initWithStyles:styles];
// append this list style to the current paragraph style text lists
NSMutableArray *textLists = [currentTag.paragraphStyle.textLists mutableCopy];
if (!textLists)
{
textLists = [NSMutableArray array];
}
[textLists addObject:newListStyle];
// workaround for different styles on stacked lists
if ([textLists count]>1) // not necessary for first
{
// find out if each list is ordered or unordered
NSMutableArray *tmpArray = [NSMutableArray array];
for (DTCSSListStyle *oneList in textLists)
{
if ([oneList isOrdered])
{
[tmpArray addObject:@"ol"];
}
else
{
[tmpArray addObject:@"ul"];
}
}
// build a CSS selector
NSString *selector = [tmpArray componentsJoinedByString:@" "];
// find style
NSDictionary *style = [[_globalStyleSheet styles] objectForKey:selector];
if (style)
{
[newListStyle updateFromStyleDictionary:style];
}
}
currentTag.paragraphStyle.textLists = textLists;
// next text needs a NL before it
needsNewLineBefore = YES;
};
[_tagStartHandlers setObject:[listBlock copy] forKey:@"ul"];
[_tagStartHandlers setObject:[listBlock copy] forKey:@"ol"];
void (^hrBlock)(void) = ^
{
// open block needs closing
if (needsNewLineBefore)
{
if ([tmpString length] && !outputHasNewline)
{
[tmpString appendNakedString:@"\n"];
outputHasNewline = YES;
}
needsNewLineBefore = NO;
}
currentTag.text = @"\n";
NSMutableDictionary *styleDict = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:@"Dummy"];
if (currentTag.backgroundColor)
{
[styleDict setObject:currentTag.backgroundColor forKey:@"BackgroundColor"];
}
[currentTag addAdditionalAttribute:styleDict forKey:DTHorizontalRuleStyleAttribute];
[tmpString appendAttributedString:[currentTag attributedString]];
outputHasNewline = YES;
currentTagIsEmpty = NO;
};
[_tagStartHandlers setObject:[hrBlock copy] forKey:@"hr"];
void (^h1Block)(void) = ^
{
currentTag.headerLevel = 1;
};
[_tagStartHandlers setObject:[h1Block copy] forKey:@"h1"];
void (^h2Block)(void) = ^
{
currentTag.headerLevel = 2;
};
[_tagStartHandlers setObject:[h2Block copy] forKey:@"h2"];
void (^h3Block)(void) = ^
{
currentTag.headerLevel = 3;
};
[_tagStartHandlers setObject:[h3Block copy] forKey:@"h3"];
void (^h4Block)(void) = ^
{
currentTag.headerLevel = 4;
};
[_tagStartHandlers setObject:[h4Block copy] forKey:@"h4"];
void (^h5Block)(void) = ^
{
currentTag.headerLevel = 5;
};
[_tagStartHandlers setObject:[h5Block copy] forKey:@"h5"];
void (^h6Block)(void) = ^
{
currentTag.headerLevel = 6;
};
[_tagStartHandlers setObject:[h6Block copy] forKey:@"h6"];
void (^fontBlock)(void) = ^
{
NSInteger size = [[currentTag attributeForKey:@"size"] intValue];
switch (size)
{
case 1:
currentTag.fontDescriptor.pointSize = textScale * 9.0f;
break;
case 2:
currentTag.fontDescriptor.pointSize = textScale * 10.0f;
break;
case 4:
currentTag.fontDescriptor.pointSize = textScale * 14.0f;
break;
case 5:
currentTag.fontDescriptor.pointSize = textScale * 18.0f;
break;
case 6:
currentTag.fontDescriptor.pointSize = textScale * 24.0f;
break;
case 7:
currentTag.fontDescriptor.pointSize = textScale * 37.0f;
break;
case 3:
default:
currentTag.fontDescriptor.pointSize = defaultFontDescriptor.pointSize;
break;
}
NSString *face = [currentTag attributeForKey:@"face"];
if (face)
{
currentTag.fontDescriptor.fontName = face;
// face usually invalidates family
currentTag.fontDescriptor.fontFamily = nil;
}
NSString *color = [currentTag attributeForKey:@"color"];
if (color)
{
currentTag.textColor = [DTColor colorWithHTMLName:color];
}
};
[_tagStartHandlers setObject:[fontBlock copy] forKey:@"font"];
void (^pBlock)(void) = ^
{
currentTag.paragraphStyle.firstLineHeadIndent = currentTag.paragraphStyle.headIndent + defaultParagraphStyle.firstLineHeadIndent;
};
[_tagStartHandlers setObject:[pBlock copy] forKey:@"p"];
void (^brBlock)(void) = ^
{
currentTag.text = UNICODE_LINE_FEED;
// NOTE: cannot use flush because that removes the break
[tmpString appendAttributedString:[currentTag attributedString]];
outputHasNewline = NO;
currentTagIsEmpty = NO;
};
[_tagStartHandlers setObject:[brBlock copy] forKey:@"br"];
}
- (void)_registerTagEndHandlers
{
_tagEndHandlers = [[NSMutableDictionary alloc] init];
void (^bodyBlock)(void) = ^
{
// if the last child was a block we need an extra \n
if (needsNewLineBefore)
{
if ([tmpString length] && !outputHasNewline)
{
[tmpString appendString:@"\n"];
outputHasNewline = YES;
}
needsNewLineBefore = NO;
}
};
[_tagEndHandlers setObject:[bodyBlock copy] forKey:@"body"];
void (^liBlock)(void) = ^
{
needsListItemStart = NO;
};
[_tagEndHandlers setObject:[liBlock copy] forKey:@"li"];
void (^ulBlock)(void) = ^
{
// pop the current list style from the paragraph style text lists
NSMutableArray *textLists = [currentTag.paragraphStyle.textLists mutableCopy];
[textLists removeLastObject];
currentTag.paragraphStyle.textLists = textLists;
// if this was the last active list
if ([textLists count]==0)
{
// adjust spacing after last li to be the one defined for ol/ul
NSInteger index = [tmpString length];
if (index)
{
index--;
// get the paragraph style for the previous paragraph
NSRange effectiveRange;
CTParagraphStyleRef prevParagraphStyle = (__bridge CTParagraphStyleRef)[tmpString attribute:(id)kCTParagraphStyleAttributeName
atIndex:index
effectiveRange:&effectiveRange];
// convert it to DTCoreText
DTCoreTextParagraphStyle *paragraphStyle = [DTCoreTextParagraphStyle paragraphStyleWithCTParagraphStyle:prevParagraphStyle];
if (paragraphStyle.paragraphSpacing != currentTag.paragraphStyle.paragraphSpacing)
{
paragraphStyle.paragraphSpacing = currentTag.paragraphStyle.paragraphSpacing;
CTParagraphStyleRef newParagraphStyle = [paragraphStyle createCTParagraphStyle];
// because we have multiple paragraph styles per paragraph still, we need to extend towards the begin of the paragraph
NSRange paragraphRange = [[tmpString string] rangeOfParagraphAtIndex:effectiveRange.location];
[tmpString addAttribute:(id)kCTParagraphStyleAttributeName value:CFBridgingRelease(newParagraphStyle) range:paragraphRange];
}
}
}
};
[_tagEndHandlers setObject:[ulBlock copy] forKey:@"ul"];
[_tagEndHandlers setObject:[ulBlock copy] forKey:@"ol"];
void (^pBlock)(void) = ^
{
// we need to output something for <p></p>
if (currentTagIsEmpty)
{
[tmpString appendString:@"\n"];
outputHasNewline = NO; // NO: otherwise a following needed NL is cancelled
}
};
[_tagEndHandlers setObject:[pBlock copy] forKey:@"p"];
}
- (void)_handleTagContent:(NSString *)string
{
NSAssert(dispatch_get_current_queue() == _stringAssemblyQueue, @"method called from invalid queue");
if (!_currentTagContents)
{
_currentTagContents = [[NSMutableString alloc] initWithCapacity:1000];
}
[_currentTagContents appendString:string];
}
- (void)_flushListPrefix
{
// if we start a list, then we wait until we have actual text
if (needsListItemStart)
{
DTCSSListStyle *effectiveList = [currentTag.paragraphStyle.textLists lastObject];
NSInteger index = [tmpString length]-1;
NSInteger counter = 0;
if (index>0)
{
// check if there was a list item before this one
index--;
NSRange prevListRange;
NSArray *prevLists = [tmpString attribute:DTTextListsAttribute atIndex:index effectiveRange:&prevListRange];
if ([prevLists containsObject:effectiveList])
{
NSInteger prevItemIndex = [tmpString itemNumberInTextList:effectiveList atIndex:index];
counter = prevItemIndex + 1;
}
else
{
// new list start
counter = [effectiveList startingItemNumber];
}
}
else
{
// new list start at beginning of string
counter = [effectiveList startingItemNumber];
}
NSAttributedString *prefixString = [currentTag prefixForListItemWithCounter:counter];
if (prefixString)
{
[tmpString appendAttributedString:prefixString];
outputHasNewline = NO;
}
needsListItemStart = NO;
}
}
- (void)_flushCurrentTagContent:(NSString *)tagContent
{
NSAssert(dispatch_get_current_queue() == _stringAssemblyQueue, @"method called from invalid queue");
// trim newlines
NSString *tagContents = tagContent;
if (![tagContents length])
{
// nothing to do
return;
}
if (currentTag.preserveNewlines)
{
tagContents = [tagContent stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
tagContents = [tagContents stringByReplacingOccurrencesOfString:@"\n" withString:UNICODE_LINE_FEED];
}
else
{
tagContents = [tagContents stringByNormalizingWhitespace];
if ([tagContents isEqualToString:@" "])
{
return;
}
}
if (needsNewLineBefore)
{
if ([tagContents hasPrefix:@" "])
{
tagContents = [tagContents substringFromIndex:1];
}
if ([tmpString length])
{
if (!outputHasNewline)
{
[tmpString appendString:@"\n"];
outputHasNewline = YES;
}
}
needsNewLineBefore = NO;
}
else // might be a continuation of a paragraph, then we might need space before it
{
NSString *stringSoFar = [tmpString string];
// prevent double spacing
if ([stringSoFar hasSuffixCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] && [tagContents hasPrefix:@" "])
{
tagContents = [tagContents substringFromIndex:1];
}
}
// if we start a list, then we wait until we have actual text
if (needsListItemStart && [tagContents length] > 0 && ![tagContents isEqualToString:@" "])
{
[self _flushListPrefix];
}
// we don't want whitespace before first tag to turn into paragraphs
if (!(currentTag.displayStyle == DTHTMLElementDisplayStyleNone) && !currentTag.tagContentInvisible)
{
currentTag.text = tagContents;
if (_willFlushCallback)
{
_willFlushCallback(currentTag);
}
[tmpString appendAttributedString:[currentTag attributedString]];
outputHasNewline = NO;
// we've written something
currentTagIsEmpty = NO;
}
_currentTagContents = nil;
}
#pragma mark DTHTMLParser Delegate
- (void)parser:(DTHTMLParser *)parser didStartElement:(NSString *)elementName attributes:(NSDictionary *)attributeDict
{
void (^tmpBlock)(void) = ^
{
DTHTMLElement *parent = currentTag;
DTHTMLElement *nextTag = [currentTag copy];
nextTag.tagName = elementName;
nextTag.textScale = textScale;
nextTag.attributes = attributeDict;
[parent addChild:nextTag];
// apply style from merged style sheet
NSDictionary *mergedStyles = [_globalStyleSheet mergedStyleDictionaryForElement:nextTag];
if (mergedStyles)
{
[nextTag applyStyleDictionary:mergedStyles];
}
BOOL removeUnflushedWhitespace = NO;
// keep currentTag, might be used in flush
if (_currentTagContents)
{
// remove whitespace suffix in current non-block item
if (nextTag.displayStyle == DTHTMLElementDisplayStyleBlock)
{
if (currentTag.displayStyle != DTHTMLElementDisplayStyleBlock)
{
[_currentTagContents removeWhitespaceSuffix];
}
removeUnflushedWhitespace = YES;
}
}
[self _flushCurrentTagContent:_currentTagContents];
// avoid transfering space from parent tag
if (removeUnflushedWhitespace)
{
_currentTagContents = nil;
}
// keep track of something was flushed for this tag
currentTagIsEmpty = YES;
// switch to new tag
currentTag = nextTag;
if (currentTag.displayStyle == DTHTMLElementDisplayStyleNone)
{
// we don't care about the other stuff in META tags, but styles are inherited
return;
}
if (currentTag.displayStyle == DTHTMLElementDisplayStyleBlock || currentTag.displayStyle == DTHTMLElementDisplayStyleListItem)
{
// make sure that we have a NL before text in this block
needsNewLineBefore = YES;
}
// direction
NSString *direction = [currentTag attributeForKey:@"dir"];
if (direction)
{
NSString *lowerDirection = [direction lowercaseString];