-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathEnrichedParser.java
More file actions
1197 lines (1062 loc) · 42.4 KB
/
Copy pathEnrichedParser.java
File metadata and controls
1197 lines (1062 loc) · 42.4 KB
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
package com.swmansion.enriched.common.parser;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ParagraphStyle;
import com.swmansion.enriched.common.EnrichedConstants;
import com.swmansion.enriched.common.EnrichedSpanFlags;
import com.swmansion.enriched.common.spans.EnrichedAlignmentSpan;
import com.swmansion.enriched.common.spans.EnrichedBoldSpan;
import com.swmansion.enriched.common.spans.EnrichedCheckboxListSpan;
import com.swmansion.enriched.common.spans.EnrichedCodeBlockSpan;
import com.swmansion.enriched.common.spans.EnrichedCustomStyleSpan;
import com.swmansion.enriched.common.spans.EnrichedH1Span;
import com.swmansion.enriched.common.spans.EnrichedH2Span;
import com.swmansion.enriched.common.spans.EnrichedH3Span;
import com.swmansion.enriched.common.spans.EnrichedH4Span;
import com.swmansion.enriched.common.spans.EnrichedH5Span;
import com.swmansion.enriched.common.spans.EnrichedH6Span;
import com.swmansion.enriched.common.spans.EnrichedImageSpan;
import com.swmansion.enriched.common.spans.EnrichedInlineCodeSpan;
import com.swmansion.enriched.common.spans.EnrichedItalicSpan;
import com.swmansion.enriched.common.spans.EnrichedLinkSpan;
import com.swmansion.enriched.common.spans.EnrichedMentionSpan;
import com.swmansion.enriched.common.spans.EnrichedOrderedListSpan;
import com.swmansion.enriched.common.spans.EnrichedStrikeThroughSpan;
import com.swmansion.enriched.common.spans.EnrichedUnderlineSpan;
import com.swmansion.enriched.common.spans.EnrichedUnorderedListSpan;
import com.swmansion.enriched.common.spans.interfaces.EnrichedBlockSpan;
import com.swmansion.enriched.common.spans.interfaces.EnrichedInlineSpan;
import com.swmansion.enriched.common.spans.interfaces.EnrichedParagraphSpan;
import com.swmansion.enriched.common.spans.interfaces.EnrichedSpan;
import com.swmansion.enriched.common.spans.interfaces.EnrichedZeroWidthSpaceSpan;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ccil.cowan.tagsoup.HTMLSchema;
import org.ccil.cowan.tagsoup.Parser;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
/**
* Most of the code in this file is copied from the Android source code and adjusted to our needs.
* For the reference see <a
* href="https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/text/Html.java">docs</a>
*/
public class EnrichedParser {
/** Retrieves images for HTML <img> tags. */
private EnrichedParser() {}
/**
* Lazy initialization holder for HTML parser. This class will a) be preloaded by the zygote, or
* b) not loaded until absolutely necessary.
*/
private static class HtmlParser {
private static final HTMLSchema schema = new HTMLSchema();
}
public static <T> Spanned fromHtml(String source, T style, EnrichedSpanFactory<T> spanFactory) {
return fromHtml(source, style, spanFactory, null);
}
public static <T> Spanned fromHtml(
String source, T style, EnrichedSpanFactory<T> spanFactory, Pattern linkRegex) {
Parser parser = new Parser();
try {
parser.setProperty(Parser.schemaProperty, HtmlParser.schema);
} catch (SAXNotRecognizedException | SAXNotSupportedException e) {
// Should not happen.
throw new RuntimeException(e);
}
HtmlToSpannedConverter converter =
new HtmlToSpannedConverter(source, style, parser, spanFactory, linkRegex);
return converter.convert();
}
public static String toHtml(Spanned text) {
StringBuilder out = new StringBuilder();
withinHtml(out, text);
String outString = out.toString();
// Codeblocks and blockquotes appends a newline character by default, so we have to remove it
String normalizedCodeBlock = outString.replaceAll("</codeblock>\\n<br>", "</codeblock>");
String normalizedBlockQuote =
normalizedCodeBlock.replaceAll("</blockquote>\\n<br>", "</blockquote>");
// Replace empty <p> tags (with or without style attributes) with <br>
String normalizedHtml = normalizedBlockQuote.replaceAll("<p[^>]*></p>", "<br>");
return "<html>\n" + normalizedHtml + "</html>";
}
public static String toHtmlWithDefault(CharSequence text) {
if (text instanceof Spanned) {
return toHtml((Spanned) text);
}
return "<html>\n<p></p>\n</html>";
}
/** Returns an HTML escaped representation of the given plain text. */
public static String escapeHtml(CharSequence text) {
StringBuilder out = new StringBuilder();
withinStyle(out, text, 0, text.length());
return out.toString();
}
private static void withinHtml(StringBuilder out, Spanned text) {
withinDiv(out, text, 0, text.length());
}
private static void withinDiv(StringBuilder out, Spanned text, int start, int end) {
int next;
for (int i = start; i < end; i = next) {
next = text.nextSpanTransition(i, end, EnrichedBlockSpan.class);
EnrichedBlockSpan[] blocks = text.getSpans(i, next, EnrichedBlockSpan.class);
String tag = "unknown";
if (blocks.length > 0) {
tag = blocks[0] instanceof EnrichedCodeBlockSpan ? "codeblock" : "blockquote";
}
// Each block appends a newline by default.
// If we set up a new block, we have to remove the last character.
if (out.length() >= 5 && out.substring(out.length() - 5).equals("<br>\n")) {
out.replace(out.length() - 5, out.length(), "");
}
for (EnrichedBlockSpan ignored : blocks) {
out.append("<").append(tag).append(">\n");
}
withinBlock(out, text, i, next);
for (EnrichedBlockSpan ignored : blocks) {
out.append("</").append(tag).append(">\n");
}
}
}
private static String getAlignmentStyleAttr(Spanned text, int start, int end) {
EnrichedAlignmentSpan[] spans = text.getSpans(start, end, EnrichedAlignmentSpan.class);
if (spans.length == 0) return "";
String cssValue = spans[0].getCssValue();
if (cssValue.equals("auto")) return "";
return " style=\"text-align: " + cssValue + "\"";
}
private static String getBlockTag(EnrichedParagraphSpan[] spans) {
for (EnrichedParagraphSpan span : spans) {
if (span instanceof EnrichedUnorderedListSpan) {
return "ul";
} else if (span instanceof EnrichedOrderedListSpan) {
return "ol";
} else if (span instanceof EnrichedCheckboxListSpan) {
return "ul data-type=\"checkbox\"";
} else if (span instanceof EnrichedH1Span) {
return "h1";
} else if (span instanceof EnrichedH2Span) {
return "h2";
} else if (span instanceof EnrichedH3Span) {
return "h3";
} else if (span instanceof EnrichedH4Span) {
return "h4";
} else if (span instanceof EnrichedH5Span) {
return "h5";
} else if (span instanceof EnrichedH6Span) {
return "h6";
}
}
return "p";
}
private static void withinBlock(StringBuilder out, Spanned text, int start, int end) {
boolean isInUlList = false;
boolean isInOlList = false;
boolean isInCheckboxList = false;
int next;
for (int i = start; i <= end; i = next) {
next = TextUtils.indexOf(text, '\n', i, end);
if (next < 0) {
next = end;
}
if (next == i) {
if (isInUlList) {
// Current paragraph is no longer a list item; close the previously opened list
isInUlList = false;
out.append("</ul>\n");
} else if (isInOlList) {
// Current paragraph is no longer a list item; close the previously opened list
isInOlList = false;
out.append("</ol>\n");
} else if (isInCheckboxList) {
// Current paragraph is no longer a list item; close the previously opened list
isInCheckboxList = false;
out.append("</ul>\n");
}
out.append("<br>\n");
} else {
EnrichedParagraphSpan[] paragraphStyles =
text.getSpans(i, next, EnrichedParagraphSpan.class);
String tag = getBlockTag(paragraphStyles);
boolean isUlListItem = tag.equals("ul");
boolean isOlListItem = tag.equals("ol");
boolean isCheckboxListItem = tag.equals("ul data-type=\"checkbox\"");
if (isInUlList && !isUlListItem) {
// Current paragraph is no longer a list item; close the previously opened list
isInUlList = false;
out.append("</ul>\n");
} else if (isInOlList && !isOlListItem) {
// Current paragraph is no longer a list item; close the previously opened list
isInOlList = false;
out.append("</ol>\n");
} else if (isInCheckboxList && !isCheckboxListItem) {
// Current paragraph is no longer a list item; close the previously opened list
isInCheckboxList = false;
out.append("</ul>\n");
}
if (isUlListItem && !isInUlList) {
// Current paragraph is the first item in a list
isInUlList = true;
out.append("<ul").append(getAlignmentStyleAttr(text, i, next)).append(">\n");
} else if (isOlListItem && !isInOlList) {
// Current paragraph is the first item in a list
isInOlList = true;
out.append("<ol").append(getAlignmentStyleAttr(text, i, next)).append(">\n");
} else if (isCheckboxListItem && !isInCheckboxList) {
// Current paragraph is the first item in a list
isInCheckboxList = true;
out.append("<ul data-type=\"checkbox\"")
.append(getAlignmentStyleAttr(text, i, next))
.append(">\n");
}
boolean isList = isUlListItem || isOlListItem || isCheckboxListItem;
String tagType = isList ? "li" : tag;
out.append("<");
out.append(tagType);
// Add alignment style to non-list paragraph/heading tags
if (!isList) {
out.append(getAlignmentStyleAttr(text, i, next));
}
if (isCheckboxListItem) {
EnrichedCheckboxListSpan[] checkboxSpans =
text.getSpans(i, next, EnrichedCheckboxListSpan.class);
if (checkboxSpans.length > 0) {
boolean isChecked = checkboxSpans[0].isChecked();
if (isChecked) out.append(" checked");
}
}
out.append(">");
withinParagraph(out, text, i, next);
out.append("</");
out.append(tagType);
out.append(">\n");
if (next == end && isInUlList) {
isInUlList = false;
out.append("</ul>\n");
} else if (next == end && isInOlList) {
isInOlList = false;
out.append("</ol>\n");
} else if (next == end && isInCheckboxList) {
isInCheckboxList = false;
out.append("</ul>\n");
}
}
next++;
}
}
private static void withinParagraph(StringBuilder out, Spanned text, int start, int end) {
int next;
for (int i = start; i < end; i = next) {
next = text.nextSpanTransition(i, end, EnrichedInlineSpan.class);
EnrichedInlineSpan[] style = text.getSpans(i, next, EnrichedInlineSpan.class);
for (int j = 0; j < style.length; j++) {
if (style[j] instanceof EnrichedBoldSpan) {
out.append("<b>");
}
if (style[j] instanceof EnrichedItalicSpan) {
out.append("<i>");
}
if (style[j] instanceof EnrichedUnderlineSpan) {
out.append("<u>");
}
if (style[j] instanceof EnrichedInlineCodeSpan) {
out.append("<code>");
}
if (style[j] instanceof EnrichedStrikeThroughSpan) {
out.append("<s>");
}
if (style[j] instanceof EnrichedLinkSpan) {
out.append("<a href=\"");
out.append(((EnrichedLinkSpan) style[j]).getUrl());
out.append("\">");
}
if (style[j] instanceof EnrichedMentionSpan) {
out.append("<mention text=\"");
out.append(((EnrichedMentionSpan) style[j]).getText());
out.append("\"");
out.append(" indicator=\"");
out.append(((EnrichedMentionSpan) style[j]).getIndicator());
out.append("\"");
Map<String, String> attributes = ((EnrichedMentionSpan) style[j]).getAttributes();
for (Map.Entry<String, String> entry : attributes.entrySet()) {
out.append(" ");
out.append(entry.getKey());
out.append("=\"");
out.append(entry.getValue());
out.append("\"");
}
out.append(">");
}
if (style[j] instanceof EnrichedImageSpan) {
out.append("<img src=\"");
out.append(((EnrichedImageSpan) style[j]).getSource());
out.append("\"");
out.append(" width=\"");
out.append(((EnrichedImageSpan) style[j]).getWidth());
out.append("\"");
out.append(" height=\"");
out.append(((EnrichedImageSpan) style[j]).getHeight());
out.append("\"/>");
// Don't output the placeholder character underlying the image.
i = next;
}
if (style[j] instanceof EnrichedCustomStyleSpan) {
EnrichedCustomStyleSpan cs = (EnrichedCustomStyleSpan) style[j];
Integer fgColor = cs.getForegroundColor();
Integer bgColor = cs.getBackgroundColor();
Float fontSize = cs.getFontSize();
String fontFamily = cs.getFontFamily();
if (fgColor != null
|| bgColor != null
|| fontSize != null
|| (fontFamily != null && !fontFamily.isEmpty())) {
StringBuilder cssProps = new StringBuilder();
if (fgColor != null) {
cssProps
.append("color: ")
.append(EnrichedColorParser.colorToHex(fgColor))
.append(";");
}
if (bgColor != null) {
if (cssProps.length() > 0) cssProps.append(" ");
cssProps
.append("background-color: ")
.append(EnrichedColorParser.colorToHex(bgColor))
.append(";");
}
if (fontSize != null) {
if (cssProps.length() > 0) cssProps.append(" ");
cssProps.append("font-size: ").append(formatCssFontSizeValue(fontSize)).append("px;");
}
if (fontFamily != null && !fontFamily.isEmpty()) {
if (cssProps.length() > 0) cssProps.append(" ");
if (fontFamily.indexOf(' ') >= 0) {
cssProps.append("font-family: '").append(fontFamily).append("';");
} else {
cssProps.append("font-family: ").append(fontFamily).append(";");
}
}
out.append("<span style=\"").append(cssProps).append("\">");
} else {
out.append("<span>");
}
}
}
withinStyle(out, text, i, next);
for (int j = style.length - 1; j >= 0; j--) {
if (style[j] instanceof EnrichedLinkSpan) {
out.append("</a>");
}
if (style[j] instanceof EnrichedMentionSpan) {
out.append("</mention>");
}
if (style[j] instanceof EnrichedStrikeThroughSpan) {
out.append("</s>");
}
if (style[j] instanceof EnrichedUnderlineSpan) {
out.append("</u>");
}
if (style[j] instanceof EnrichedInlineCodeSpan) {
out.append("</code>");
}
if (style[j] instanceof EnrichedBoldSpan) {
out.append("</b>");
}
if (style[j] instanceof EnrichedItalicSpan) {
out.append("</i>");
}
if (style[j] instanceof EnrichedCustomStyleSpan) {
out.append("</span>");
}
}
}
}
private static void withinStyle(StringBuilder out, CharSequence text, int start, int end) {
for (int i = start; i < end; i++) {
char c = text.charAt(i);
if (c == EnrichedConstants.ZWS) {
// Do not output zero-width space characters.
continue;
} else if (c == '<') {
out.append("<");
} else if (c == '>') {
out.append(">");
} else if (c == '&') {
out.append("&");
} else if (c >= 0xD800 && c <= 0xDFFF) {
if (c < 0xDC00 && i + 1 < end) {
char d = text.charAt(i + 1);
if (d >= 0xDC00 && d <= 0xDFFF) {
i++;
int codepoint = 0x010000 | (int) c - 0xD800 << 10 | (int) d - 0xDC00;
out.append("&#").append(codepoint).append(";");
}
}
} else if (c > 0x7E || c < ' ') {
out.append("&#").append((int) c).append(";");
} else if (c == ' ') {
while (i + 1 < end && text.charAt(i + 1) == ' ') {
out.append(" ");
i++;
}
out.append(' ');
} else {
out.append(c);
}
}
}
private static String formatCssFontSizeValue(float fontSize) {
if (fontSize == Math.rint(fontSize) && !Float.isInfinite(fontSize)) {
return String.valueOf((int) fontSize);
}
return String.valueOf(fontSize);
}
}
class HtmlToSpannedConverter<T> implements ContentHandler {
private final EnrichedSpanFactory<T> mSpanFactory;
private final T mStyle;
private final String mSource;
private final XMLReader mReader;
private final SpannableStringBuilder mSpannableStringBuilder;
private final Pattern mLinkRegex;
private static Integer currentOrderedListItemIndex = 0;
private static Boolean isInOrderedList = false;
private static Boolean isInCheckboxList = false;
private static Boolean isEmptyTag = false;
private static String currentListAlignmentCssValue = null;
private static final Pattern CSS_ALIGNMENT_PATTERN =
Pattern.compile("text-align\\s*:\\s*(left|center|right)", Pattern.CASE_INSENSITIVE);
private static final Pattern CSS_FG_PATTERN =
Pattern.compile("(?:^|;)\\s*(?<!background-)color\\s*:\\s*([^;]+)", Pattern.CASE_INSENSITIVE);
private static final Pattern CSS_BG_PATTERN =
Pattern.compile("background-color\\s*:\\s*([^;]+)", Pattern.CASE_INSENSITIVE);
private static final Pattern CSS_FONT_SIZE_PATTERN =
Pattern.compile(
"font-size\\s*:\\s*([0-9.]+)(?:\\s*px)?(?=\\s*;|\\s*$)", Pattern.CASE_INSENSITIVE);
private static final Pattern CSS_FONT_FAMILY_PATTERN =
Pattern.compile("font-family\\s*:\\s*([^;]+)", Pattern.CASE_INSENSITIVE);
private static String parseCssAlignmentValue(Attributes attributes) {
String style = attributes.getValue("", "style");
if (style == null) return null;
Matcher m = CSS_ALIGNMENT_PATTERN.matcher(style);
return m.find() ? m.group(1).toLowerCase() : null;
}
private static void pushAlignmentMark(Editable text, Attributes attributes) {
String cssValue = parseCssAlignmentValue(attributes);
if (cssValue != null) {
start(text, new Alignment(cssValue));
}
}
public HtmlToSpannedConverter(
String source,
T style,
Parser parser,
EnrichedSpanFactory<T> spanFactory,
Pattern linkRegex) {
mStyle = style;
mSource = source;
mSpannableStringBuilder = new SpannableStringBuilder();
mReader = parser;
mSpanFactory = spanFactory;
mLinkRegex = linkRegex;
}
public Spanned convert() {
mReader.setContentHandler(this);
try {
mReader.parse(new InputSource(new StringReader(mSource)));
} catch (IOException e) {
// We are reading from a string. There should not be IO problems.
throw new RuntimeException(e);
} catch (SAXException e) {
// TagSoup doesn't throw parse exceptions.
throw new RuntimeException(e);
}
// Fix flags and range for paragraph-type markup.
Object[] obj =
mSpannableStringBuilder.getSpans(0, mSpannableStringBuilder.length(), ParagraphStyle.class);
for (int i = 0; i < obj.length; i++) {
int start = mSpannableStringBuilder.getSpanStart(obj[i]);
int end = mSpannableStringBuilder.getSpanEnd(obj[i]);
// If the last line of the range is blank, back off by one.
if (end - 2 >= 0) {
if (mSpannableStringBuilder.charAt(end - 1) == '\n'
&& mSpannableStringBuilder.charAt(end - 2) == '\n') {
end--;
}
}
if (end == start) {
mSpannableStringBuilder.removeSpan(obj[i]);
} else {
mSpannableStringBuilder.setSpan(obj[i], start, end, EnrichedSpanFlags.forSpan(obj[i]));
}
}
// Assign zero-width space character to the proper spans.
EnrichedZeroWidthSpaceSpan[] zeroWidthSpaceSpans =
mSpannableStringBuilder.getSpans(
0, mSpannableStringBuilder.length(), EnrichedZeroWidthSpaceSpan.class);
for (EnrichedZeroWidthSpaceSpan zeroWidthSpaceSpan : zeroWidthSpaceSpans) {
int start = mSpannableStringBuilder.getSpanStart(zeroWidthSpaceSpan);
int end = mSpannableStringBuilder.getSpanEnd(zeroWidthSpaceSpan);
if (mSpannableStringBuilder.charAt(start) != EnrichedConstants.ZWS) {
// Collect spans before inserting ZWS. SPAN_EXCLUSIVE_EXCLUSIVE spans will
// shift to start+1. We must re-anchor them back to `start` to prevent
// the loop from processing them again and inserting duplicate ZWS.
EnrichedSpan[] colocated =
mSpannableStringBuilder.getSpans(start, start + 1, EnrichedSpan.class);
mSpannableStringBuilder.insert(start, EnrichedConstants.ZWS_STRING);
end++;
for (EnrichedSpan span : colocated) {
if (span == zeroWidthSpaceSpan) continue;
// Only re-anchor spans that actually shifted.
// Skip overlapping or INCLUSIVE spans that kept their original start.
if (mSpannableStringBuilder.getSpanStart(span) != start + 1) continue;
int spanEnd = mSpannableStringBuilder.getSpanEnd(span);
mSpannableStringBuilder.removeSpan(span);
mSpannableStringBuilder.setSpan(span, start, spanEnd, EnrichedSpanFlags.forSpan(span));
}
}
mSpannableStringBuilder.removeSpan(zeroWidthSpaceSpan);
mSpannableStringBuilder.setSpan(
zeroWidthSpaceSpan, start, end, EnrichedSpanFlags.forSpan(zeroWidthSpaceSpan));
}
return mSpannableStringBuilder;
}
private void handleStartTag(String tag, Attributes attributes) {
if (tag.equalsIgnoreCase("br")) {
// We don't need to handle this. TagSoup will ensure that there's a </br> for each <br>
// so we can safely emit the linebreaks when we handle the close tag.
} else if (tag.equalsIgnoreCase("p")) {
isEmptyTag = true;
startBlockElement(mSpannableStringBuilder);
pushAlignmentMark(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("ul")) {
isInOrderedList = false;
String dataType = attributes.getValue("", "data-type");
isInCheckboxList = "checkbox".equals(dataType);
currentListAlignmentCssValue = parseCssAlignmentValue(attributes);
startBlockElement(mSpannableStringBuilder);
} else if (tag.equalsIgnoreCase("ol")) {
isInOrderedList = true;
currentOrderedListItemIndex = 0;
currentListAlignmentCssValue = parseCssAlignmentValue(attributes);
startBlockElement(mSpannableStringBuilder);
} else if (tag.equalsIgnoreCase("li")) {
isEmptyTag = true;
startLi(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("b")) {
start(mSpannableStringBuilder, new Bold());
} else if (tag.equalsIgnoreCase("i")) {
start(mSpannableStringBuilder, new Italic());
} else if (tag.equalsIgnoreCase("blockquote")) {
isEmptyTag = true;
startBlockquote(mSpannableStringBuilder);
} else if (tag.equalsIgnoreCase("codeblock")) {
isEmptyTag = true;
startCodeBlock(mSpannableStringBuilder);
} else if (tag.equalsIgnoreCase("a")) {
startA(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("u")) {
start(mSpannableStringBuilder, new Underline());
} else if (tag.equalsIgnoreCase("s")) {
start(mSpannableStringBuilder, new Strikethrough());
} else if (tag.equalsIgnoreCase("strike")) {
start(mSpannableStringBuilder, new Strikethrough());
} else if (tag.equalsIgnoreCase("h1")) {
startHeading(mSpannableStringBuilder, 1);
pushAlignmentMark(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("h2")) {
startHeading(mSpannableStringBuilder, 2);
pushAlignmentMark(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("h3")) {
startHeading(mSpannableStringBuilder, 3);
pushAlignmentMark(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("h4")) {
startHeading(mSpannableStringBuilder, 4);
pushAlignmentMark(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("h5")) {
startHeading(mSpannableStringBuilder, 5);
pushAlignmentMark(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("h6")) {
startHeading(mSpannableStringBuilder, 6);
pushAlignmentMark(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("img")) {
// Image content means the current tag is not empty (e.g. <li><img .../></li>).
isEmptyTag = false;
startImg(mSpannableStringBuilder, attributes, mSpanFactory);
} else if (tag.equalsIgnoreCase("code")) {
start(mSpannableStringBuilder, new Code());
} else if (tag.equalsIgnoreCase("mention")) {
startMention(mSpannableStringBuilder, attributes);
} else if (tag.equalsIgnoreCase("span")) {
startSpan(mSpannableStringBuilder, attributes);
}
}
private void handleEndTag(String tag) {
if (tag.equalsIgnoreCase("br")) {
handleBr(mSpannableStringBuilder);
} else if (tag.equalsIgnoreCase("p")) {
endBlockElement(mSpannableStringBuilder, mSpanFactory);
} else if (tag.equalsIgnoreCase("ul")) {
currentListAlignmentCssValue = null;
endBlockElement(mSpannableStringBuilder, mSpanFactory);
} else if (tag.equalsIgnoreCase("ol")) {
currentListAlignmentCssValue = null;
endBlockElement(mSpannableStringBuilder, mSpanFactory);
} else if (tag.equalsIgnoreCase("li")) {
endLi(mSpannableStringBuilder, mStyle, mSpanFactory);
} else if (tag.equalsIgnoreCase("b")) {
end(mSpannableStringBuilder, Bold.class, mSpanFactory.createBoldSpan(mStyle));
} else if (tag.equalsIgnoreCase("i")) {
end(mSpannableStringBuilder, Italic.class, mSpanFactory.createItalicSpan(mStyle));
} else if (tag.equalsIgnoreCase("blockquote")) {
endBlockquote(mSpannableStringBuilder, mStyle, mSpanFactory);
} else if (tag.equalsIgnoreCase("codeblock")) {
endCodeBlock(mSpannableStringBuilder, mStyle, mSpanFactory);
} else if (tag.equalsIgnoreCase("a")) {
endA(mSpannableStringBuilder, mStyle, mSpanFactory, mLinkRegex);
} else if (tag.equalsIgnoreCase("u")) {
end(mSpannableStringBuilder, Underline.class, mSpanFactory.createUnderlineSpan(mStyle));
} else if (tag.equalsIgnoreCase("s")) {
end(
mSpannableStringBuilder,
Strikethrough.class,
mSpanFactory.createStrikeThroughSpan(mStyle));
} else if (tag.equalsIgnoreCase("h1")) {
endHeading(mSpannableStringBuilder, mStyle, mSpanFactory, 1);
} else if (tag.equalsIgnoreCase("h2")) {
endHeading(mSpannableStringBuilder, mStyle, mSpanFactory, 2);
} else if (tag.equalsIgnoreCase("h3")) {
endHeading(mSpannableStringBuilder, mStyle, mSpanFactory, 3);
} else if (tag.equalsIgnoreCase("h4")) {
endHeading(mSpannableStringBuilder, mStyle, mSpanFactory, 4);
} else if (tag.equalsIgnoreCase("h5")) {
endHeading(mSpannableStringBuilder, mStyle, mSpanFactory, 5);
} else if (tag.equalsIgnoreCase("h6")) {
endHeading(mSpannableStringBuilder, mStyle, mSpanFactory, 6);
} else if (tag.equalsIgnoreCase("code")) {
end(mSpannableStringBuilder, Code.class, mSpanFactory.createInlineCodeSpan(mStyle));
} else if (tag.equalsIgnoreCase("mention")) {
endMention(mSpannableStringBuilder, mStyle, mSpanFactory);
} else if (tag.equalsIgnoreCase("span")) {
endSpan(mSpannableStringBuilder, mStyle, mSpanFactory);
}
}
private static void appendNewlines(Editable text, int minNewline) {
final int len = text.length();
if (len == 0) {
return;
}
int existingNewlines = 0;
for (int i = len - 1; i >= 0 && text.charAt(i) == '\n'; i--) {
existingNewlines++;
}
for (int j = existingNewlines; j < minNewline; j++) {
text.append("\n");
}
}
private static void startBlockElement(Editable text) {
appendNewlines(text, 1);
start(text, new Newline(1));
}
private static <T> void endBlockElement(Editable text, EnrichedSpanFactory<T> spanFactory) {
Newline n = getLast(text, Newline.class);
if (n != null) {
appendNewlines(text, n.mNumNewlines);
text.removeSpan(n);
}
Alignment a = getLast(text, Alignment.class);
if (a != null) {
setParagraphSpanFromMark(text, a, spanFactory.createAlignmentSpan(a.mCssValue));
}
}
private static void handleBr(Editable text) {
text.append('\n');
}
private void startLi(Editable text, Attributes attributes) {
startBlockElement(text);
if (currentListAlignmentCssValue != null) {
start(text, new Alignment(currentListAlignmentCssValue));
}
if (isInOrderedList) {
currentOrderedListItemIndex++;
start(text, new List("ordered", currentOrderedListItemIndex, false));
} else if (isInCheckboxList) {
String isChecked = attributes.getValue("", "checked");
start(text, new List("checked", 0, "checked".equals(isChecked)));
} else {
start(text, new List("unordered", 0, false));
}
}
private static <T> void endLi(Editable text, T style, EnrichedSpanFactory<T> spanFactory) {
endBlockElement(text, spanFactory);
List l = getLast(text, List.class);
if (l != null) {
if (l.mType.equals("ordered")) {
setParagraphSpanFromMark(text, l, spanFactory.createOrderedListSpan(l.mIndex, style));
} else if (l.mType.equals("checked")) {
setParagraphSpanFromMark(text, l, spanFactory.createCheckboxListSpan(l.mChecked, style));
} else {
setParagraphSpanFromMark(text, l, spanFactory.createUnorderedListSpan(style));
}
}
endBlockElement(text, spanFactory);
}
private void startBlockquote(Editable text) {
startBlockElement(text);
start(text, new Blockquote());
}
private static <T> void endBlockquote(
Editable text, T style, EnrichedSpanFactory<T> spanFactory) {
endBlockElement(text, spanFactory);
Blockquote last = getLast(text, Blockquote.class);
setParagraphSpanFromMark(text, last, spanFactory.createBlockQuoteSpan(style));
}
private void startCodeBlock(Editable text) {
startBlockElement(text);
start(text, new CodeBlock());
}
private static <T> void endCodeBlock(Editable text, T style, EnrichedSpanFactory<T> spanFactory) {
endBlockElement(text, spanFactory);
CodeBlock last = getLast(text, CodeBlock.class);
setParagraphSpanFromMark(text, last, spanFactory.createCodeBlockSpan(style));
}
private void startHeading(Editable text, int level) {
startBlockElement(text);
switch (level) {
case 1:
start(text, new H1());
break;
case 2:
start(text, new H2());
break;
case 3:
start(text, new H3());
break;
case 4:
start(text, new H4());
break;
case 5:
start(text, new H5());
break;
case 6:
start(text, new H6());
break;
default:
throw new IllegalArgumentException("Unsupported heading level: " + level);
}
}
private static <T> void endHeading(
Editable text, T style, EnrichedSpanFactory<T> spanFactory, int level) {
endBlockElement(text, spanFactory);
switch (level) {
case 1:
H1 lastH1 = getLast(text, H1.class);
setParagraphSpanFromMark(text, lastH1, spanFactory.createH1Span(style));
break;
case 2:
H2 lastH2 = getLast(text, H2.class);
setParagraphSpanFromMark(text, lastH2, spanFactory.createH2Span(style));
break;
case 3:
H3 lastH3 = getLast(text, H3.class);
setParagraphSpanFromMark(text, lastH3, spanFactory.createH3Span(style));
break;
case 4:
H4 lastH4 = getLast(text, H4.class);
setParagraphSpanFromMark(text, lastH4, spanFactory.createH4Span(style));
break;
case 5:
H5 lastH5 = getLast(text, H5.class);
setParagraphSpanFromMark(text, lastH5, spanFactory.createH5Span(style));
break;
case 6:
H6 lastH6 = getLast(text, H6.class);
setParagraphSpanFromMark(text, lastH6, spanFactory.createH6Span(style));
break;
default:
throw new IllegalArgumentException("Unsupported heading level: " + level);
}
}
private static <T> T getLast(Spanned text, Class<T> kind) {
/*
* This knows that the last returned object from getSpans()
* will be the most recently added.
*/
T[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
return objs[objs.length - 1];
}
}
private static void setSpanFromMark(Spannable text, Object mark, Object... spans) {
int where = text.getSpanStart(mark);
text.removeSpan(mark);
int len = text.length();
if (where != len) {
for (Object span : spans) {
text.setSpan(span, where, len, EnrichedSpanFlags.forSpan(span));
}
}
}
private static void setParagraphSpanFromMark(Editable text, Object mark, Object... spans) {
int where = text.getSpanStart(mark);
text.removeSpan(mark);
int len = text.length();
// Block spans require at least one character to be applied.
if (isEmptyTag) {
text.append(EnrichedConstants.ZWS);
len++;
}
// Adjust the end position to exclude the newline character, if present
if (len > 0 && text.charAt(len - 1) == '\n') {
len--;
}
if (where != len) {
for (Object span : spans) {
text.setSpan(span, where, len, EnrichedSpanFlags.forSpan(span));
}
}
}
private static void start(Editable text, Object mark) {
int len = text.length();
text.setSpan(
mark, len, len, EnrichedSpanFlags.forSpan(mark, Spannable.SPAN_INCLUSIVE_EXCLUSIVE));
}
private static void end(Editable text, Class kind, Object repl) {
Object obj = getLast(text, kind);
if (obj != null) {
setSpanFromMark(text, obj, repl);
}
}
private static <T> void startImg(
Editable text, Attributes attributes, EnrichedSpanFactory<T> spanFactory) {
String src = attributes.getValue("", "src");
String width = attributes.getValue("", "width");
String height = attributes.getValue("", "height");
int len = text.length();
text.append("");
Object imageSpan =
spanFactory.createImageSpan(src, parseDimension(width), parseDimension(height));
text.setSpan(imageSpan, len, text.length(), EnrichedSpanFlags.forSpan(imageSpan));
}
private static int parseDimension(String value) {
if (value == null) return 0;
try {
int parsed = (int) Math.floor(Float.parseFloat(value));
return Math.max(parsed, 0);
} catch (NumberFormatException e) {
return 0;
}
}
private static void startA(Editable text, Attributes attributes) {
String href = attributes.getValue("", "href");
start(text, new Href(href));
}
private static boolean urlMatchesLinkRegex(String url, Pattern linkRegex) {
if (linkRegex == null) return false;
return linkRegex.matcher(url).matches();
}
private static <T> void endA(
Editable text, T style, EnrichedSpanFactory<T> spanFactory, Pattern linkRegex) {
Href h = getLast(text, Href.class);
if (h != null && h.mHref != null) {
String linkText = text.subSequence(text.getSpanStart(h), text.length()).toString();
boolean isManual = !linkText.equals(h.mHref) || !urlMatchesLinkRegex(h.mHref, linkRegex);
setSpanFromMark(text, h, spanFactory.createLinkSpan(h.mHref, style, isManual));
}
}
private static void startMention(Editable mention, Attributes attributes) {
String text = attributes.getValue("", "text");
String indicator = attributes.getValue("", "indicator");
Map<String, String> attributesMap = new HashMap<>();
for (int i = 0; i < attributes.getLength(); i++) {
String localName = attributes.getLocalName(i);
if (!"text".equals(localName) && !"indicator".equals(localName)) {
attributesMap.put(localName, attributes.getValue(i));
}
}
start(mention, new Mention(indicator, text, attributesMap));
}
private static <T> void endMention(Editable text, T style, EnrichedSpanFactory<T> spanFactory) {
Mention m = getLast(text, Mention.class);
if (m == null) return;
if (m.mText == null) return;
setSpanFromMark(
text, m, spanFactory.createMentionSpan(m.mText, m.mIndicator, m.mAttributes, style));
}
private static void startSpan(Editable text, Attributes attributes) {
String styleAttr = attributes.getValue("", "style");
Integer fg = null;
Integer bg = null;
Float fontSize = null;
String fontFamily = null;
if (styleAttr != null) {