FairEmail/app/src/main/java/eu/faircode/email/HtmlHelper.java

3947 lines
169 KiB
Java
Raw Normal View History

2018-08-02 13:33:06 +00:00
package eu.faircode.email;
/*
2018-08-14 05:53:24 +00:00
This file is part of FairEmail.
2018-08-02 13:33:06 +00:00
2018-08-14 05:53:24 +00:00
FairEmail is free software: you can redistribute it and/or modify
2018-08-02 13:33:06 +00:00
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-08-02 13:33:06 +00:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-08-02 13:33:06 +00:00
2023-01-01 07:52:55 +00:00
Copyright 2018-2023 by Marcel Bokhorst (M66B)
2018-08-02 13:33:06 +00:00
*/
2021-08-01 05:13:38 +00:00
import static androidx.core.text.HtmlCompat.TO_HTML_PARAGRAPH_LINES_INDIVIDUAL;
import static org.w3c.css.sac.Condition.SAC_CLASS_CONDITION;
import android.app.ActivityManager;
2018-12-14 09:11:45 +00:00
import android.content.Context;
import android.content.SharedPreferences;
2021-08-04 15:19:43 +00:00
import android.content.res.TypedArray;
2019-10-04 21:04:03 +00:00
import android.graphics.Bitmap;
import android.graphics.Canvas;
2019-09-24 12:46:12 +00:00
import android.graphics.Color;
import android.graphics.Typeface;
2019-10-04 21:04:03 +00:00
import android.graphics.drawable.Drawable;
2019-09-13 11:46:52 +00:00
import android.net.Uri;
2019-09-07 18:13:58 +00:00
import android.os.Build;
2019-02-10 12:01:21 +00:00
import android.text.Html;
2020-04-24 21:13:32 +00:00
import android.text.Layout;
2020-04-23 17:45:33 +00:00
import android.text.Spannable;
2019-08-29 19:57:04 +00:00
import android.text.SpannableStringBuilder;
2019-02-10 12:01:21 +00:00
import android.text.Spanned;
2021-04-29 15:26:02 +00:00
import android.text.TextDirectionHeuristics;
2018-12-14 09:11:45 +00:00
import android.text.TextUtils;
2022-03-30 18:20:24 +00:00
import android.text.format.DateUtils;
2021-08-04 15:19:43 +00:00
import android.text.style.AbsoluteSizeSpan;
2020-05-03 17:29:02 +00:00
import android.text.style.AlignmentSpan;
2021-07-04 09:58:54 +00:00
import android.text.style.BackgroundColorSpan;
2020-04-24 21:13:32 +00:00
import android.text.style.BulletSpan;
2021-07-04 09:58:54 +00:00
import android.text.style.CharacterStyle;
2021-07-01 07:19:59 +00:00
import android.text.style.ClickableSpan;
2019-08-29 19:57:04 +00:00
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.QuoteSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
2018-12-14 09:11:45 +00:00
import android.util.Base64;
import android.util.Patterns;
2021-07-01 07:19:59 +00:00
import android.view.View;
2018-12-14 09:11:45 +00:00
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
2022-08-04 13:24:27 +00:00
import androidx.core.content.ContextCompat;
2020-02-14 08:34:28 +00:00
import androidx.core.content.FileProvider;
import androidx.core.content.res.ResourcesCompat;
2020-01-26 12:41:12 +00:00
import androidx.core.graphics.ColorUtils;
import androidx.core.util.PatternsCompat;
import androidx.preference.PreferenceManager;
2020-04-21 07:04:55 +00:00
import com.steadystate.css.dom.CSSMediaRuleImpl;
2020-04-20 13:01:05 +00:00
import com.steadystate.css.dom.CSSStyleRuleImpl;
2020-04-21 07:04:55 +00:00
import com.steadystate.css.dom.MediaListImpl;
2020-04-20 13:01:05 +00:00
import com.steadystate.css.parser.CSSOMParser;
import com.steadystate.css.parser.SACParserCSS3;
import com.steadystate.css.parser.selectors.ClassConditionImpl;
import com.steadystate.css.parser.selectors.ConditionalSelectorImpl;
2020-04-22 14:32:35 +00:00
import com.steadystate.css.parser.selectors.ElementSelectorImpl;
2020-04-20 13:01:05 +00:00
2019-03-10 19:39:17 +00:00
import org.jsoup.nodes.Attribute;
2020-02-02 12:03:06 +00:00
import org.jsoup.nodes.Comment;
2018-08-02 13:33:06 +00:00
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
2018-08-02 13:33:06 +00:00
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
2019-03-12 09:04:16 +00:00
import org.jsoup.safety.Cleaner;
2021-09-11 18:44:55 +00:00
import org.jsoup.safety.Safelist;
2020-07-16 20:06:52 +00:00
import org.jsoup.select.Elements;
2020-02-02 12:03:06 +00:00
import org.jsoup.select.NodeFilter;
2018-08-02 13:33:06 +00:00
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
2020-04-20 13:01:05 +00:00
import org.w3c.css.sac.CSSException;
import org.w3c.css.sac.CSSParseException;
import org.w3c.css.sac.ErrorHandler;
import org.w3c.css.sac.InputSource;
import org.w3c.css.sac.Selector;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSRuleList;
import org.w3c.dom.css.CSSStyleSheet;
2020-04-21 07:04:55 +00:00
import org.w3c.dom.stylesheets.MediaList;
2018-08-02 13:33:06 +00:00
2021-06-15 13:15:03 +00:00
import java.io.ByteArrayInputStream;
2019-10-04 21:04:03 +00:00
import java.io.ByteArrayOutputStream;
2018-12-14 09:11:45 +00:00
import java.io.File;
2020-02-28 09:01:18 +00:00
import java.io.FileInputStream;
2018-12-14 09:11:45 +00:00
import java.io.IOException;
2020-02-28 09:01:18 +00:00
import java.io.InputStream;
2020-04-20 13:01:05 +00:00
import java.io.StringReader;
2021-10-01 17:24:06 +00:00
import java.net.URI;
2021-06-15 13:15:03 +00:00
import java.text.DateFormat;
2022-03-30 18:20:24 +00:00
import java.text.ParseException;
2021-06-15 13:15:03 +00:00
import java.text.ParsePosition;
2019-09-13 11:46:52 +00:00
import java.util.ArrayList;
2019-01-05 11:17:33 +00:00
import java.util.Arrays;
2020-10-30 17:10:57 +00:00
import java.util.Collections;
2020-04-22 09:10:14 +00:00
import java.util.Date;
2020-01-22 11:28:39 +00:00
import java.util.HashMap;
2021-04-21 15:35:04 +00:00
import java.util.LinkedHashMap;
2019-01-05 11:17:33 +00:00
import java.util.List;
2019-09-23 20:07:22 +00:00
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
2019-06-05 08:23:41 +00:00
import java.util.regex.Pattern;
2018-08-02 13:33:06 +00:00
2021-06-15 13:15:03 +00:00
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MailDateFormat;
import javax.mail.internet.MimeUtility;
public class HtmlHelper {
2021-02-11 15:24:32 +00:00
static final int PREVIEW_SIZE = 500; // characters
2022-08-27 15:48:36 +00:00
// https://drafts.csswg.org/css-fonts/#absolute-size-mapping
static final float FONT_XSMALL = 0.6f; // 10px=0.625
static final float FONT_SMALL = 0.8f; // 13px=0.8125
// 16 px
static final float FONT_LARGE = 1.25f; // 20px=1.2
static final float FONT_XLARGE = 1.50f; // 24px=1.5
2021-07-07 17:39:09 +00:00
2021-10-17 06:19:51 +00:00
static final int MAX_FULL_TEXT_SIZE = 1024 * 1024; // characters
static final int MAX_SHARE_TEXT_SIZE = 50 * 1024; // characters
static final int MAX_TRANSLATABLE_TEXT_SIZE = 50 * 1024; // characters
2020-02-20 10:37:40 +00:00
private static final int DEFAULT_FONT_SIZE = 16; // pixels
2020-04-28 16:32:10 +00:00
private static final int DEFAULT_FONT_SIZE_PT = 12; // points
private static final int GRAY_THRESHOLD = Math.round(255 * 0.2f);
2021-08-04 06:10:39 +00:00
private static final int COLOR_THRESHOLD = Math.round(255 * 0.1f);
private static final float MIN_LUMINANCE_VIEW = 0.7f;
private static final float MIN_LUMINANCE_COMPOSE = 0.85f;
2021-11-15 13:56:39 +00:00
private static final int TAB_SIZE = 4;
2020-05-04 18:19:05 +00:00
private static final int MAX_ALT = 250;
2019-09-01 07:44:03 +00:00
private static final int MAX_AUTO_LINK = 250;
2022-07-19 05:11:31 +00:00
private static final int MAX_FORMAT_TEXT_SIZE = 100 * 1024; // characters
2020-08-06 17:00:11 +00:00
private static final int SMALL_IMAGE_SIZE = 5; // pixels
2019-08-20 18:05:11 +00:00
private static final int TRACKING_PIXEL_SURFACE = 25; // pixels
private static final float[] HEADING_SIZES = {1.5f, 1.4f, 1.3f, 1.2f, 1.1f, 1f};
2020-05-04 13:21:34 +00:00
private static final String LINE = "----------------------------------------";
2022-05-06 18:58:39 +00:00
private static final String W3NS = /* http/https */ "://www.w3.org/";
2021-07-07 17:39:09 +00:00
2020-01-22 11:28:39 +00:00
private static final HashMap<String, Integer> x11ColorMap = new HashMap<>();
2022-03-08 14:20:41 +00:00
// https://www.w3.org/TR/CSS21/propidx.html
private static final List<String> STYLE_NO_INHERIT = Collections.unmodifiableList(Arrays.asList(
"background-attachment", "background-color", "background-image", "background-position", "background-repeat", "background",
"border-color", "border-style", "border-top", "border-right", "border-bottom", "border-left",
"border-top-color", "border-right-color", "border-bottom-color", "border-left-color",
"border-top-style", "border-right-style", "border-bottom-style", "border-left-style",
"border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
"border-width", "border",
"bottom",
"clear",
"clip",
"content",
"counter-increment", "counter-reset",
"cue-after", "cue-before", "cue",
"display",
"float",
"height",
"left",
"margin-right", "margin-left", "margin-top", "margin-bottom", "margin",
"max-height", "max-width", "min-height", "min-width",
"outline-color", "outline-style", "outline-width", "outline",
"overflow",
"padding-top", "padding-right", "padding-bottom", "padding-left",
"padding", "page-break-after", "page-break-before", "page-break-inside",
"pause-after", "pause-before", "pause",
"play-during",
"position",
"right",
"table-layout",
"text-decoration",
"top",
"unicode-bidi",
"vertical-align",
"width",
"z-index"
));
2020-01-22 11:28:39 +00:00
static {
// https://www.w3.org/TR/css-color-3/
x11ColorMap.put("aliceblue", 0xF0F8FF);
x11ColorMap.put("antiquewhite", 0xFAEBD7);
x11ColorMap.put("aqua", 0x00FFFF);
x11ColorMap.put("aquamarine", 0x7FFFD4);
x11ColorMap.put("azure", 0xF0FFFF);
x11ColorMap.put("beige", 0xF5F5DC);
x11ColorMap.put("bisque", 0xFFE4C4);
x11ColorMap.put("black", 0x000000);
x11ColorMap.put("blanchedalmond", 0xFFEBCD);
x11ColorMap.put("blue", 0x0000FF);
x11ColorMap.put("blueviolet", 0x8A2BE2);
x11ColorMap.put("brown", 0xA52A2A);
x11ColorMap.put("burlywood", 0xDEB887);
x11ColorMap.put("cadetblue", 0x5F9EA0);
x11ColorMap.put("chartreuse", 0x7FFF00);
x11ColorMap.put("chocolate", 0xD2691E);
x11ColorMap.put("coral", 0xFF7F50);
x11ColorMap.put("cornflowerblue", 0x6495ED);
x11ColorMap.put("cornsilk", 0xFFF8DC);
x11ColorMap.put("crimson", 0xDC143C);
x11ColorMap.put("cyan", 0x00FFFF);
x11ColorMap.put("darkblue", 0x00008B);
x11ColorMap.put("darkcyan", 0x008B8B);
x11ColorMap.put("darkgoldenrod", 0xB8860B);
x11ColorMap.put("darkgray", 0xA9A9A9);
x11ColorMap.put("darkgreen", 0x006400);
x11ColorMap.put("darkgrey", 0xA9A9A9);
x11ColorMap.put("darkkhaki", 0xBDB76B);
x11ColorMap.put("darkmagenta", 0x8B008B);
x11ColorMap.put("darkolivegreen", 0x556B2F);
x11ColorMap.put("darkorange", 0xFF8C00);
x11ColorMap.put("darkorchid", 0x9932CC);
x11ColorMap.put("darkred", 0x8B0000);
x11ColorMap.put("darksalmon", 0xE9967A);
x11ColorMap.put("darkseagreen", 0x8FBC8F);
x11ColorMap.put("darkslateblue", 0x483D8B);
x11ColorMap.put("darkslategray", 0x2F4F4F);
x11ColorMap.put("darkslategrey", 0x2F4F4F);
x11ColorMap.put("darkturquoise", 0x00CED1);
x11ColorMap.put("darkviolet", 0x9400D3);
x11ColorMap.put("deeppink", 0xFF1493);
x11ColorMap.put("deepskyblue", 0x00BFFF);
x11ColorMap.put("dimgray", 0x696969);
x11ColorMap.put("dimgrey", 0x696969);
x11ColorMap.put("dodgerblue", 0x1E90FF);
x11ColorMap.put("firebrick", 0xB22222);
x11ColorMap.put("floralwhite", 0xFFFAF0);
x11ColorMap.put("forestgreen", 0x228B22);
x11ColorMap.put("fuchsia", 0xFF00FF);
x11ColorMap.put("gainsboro", 0xDCDCDC);
x11ColorMap.put("ghostwhite", 0xF8F8FF);
x11ColorMap.put("gold", 0xFFD700);
x11ColorMap.put("goldenrod", 0xDAA520);
x11ColorMap.put("gray", 0x808080);
x11ColorMap.put("green", 0x008000);
x11ColorMap.put("greenyellow", 0xADFF2F);
x11ColorMap.put("grey", 0x808080);
x11ColorMap.put("honeydew", 0xF0FFF0);
x11ColorMap.put("hotpink", 0xFF69B4);
x11ColorMap.put("indianred", 0xCD5C5C);
x11ColorMap.put("indigo", 0x4B0082);
x11ColorMap.put("ivory", 0xFFFFF0);
x11ColorMap.put("khaki", 0xF0E68C);
x11ColorMap.put("lavender", 0xE6E6FA);
x11ColorMap.put("lavenderblush", 0xFFF0F5);
x11ColorMap.put("lawngreen", 0x7CFC00);
x11ColorMap.put("lemonchiffon", 0xFFFACD);
x11ColorMap.put("lightblue", 0xADD8E6);
x11ColorMap.put("lightcoral", 0xF08080);
x11ColorMap.put("lightcyan", 0xE0FFFF);
x11ColorMap.put("lightgoldenrodyellow", 0xFAFAD2);
x11ColorMap.put("lightgray", 0xD3D3D3);
x11ColorMap.put("lightgreen", 0x90EE90);
x11ColorMap.put("lightgrey", 0xD3D3D3);
x11ColorMap.put("lightpink", 0xFFB6C1);
x11ColorMap.put("lightsalmon", 0xFFA07A);
x11ColorMap.put("lightseagreen", 0x20B2AA);
x11ColorMap.put("lightskyblue", 0x87CEFA);
x11ColorMap.put("lightslategray", 0x778899);
x11ColorMap.put("lightslategrey", 0x778899);
x11ColorMap.put("lightsteelblue", 0xB0C4DE);
x11ColorMap.put("lightyellow", 0xFFFFE0);
x11ColorMap.put("lime", 0x00FF00);
x11ColorMap.put("limegreen", 0x32CD32);
x11ColorMap.put("linen", 0xFAF0E6);
x11ColorMap.put("magenta", 0xFF00FF);
x11ColorMap.put("maroon", 0x800000);
x11ColorMap.put("mediumaquamarine", 0x66CDAA);
x11ColorMap.put("mediumblue", 0x0000CD);
x11ColorMap.put("mediumorchid", 0xBA55D3);
x11ColorMap.put("mediumpurple", 0x9370DB);
x11ColorMap.put("mediumseagreen", 0x3CB371);
x11ColorMap.put("mediumslateblue", 0x7B68EE);
x11ColorMap.put("mediumspringgreen", 0x00FA9A);
x11ColorMap.put("mediumturquoise", 0x48D1CC);
x11ColorMap.put("mediumvioletred", 0xC71585);
x11ColorMap.put("midnightblue", 0x191970);
x11ColorMap.put("mintcream", 0xF5FFFA);
x11ColorMap.put("mistyrose", 0xFFE4E1);
x11ColorMap.put("moccasin", 0xFFE4B5);
x11ColorMap.put("navajowhite", 0xFFDEAD);
x11ColorMap.put("navy", 0x000080);
x11ColorMap.put("oldlace", 0xFDF5E6);
x11ColorMap.put("olive", 0x808000);
x11ColorMap.put("olivedrab", 0x6B8E23);
x11ColorMap.put("orange", 0xFFA500);
x11ColorMap.put("orangered", 0xFF4500);
x11ColorMap.put("orchid", 0xDA70D6);
x11ColorMap.put("palegoldenrod", 0xEEE8AA);
x11ColorMap.put("palegreen", 0x98FB98);
x11ColorMap.put("paleturquoise", 0xAFEEEE);
x11ColorMap.put("palevioletred", 0xDB7093);
x11ColorMap.put("papayawhip", 0xFFEFD5);
x11ColorMap.put("peachpuff", 0xFFDAB9);
x11ColorMap.put("peru", 0xCD853F);
x11ColorMap.put("pink", 0xFFC0CB);
x11ColorMap.put("plum", 0xDDA0DD);
x11ColorMap.put("powderblue", 0xB0E0E6);
x11ColorMap.put("purple", 0x800080);
x11ColorMap.put("red", 0xFF0000);
x11ColorMap.put("rosybrown", 0xBC8F8F);
x11ColorMap.put("royalblue", 0x4169E1);
x11ColorMap.put("saddlebrown", 0x8B4513);
x11ColorMap.put("salmon", 0xFA8072);
x11ColorMap.put("sandybrown", 0xF4A460);
x11ColorMap.put("seagreen", 0x2E8B57);
x11ColorMap.put("seashell", 0xFFF5EE);
x11ColorMap.put("sienna", 0xA0522D);
x11ColorMap.put("silver", 0xC0C0C0);
x11ColorMap.put("skyblue", 0x87CEEB);
x11ColorMap.put("slateblue", 0x6A5ACD);
x11ColorMap.put("slategray", 0x708090);
x11ColorMap.put("slategrey", 0x708090);
x11ColorMap.put("snow", 0xFFFAFA);
x11ColorMap.put("springgreen", 0x00FF7F);
x11ColorMap.put("steelblue", 0x4682B4);
x11ColorMap.put("tan", 0xD2B48C);
x11ColorMap.put("teal", 0x008080);
x11ColorMap.put("thistle", 0xD8BFD8);
x11ColorMap.put("tomato", 0xFF6347);
x11ColorMap.put("turquoise", 0x40E0D0);
x11ColorMap.put("violet", 0xEE82EE);
x11ColorMap.put("wheat", 0xF5DEB3);
x11ColorMap.put("white", 0xFFFFFF);
x11ColorMap.put("whitesmoke", 0xF5F5F5);
x11ColorMap.put("yellow", 0xFFFF00);
x11ColorMap.put("yellowgreen", 0x9ACD32);
}
2020-10-30 17:10:57 +00:00
private static final List<String> TRACKING_HOSTS = Collections.unmodifiableList(Arrays.asList(
"www.google-analytics.com"
));
static Map<Integer, Integer> MAP_WINGDINGS;
static {
// http://www.alanwood.net/demos/wingdings.html
// https://unicode.org/L2/L2011/11052r-wingding.pdf
Map<Integer, Integer> map = new HashMap<>();
map.put(37, 0x1F514); // Bell
map.put(39, 0x1F56F); // Candle
map.put(44, 0x1F4EA); // Closed mailbox with lowered flag
map.put(45, 0x1F4EB); // Closed mailbox with raised flag
map.put(46, 0x1F4EC); // Open mailbox with raised flag
map.put(47, 0x1F4ED); // Open mailbox with lowered flag
map.put(48, 0x1F4C1); // Folder
map.put(49, 0x1F4C2); // Open folder
map.put(53, 0x1F5C4); // File cabinet
map.put(54, 0x231B); // Hourglass
map.put(57, 0x1F5B2); // Trackball
map.put(58, 0x1F5A5); // Computer
map.put(65, 0x270C); // Victory hand
map.put(66, 0x1F44C); // OK hand
map.put(67, 0x1F44D); // Thumb up
map.put(68, 0x1F44E); // Thumb down
map.put(69, 0x1F448); // Pointing left
map.put(70, 0x1F449); // Pointing right
map.put(71, 0x261D); // Pointing up
map.put(72, 0x1F447); // Pointing down
map.put(73, 0x1F590); // Raised hand
map.put(74, 0x1F642); // Smiling face
map.put(75, 0x1F610); // Neutral face
map.put(76, 0x1F641); // Frowning face
map.put(77, 0x1F4A3); // Bomb
map.put(83, 0x1F4A7); // Droplet
map.put(84, 0x2744); // Snowflake
map.put(94, 0x2648); // Aries
map.put(95, 0x2649); // Taurus
map.put(96, 0x264A); // Gemini
map.put(97, 0x264B); // Cancer
map.put(98, 0x264C); // Leo
map.put(99, 0x264D); // Virgo
map.put(100, 0x264E); // Libra
map.put(101, 0x264F); // Scorpio
map.put(102, 0x2650); // Sagittarius
map.put(103, 0x2651); // Capricorn
map.put(104, 0x2652); // Aquarius
map.put(105, 0x2653); // Pisces
map.put(183, 0x1F550); // Clock 1
map.put(184, 0x1F551); // Clock 2
map.put(185, 0x1F552); // Clock 3
map.put(186, 0x1F553); // Clock 4
map.put(187, 0x1F554); // Clock 5
map.put(188, 0x1F555); // Clock 6
map.put(189, 0x1F556); // Clock 7
map.put(190, 0x1F557); // Clock 8
map.put(191, 0x1F558); // Clock 9
map.put(192, 0x1F559); // Clock 10
map.put(193, 0x1F55A); // Clock 11
map.put(194, 0x1F55B); // Clock 12
map.put(251, 0x274C); // Red cross
map.put(252, 0x2705); // Green check
MAP_WINGDINGS = Collections.unmodifiableMap(map);
}
2020-03-25 19:25:06 +00:00
static Document sanitizeCompose(Context context, String html, boolean show_images) {
2022-11-23 08:08:12 +00:00
return sanitizeCompose(context, JsoupEx.parse(html), show_images);
}
static Document sanitizeCompose(Context context, Document parsed, boolean show_images) {
2020-03-25 19:25:06 +00:00
try {
2022-11-23 08:08:12 +00:00
return sanitize(context, parsed, false, show_images);
2020-03-25 19:25:06 +00:00
} catch (Throwable ex) {
// OutOfMemoryError
Log.e(ex);
Document document = Document.createShell("");
Element strong = document.createElement("strong");
2020-10-15 19:46:15 +00:00
strong.text(android.util.Log.getStackTraceString(ex));
2020-03-25 19:25:06 +00:00
document.body().appendChild(strong);
return document;
}
2020-02-14 08:41:28 +00:00
}
2020-03-25 19:25:06 +00:00
static Document sanitizeView(Context context, Document parsed, boolean show_images) {
2019-10-20 12:15:20 +00:00
try {
2020-03-25 19:25:06 +00:00
return sanitize(context, parsed, true, show_images);
2019-10-20 12:15:20 +00:00
} catch (Throwable ex) {
// OutOfMemoryError
Log.e(ex);
2019-11-22 18:16:02 +00:00
Document document = Document.createShell("");
2019-11-19 20:53:12 +00:00
Element strong = document.createElement("strong");
2020-10-15 19:46:15 +00:00
strong.text(android.util.Log.getStackTraceString(ex));
2019-11-22 18:16:02 +00:00
document.body().appendChild(strong);
2019-11-19 20:53:12 +00:00
return document;
2019-10-20 12:15:20 +00:00
}
}
private static int getMaxFormatTextSize(Context context) {
2022-04-13 20:27:33 +00:00
ActivityManager am = Helper.getSystemService(context, ActivityManager.class);
int mc = am.getMemoryClass();
if (mc >= 256)
return MAX_FORMAT_TEXT_SIZE;
else
return mc * MAX_FORMAT_TEXT_SIZE / 256;
}
2020-03-25 19:25:06 +00:00
private static Document sanitize(Context context, Document parsed, boolean view, boolean show_images) {
2019-10-04 13:25:04 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2021-01-18 10:09:53 +00:00
String theme = prefs.getString("theme", "blue_orange_system");
2021-07-04 09:58:54 +00:00
boolean bw = "black_and_white".equals(theme);
boolean background_color = (!view || (!bw && prefs.getBoolean("background_color", false)));
boolean text_color = (!view || (!bw && prefs.getBoolean("text_color", true)));
boolean text_size = (!view || prefs.getBoolean("text_size", true));
boolean text_font = (!view || prefs.getBoolean("text_font", true));
2020-05-03 17:29:02 +00:00
boolean text_align = prefs.getBoolean("text_align", true);
2022-07-07 07:54:57 +00:00
boolean text_titles = prefs.getBoolean("text_titles", false);
2019-10-16 09:05:38 +00:00
boolean display_hidden = prefs.getBoolean("display_hidden", false);
2019-10-04 13:25:04 +00:00
boolean disable_tracking = prefs.getBoolean("disable_tracking", true);
2020-11-09 11:49:04 +00:00
boolean parse_classes = prefs.getBoolean("parse_classes", true);
2020-09-11 14:52:11 +00:00
boolean inline_images = prefs.getBoolean("inline_images", false);
2020-11-16 08:58:19 +00:00
boolean text_separators = prefs.getBoolean("text_separators", true);
boolean image_placeholders = prefs.getBoolean("image_placeholders", true);
2019-10-04 13:25:04 +00:00
2021-07-05 04:55:24 +00:00
boolean dark = Helper.isDarkTheme(context);
int textColorPrimary = Helper.resolveColor(context, android.R.attr.textColorPrimary);
int textColorPrimaryInverse = Helper.resolveColor(context, android.R.attr.textColorPrimaryInverse);
2021-08-04 15:19:43 +00:00
int textSizeSmall;
TypedArray ta = context.obtainStyledAttributes(
R.style.TextAppearance_AppCompat_Small, new int[]{android.R.attr.textSize});
if (ta == null)
textSizeSmall = Helper.dp2pixels(context, 6);
else {
textSizeSmall = ta.getDimensionPixelSize(0, 0);
ta.recycle();
}
2020-02-09 14:04:35 +00:00
// https://chromium.googlesource.com/chromium/blink/+/master/Source/core/css/html.css
2019-05-13 09:03:15 +00:00
2020-02-02 12:03:06 +00:00
// <!--[if ...]><!--> ... <!--<![endif]-->
2020-02-04 09:10:36 +00:00
// https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/hh801214(v=vs.85)
if (!display_hidden && false)
2020-02-02 12:03:06 +00:00
parsed.filter(new NodeFilter() {
private boolean remove = false;
@Override
public FilterResult head(Node node, int depth) {
if (node instanceof Comment) {
String data = ((Comment) node).getData().trim();
if (data.startsWith("[if") && !data.endsWith("endif]")) {
remove = true;
return FilterResult.REMOVE;
} else if (remove && data.endsWith("endif]")) {
remove = false;
return FilterResult.REMOVE;
}
}
return (remove ? FilterResult.REMOVE : FilterResult.CONTINUE);
}
@Override
public FilterResult tail(Node node, int depth) {
return FilterResult.CONTINUE;
}
});
2020-12-29 08:04:29 +00:00
// Fix Microsoft namespaces
normalizeNamespaces(parsed, display_hidden);
2019-05-13 09:03:15 +00:00
2020-02-14 08:04:16 +00:00
// Limit length
if (view && truncate(parsed, getMaxFormatTextSize(context))) {
2020-02-14 08:04:16 +00:00
parsed.body()
.appendElement("p")
.appendElement("em")
.text(context.getString(R.string.title_too_large));
2020-03-25 19:25:06 +00:00
parsed.body()
.appendElement("p")
.appendElement("big")
.appendElement("a")
.attr("href", "full:")
.text(context.getString(R.string.title_show_full));
2020-02-14 08:04:16 +00:00
}
2020-04-20 13:01:05 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style
2020-04-21 07:04:55 +00:00
List<CSSStyleSheet> sheets = new ArrayList<>();
2020-04-22 10:10:30 +00:00
if (parse_classes)
2020-07-16 20:06:52 +00:00
sheets = parseStyles(parsed.head().select("style"));
2020-04-20 13:01:05 +00:00
2021-09-11 18:44:55 +00:00
Safelist safelist = Safelist.relaxed()
2022-04-04 06:23:20 +00:00
.addTags("hr", "abbr", "big", "font", "dfn", "del", "s", "tt", "mark")
2020-04-20 13:01:05 +00:00
.addAttributes(":all", "class")
.addAttributes(":all", "style")
2021-04-23 18:25:15 +00:00
.addAttributes("span", "dir")
2021-05-08 19:48:39 +00:00
.addAttributes("li", "dir")
2020-05-05 16:43:37 +00:00
.addAttributes("div", "x-plain")
2020-11-07 15:44:33 +00:00
.removeTags("col", "colgroup")
2020-11-09 16:30:33 +00:00
.removeTags("thead", "tbody", "tfoot")
2020-11-09 18:45:57 +00:00
.addAttributes("td", "width")
.addAttributes("td", "height")
.addAttributes("tr", "width")
.addAttributes("tr", "height")
2022-07-07 07:54:57 +00:00
.addAttributes(":all", "title")
.addAttributes("blockquote", "type")
2020-11-09 18:45:57 +00:00
.removeAttributes("td", "colspan", "rowspan", "width")
.removeAttributes("th", "colspan", "rowspan", "width")
2018-12-14 09:05:48 +00:00
.addProtocols("img", "src", "cid")
2020-02-14 08:04:16 +00:00
.addProtocols("img", "src", "data")
2021-03-05 12:48:16 +00:00
.removeTags("a").addAttributes("a", "href", "title");
2019-09-23 18:13:38 +00:00
if (text_color)
2021-09-11 18:44:55 +00:00
safelist.addAttributes("font", "color");
2020-06-28 13:59:02 +00:00
if (text_size)
2021-09-11 18:44:55 +00:00
safelist.addAttributes("font", "size");
2020-06-28 13:59:02 +00:00
if (text_font)
2021-09-11 18:44:55 +00:00
safelist.addAttributes("font", "face");
2020-05-03 17:29:02 +00:00
if (text_align)
2021-09-11 18:44:55 +00:00
safelist.addTags("center").addAttributes(":all", "align");
2020-04-27 07:40:43 +00:00
if (!view)
2021-09-11 18:44:55 +00:00
safelist.addProtocols("img", "src", "content");
2019-09-23 18:13:38 +00:00
2021-09-11 18:44:55 +00:00
final Document document = new Cleaner(safelist).clean(parsed);
2018-11-24 11:27:44 +00:00
2020-09-12 07:09:07 +00:00
// Remove tracking pixels
if (disable_tracking)
2020-11-16 17:53:56 +00:00
removeTrackingPixels(context, document);
2020-09-12 07:09:07 +00:00
2022-04-04 06:23:38 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font
2019-09-25 10:48:02 +00:00
for (Element font : document.select("font")) {
2020-04-26 16:43:20 +00:00
String style = font.attr("style");
2021-04-19 19:23:54 +00:00
String color = font.attr("color").trim();
String size = font.attr("size").trim();
String face = font.attr("face").trim();
2020-04-20 07:57:42 +00:00
2020-04-26 16:43:20 +00:00
style = style.trim();
if (!TextUtils.isEmpty(style) && !style.endsWith(";"))
style += ";";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
font.removeAttr("color");
2020-04-20 07:57:42 +00:00
font.removeAttr("size");
2020-06-28 13:59:02 +00:00
font.removeAttr("face");
2020-04-20 07:57:42 +00:00
2020-04-26 16:43:20 +00:00
StringBuilder sb = new StringBuilder(style);
2020-04-20 07:57:42 +00:00
if (!TextUtils.isEmpty(color))
sb.append("color:").append(color).append(";");
2021-04-20 18:17:00 +00:00
if (!TextUtils.isEmpty(size))
2020-04-20 07:57:42 +00:00
try {
2021-04-20 18:17:00 +00:00
int s = Integer.parseInt(size);
if (size.startsWith("-")) {
if (s < 0)
size = "smaller";
2021-04-21 05:32:56 +00:00
else
throw new NumberFormatException("size=" + size);
2021-04-20 18:17:00 +00:00
} else if (size.startsWith("+")) {
if (s > 0)
size = "larger";
2021-04-21 05:32:56 +00:00
else
throw new NumberFormatException("size=" + size);
2022-10-16 10:01:34 +00:00
} else {
if (s < 2)
size = "x-small";
else if (s < 3)
size = "small";
else if (s > 4)
size = "x-large";
else if (s > 3)
size = "large";
else
size = "medium";
}
2020-04-20 07:57:42 +00:00
sb.append("font-size:").append(size).append(";");
} catch (NumberFormatException ex) {
2020-05-28 06:48:28 +00:00
Log.i(ex);
2020-04-20 07:57:42 +00:00
}
2021-04-20 06:01:03 +00:00
if (!TextUtils.isEmpty(face)) {
sb.append("font-family:");
String[] faces = face.split(",");
for (int i = 0; i < faces.length; i++) {
if (i > 0)
sb.append(',');
String f = faces[i].trim();
if (f.contains(" ") && !f.startsWith("\"") && !f.endsWith("\""))
sb.append('"').append(f).append('"');
else
sb.append(f);
}
sb.append(";");
}
2020-06-28 13:59:02 +00:00
2020-04-20 07:57:42 +00:00
font.attr("style", sb.toString());
2019-09-25 10:48:02 +00:00
font.tagName("span");
}
2019-10-16 09:05:38 +00:00
// Sanitize styles
for (Element element : document.select("*")) {
2020-04-22 14:32:35 +00:00
// Class style
2020-07-16 20:25:16 +00:00
String tag = element.tagName();
2020-11-08 17:14:42 +00:00
String clazz = element.className();
2020-07-16 20:25:16 +00:00
String style = processStyles(tag, clazz, null, sheets);
2020-04-20 13:01:05 +00:00
2020-04-22 14:32:35 +00:00
// Element style
2022-03-08 18:42:54 +00:00
style = mergeElementStyles(style, element.attr("style"));
2020-04-20 13:01:05 +00:00
2021-08-15 19:28:33 +00:00
if ("fairemail_debug_info".equals(clazz))
style = mergeStyles(style, "font-size: smaller");
2020-05-03 17:29:02 +00:00
if (text_align) {
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center
if ("center".equals(element.tagName())) {
style = mergeStyles(style, "text-align:center");
element.tagName("div");
2020-05-05 11:30:48 +00:00
} else if ("table".equals(element.tagName()))
style = mergeStyles(style, "text-align:left");
else {
// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
String align = element.attr("align");
if (!TextUtils.isEmpty(align))
style = mergeStyles(style, "text-align:" + align);
2020-05-03 17:29:02 +00:00
}
}
2020-04-20 13:01:05 +00:00
// Process style
2019-09-23 17:51:17 +00:00
if (!TextUtils.isEmpty(style)) {
2021-04-23 18:25:15 +00:00
boolean block = false;
2019-09-23 17:51:17 +00:00
StringBuilder sb = new StringBuilder();
2021-04-24 05:36:23 +00:00
if (!view &&
"span".equals(element.tagName()) &&
2021-04-23 18:25:15 +00:00
"rtl".equals(element.attr("dir")))
block = true;
2019-09-23 17:51:17 +00:00
2021-04-21 15:35:04 +00:00
Map<String, String> kv = new LinkedHashMap<>();
2019-09-23 17:51:17 +00:00
String[] params = style.split(";");
for (String param : params) {
2020-04-20 13:01:05 +00:00
int colon = param.indexOf(':');
2021-04-21 15:35:04 +00:00
if (colon <= 0)
continue;
2021-07-08 17:09:43 +00:00
String key = param.substring(0, colon)
.trim()
.toLowerCase(Locale.ROOT);
String value = param.substring(colon + 1)
2021-04-21 15:35:04 +00:00
.trim()
2021-07-08 17:09:43 +00:00
.toLowerCase(Locale.ROOT)
.replace("!important", "")
2021-04-21 15:35:04 +00:00
.replaceAll("\\s+", " ");
kv.put(key, value);
}
2021-07-05 13:58:43 +00:00
List<String> keys = new ArrayList<>(kv.keySet());
Collections.sort(keys); // background-color first
for (String key : keys) {
2021-04-21 15:35:04 +00:00
String value = kv.get(key);
switch (key) {
2022-03-29 19:59:25 +00:00
case "background-image":
// https://developer.mozilla.org/en-US/docs/Web/CSS/background-image
String url = value.replace(" ", "");
int us = url.indexOf("url(");
int ue = url.indexOf(')', us + 4);
if (us >= 0 && ue > us) {
url = url.substring(us + 4, ue);
if ((url.startsWith("'") && url.endsWith("'")) ||
(url.startsWith("\"") && url.endsWith("\"")))
url = url.substring(1, url.length() - 1);
Element img = document.createElement("img")
.attr("src", url);
element.prependElement("br");
element.prependChild(img);
}
break;
2021-04-21 15:35:04 +00:00
case "color":
case "background":
2021-07-04 09:58:54 +00:00
case "background-color":
2021-04-21 15:35:04 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/color
// https://developer.mozilla.org/en-US/docs/Web/CSS/background
// https://developer.mozilla.org/en-US/docs/Web/CSS/background-color
if ("color".equals(key)) {
if (!text_color)
continue;
} else {
if (!background_color)
continue;
}
2021-04-21 15:35:04 +00:00
Integer color = parseColor(value);
2022-03-03 17:00:34 +00:00
if (color != null && color == Color.TRANSPARENT) {
2022-03-08 12:16:11 +00:00
if ("color".equals(key) && BuildConfig.DEBUG)
if (display_hidden)
2022-03-03 17:19:06 +00:00
sb.append("text-decoration:line-through;");
else if (false) {
Log.i("Removing color transparent " + element.tagName());
element.remove();
continue;
}
2022-03-03 17:00:34 +00:00
color = null;
}
2021-07-05 13:58:43 +00:00
if ("color".equals(key)) {
2021-08-04 06:10:39 +00:00
Integer bg = null;
2021-07-06 07:04:02 +00:00
if (background_color) {
Element e = element;
2021-08-04 06:10:39 +00:00
while (e != null && bg == null)
2021-07-06 07:04:02 +00:00
if (e.hasAttr("x-background"))
2021-08-04 06:10:39 +00:00
bg = parseWebColor(e.attr("x-background"));
2021-07-06 07:04:02 +00:00
else
e = e.parent();
}
if (!view &&
color != null && (bg == null || bg == Color.TRANSPARENT)) {
2021-07-05 14:35:47 +00:00
// Special case:
// external draft: very dark/light font
double lum = ColorUtils.calculateLuminance(color);
2023-01-01 18:37:52 +00:00
if (lum < 1 - MIN_LUMINANCE_COMPOSE || lum > MIN_LUMINANCE_COMPOSE)
color = null;
}
2021-07-05 13:58:43 +00:00
if (bg == null) {
2021-07-05 13:58:43 +00:00
if (color != null && view)
color = adjustColor(dark, textColorPrimary, color);
2021-08-04 07:37:33 +00:00
} else if (bg == Color.TRANSPARENT) {
// Background color was suppressed because "no color"
2021-08-04 06:10:39 +00:00
if (color != null) {
2021-08-04 07:37:33 +00:00
double lum = ColorUtils.calculateLuminance(color);
2022-08-02 13:17:01 +00:00
if (dark ? lum < 1 - MIN_LUMINANCE_VIEW : lum > MIN_LUMINANCE_VIEW)
2021-08-04 07:37:33 +00:00
color = textColorPrimary;
2021-08-04 06:10:39 +00:00
}
2021-07-05 13:58:43 +00:00
}
2021-07-05 14:55:31 +00:00
if (color != null)
element.attr("x-color", "true");
} else /* background */ {
2021-08-04 06:10:39 +00:00
if (color != null && !hasColor(color))
2021-08-04 07:37:33 +00:00
color = Color.TRANSPARENT;
2021-07-05 13:58:43 +00:00
2021-07-05 14:55:31 +00:00
if (color != null)
2021-08-04 06:10:39 +00:00
element.attr("x-background", encodeWebColor(color));
2021-07-05 14:55:31 +00:00
2021-08-04 07:42:41 +00:00
if (color != null && dark) {
2021-07-06 07:04:02 +00:00
boolean fg = false;
if (text_color) {
fg = (parseColor(kv.get("color")) != null);
Element e = element;
while (e != null && !fg)
if (e.hasAttr("x-color"))
fg = true;
else
e = e.parent();
}
2021-07-05 14:55:31 +00:00
2021-07-06 07:04:02 +00:00
// Dark theme, background color with no text color:
2021-08-04 07:42:41 +00:00
// force (inverse) text color
if (!fg) {
double lum = (color == Color.TRANSPARENT ? 0 : ColorUtils.calculateLuminance(color));
int c = (lum < 0.5 ? textColorPrimary : textColorPrimaryInverse);
2021-07-05 14:55:31 +00:00
sb.append("color")
.append(':')
2021-08-04 07:42:41 +00:00
.append(encodeWebColor(c))
2021-07-05 14:55:31 +00:00
.append(";");
2021-08-04 07:42:41 +00:00
}
2021-07-05 13:58:43 +00:00
}
}
2021-07-04 09:58:54 +00:00
if (color == null) {
2021-07-04 09:58:54 +00:00
element.removeAttr(key);
continue;
2021-04-21 15:35:04 +00:00
}
2021-07-05 14:55:31 +00:00
String c = encodeWebColor(color);
2021-07-04 09:58:54 +00:00
sb.append(key).append(':').append(c).append(";");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
element.attr(key, c);
2021-04-21 15:35:04 +00:00
break;
case "font-size":
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-size
if (!text_size)
continue;
float current;
if (tag.length() == 2 &&
tag.charAt(0) == 'h' &&
Character.isDigit(tag.charAt(1)))
current = HEADING_SIZES[tag.charAt(1) - '1'];
else
current = 1.0f;
Element parent = element.parent();
while (parent != null) {
String xFontSize = parent.attr("x-font-size");
if (!TextUtils.isEmpty(xFontSize)) {
current = Float.parseFloat(xFontSize);
break;
}
2021-04-21 15:35:04 +00:00
parent = parent.parent();
}
Float fsize = getFontSize(value, current);
2022-03-03 16:55:45 +00:00
if (fsize != null)
if (fsize == 0) {
2022-03-08 12:16:11 +00:00
if (BuildConfig.DEBUG)
2022-03-09 10:23:19 +00:00
if (display_hidden && false)
2022-03-08 12:16:11 +00:00
sb.append("text-decoration:line-through;");
else if (false) {
Log.i("Removing font size zero " + element.tagName());
element.remove();
}
2022-03-03 16:55:45 +00:00
} else {
if (!view) {
if (fsize < 1)
2022-08-27 15:48:36 +00:00
fsize = (fsize < FONT_SMALL ? FONT_XSMALL : FONT_SMALL);
2022-03-03 16:55:45 +00:00
else if (fsize > 1)
2022-08-27 15:48:36 +00:00
fsize = (fsize > FONT_LARGE ? FONT_XLARGE : FONT_LARGE);
2022-03-03 16:55:45 +00:00
}
element.attr("x-font-size", Float.toString(fsize));
element.attr("x-font-size-rel", Float.toString(fsize / current));
}
2021-04-21 15:35:04 +00:00
break;
case "font-weight":
if (element.parent() != null) {
Integer fweight = getFontWeight(value);
if (fweight != null && fweight >= 600) {
Element strong = new Element("strong");
for (Node child : new ArrayList<>(element.childNodes())) {
child.remove();
strong.appendChild(child);
2020-02-10 08:29:47 +00:00
}
2021-04-21 15:35:04 +00:00
element.appendChild(strong);
2020-02-08 19:39:51 +00:00
}
2021-04-21 15:35:04 +00:00
}
break;
case "font-family":
if (!text_font)
continue;
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-family
sb.append(key).append(":").append(value).append(";");
break;
2022-04-04 12:49:23 +00:00
case "font-style":
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-style
if (value.contains("italic") || value.contains("oblique"))
sb.append(key).append(":").append("italic").append(";");
break;
2021-04-21 15:35:04 +00:00
case "text-decoration":
2022-03-03 14:26:25 +00:00
case "text-decoration-line":
2021-04-21 15:35:04 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration
2022-03-03 14:26:25 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-line
2021-04-21 15:35:04 +00:00
if (value.contains("line-through"))
sb.append("text-decoration:line-through;");
2022-03-03 14:26:25 +00:00
else if (value.contains("underline"))
sb.append("text-decoration:underline;");
2021-04-21 15:35:04 +00:00
break;
2022-02-06 19:33:44 +00:00
case "text-transform":
// https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform
NodeTraversor.traverse(new NodeVisitor() {
@Override
public void head(Node node, int depth) {
if (node instanceof TextNode) {
TextNode tnode = (TextNode) node;
String text = tnode.getWholeText();
switch (value) {
case "capitalize":
// TODO: capitalize
break;
case "uppercase":
tnode.text(text.toUpperCase(Locale.ROOT));
break;
case "lowercase":
tnode.text(text.toLowerCase(Locale.ROOT));
break;
}
}
}
@Override
public void tail(Node node, int depth) {
// Do nothing
}
}, element);
break;
2021-04-21 15:35:04 +00:00
case "display":
// https://developer.mozilla.org/en-US/docs/Web/CSS/display
2022-03-03 17:19:06 +00:00
if (element.parent() != null && "none".equals(value)) {
if (display_hidden)
sb.append("text-decoration:line-through;");
else {
Log.i("Removing display none " + element.tagName());
element.remove();
}
2021-04-21 15:35:04 +00:00
}
if ("block".equals(value) || "inline-block".equals(value))
element.attr("x-block", "true");
if ("inline".equals(value) || "inline-block".equals(value)) {
if (element.nextSibling() != null)
element.attr("x-inline", "true");
}
break;
2021-10-16 16:46:48 +00:00
/*
2021-04-21 15:35:04 +00:00
case "height":
case "width":
//case "font-size":
//case "line-height":
if (element.parent() != null && !display_hidden) {
Float s = getFontSize(value, 1.0f);
if (s != null && s == 0) {
2021-05-30 19:25:12 +00:00
if (!"table".equals(element.tagName())) {
2020-02-10 18:55:52 +00:00
Log.i("Removing no height/width " + element.tagName());
element.remove();
}
}
2021-04-21 15:35:04 +00:00
}
break;
2021-10-16 16:46:48 +00:00
*/
2021-04-21 15:35:04 +00:00
case "margin":
case "padding":
case "margin-top":
case "margin-bottom":
case "padding-top":
case "padding-bottom":
// https://developer.mozilla.org/en-US/docs/Web/CSS/margin
// https://developer.mozilla.org/en-US/docs/Web/CSS/padding
if (element.isBlock()) {
Float[] p = new Float[4];
String[] v = value.split(" ");
for (int i = 0; i < v.length && i < p.length; i++)
p[i] = getFontSize(v[i], 1.0f);
if (v.length == 1) {
p[1] = p[0];
p[2] = p[0];
p[3] = p[0];
} else if (v.length == 2) {
p[2] = p[0];
p[3] = p[1];
2020-10-03 12:04:06 +00:00
}
2021-04-21 15:35:04 +00:00
if (key.endsWith("top"))
p[2] = null;
else if (key.endsWith("bottom"))
p[0] = null;
if (p[0] != null)
if (p[0] == 0)
element.attr("x-line-before", "false");
else if (p[0] > 0.5)
element.attr("x-line-before", "true");
if (p[2] != null)
if (p[2] == 0)
element.attr("x-line-after", "false");
else if (p[2] > 0.5)
element.attr("x-line-after", "true");
}
break;
case "text-align":
// https://developer.mozilla.org/en-US/docs/Web/CSS/text-align
if (text_align) {
2021-04-24 05:36:23 +00:00
if (!element.isBlock())
block = true;
2021-04-21 15:35:04 +00:00
element.attr("x-align", value);
sb.append(key).append(':').append(value).append(';');
}
break;
2021-07-07 13:12:35 +00:00
case "border-left":
case "border-right":
if (value != null) {
// 1px solid rgb(204,204,204)
Float border = getFontSize(value.trim().split("\\s+")[0], 1.0f);
2021-07-07 14:39:04 +00:00
if (border != null && border > 0) {
2021-07-07 13:12:35 +00:00
element.attr("x-border", "true");
2021-07-07 14:39:04 +00:00
if (!view) {
sb.append("border-left").append(':').append("3px solid #ccc").append(';');
sb.append("padding-left").append(':').append("3px").append(';');
}
}
2021-07-07 13:12:35 +00:00
}
break;
2021-07-08 06:16:30 +00:00
case "list-style-type":
2021-07-08 12:11:20 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type
2021-07-08 06:16:30 +00:00
element.attr("x-list-style", value);
2021-07-09 08:38:48 +00:00
if (!view)
sb.append(key).append(':').append(value).append(';');
2021-07-08 06:16:30 +00:00
break;
2022-04-04 14:54:13 +00:00
case "visibility":
// https://developer.mozilla.org/en-US/docs/Web/CSS/visibility
if (element.parent() != null &&
("hidden".equals(value) || "collapse".equals(value)))
if (display_hidden)
sb.append("text-decoration:line-through;");
else
sb.append(key).append(':').append("hidden").append(';');
break;
2019-10-16 09:05:38 +00:00
}
2019-09-23 17:51:17 +00:00
}
2021-04-24 05:36:23 +00:00
if (block) {
2021-04-23 18:25:15 +00:00
sb.append("display:block;");
2021-04-24 05:36:23 +00:00
Element next = element.nextElementSibling();
if (next != null && "br".equals(next.tagName()))
next.remove();
}
2021-04-23 18:25:15 +00:00
2019-09-25 16:05:13 +00:00
if (sb.length() == 0)
2019-10-16 09:05:38 +00:00
element.removeAttr("style");
2020-01-31 12:52:57 +00:00
else {
2019-10-16 09:05:38 +00:00
element.attr("style", sb.toString());
2020-01-31 12:52:57 +00:00
if (BuildConfig.DEBUG)
Log.i("Style=" + sb);
}
2019-09-23 17:51:17 +00:00
}
2020-11-02 08:34:43 +00:00
2020-11-06 18:39:31 +00:00
if (element.isBlock() &&
!"true".equals(element.attr("x-inline")))
2020-11-02 08:34:43 +00:00
element.attr("x-block", "true");
2019-09-23 17:51:17 +00:00
}
2022-07-07 07:54:57 +00:00
// Insert titles
if (text_titles)
for (Element e : document.select("[title]")) {
String title = e.attr("title");
2022-07-08 05:21:09 +00:00
if (TextUtils.isEmpty(title))
continue;
if ("img".equals(e.tagName()) &&
title.equals(e.attr("alt")))
continue;
e.prependChild(document.createElement("span").text("{" + title + "}"));
2022-07-07 07:54:57 +00:00
}
2020-02-24 19:34:16 +00:00
// Replace headings
2020-11-11 15:58:38 +00:00
Elements hs = document.select("h1,h2,h3,h4,h5,h6");
2020-11-17 11:26:43 +00:00
hs.attr("x-line-before", "true");
2020-11-11 15:58:38 +00:00
if (text_size) {
if (text_separators && view)
for (Element h : hs)
h.appendElement("hr")
.attr("x-block", "true");
else
hs.attr("x-line-after", "true");
2020-11-12 11:46:25 +00:00
} else {
2020-11-11 15:58:38 +00:00
hs.tagName("strong");
2020-11-12 11:46:25 +00:00
hs.attr("x-line-after", "true");
}
2019-09-12 08:45:54 +00:00
// Paragraphs
2019-11-11 10:32:47 +00:00
for (Element p : document.select("p")) {
2019-09-12 08:45:54 +00:00
p.tagName("div");
2020-11-08 18:46:46 +00:00
if (p.childNodeSize() != 0) {
if (p.childNodeSize() == 1) {
Node lonely = p.childNode(0);
if (lonely instanceof TextNode &&
"\u00a0".equals(((TextNode) lonely).getWholeText()))
continue;
}
p.attr("x-paragraph", "true");
}
2019-11-11 10:32:47 +00:00
}
2019-09-12 08:45:54 +00:00
// Short inline quotes
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q
2019-03-10 15:21:46 +00:00
for (Element q : document.select("q")) {
q.tagName("a");
2021-09-23 15:38:54 +00:00
String cite = q.attr("cite");
if (!TextUtils.isEmpty(cite) && !cite.trim().startsWith("#"))
q.attr("href", cite);
q.removeAttr("cite");
2019-03-10 15:21:46 +00:00
}
// Citation
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite
for (Element cite : document.select("cite")) {
cite.prependText("\"");
cite.appendText("\"");
cite.tagName("em");
}
// Definition
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dfn
for (Element dfn : document.select("dfn"))
dfn.tagName("em");
2019-03-10 15:21:46 +00:00
// Pre formatted text
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
2020-05-02 15:51:15 +00:00
for (Element pre : document.select("pre")) {
2021-12-25 09:28:04 +00:00
NodeTraversor.traverse(new NodeVisitor() {
private int index = 0;
private boolean inElement = false;
@Override
public void head(Node node, int depth) {
if (node instanceof Element)
inElement = true;
else if (node instanceof TextNode) {
if (inElement) {
TextNode tnode = (TextNode) node;
StringBuilder sb = new StringBuilder();
for (Character c : tnode.getWholeText().toCharArray()) {
if (c == '\t')
do {
index++;
sb.append(' ');
}
while ((index % TAB_SIZE) != 0);
else {
if (c == '\n')
index = 0;
else
index++;
sb.append(c);
}
}
tnode.text(sb.toString());
}
}
}
@Override
public void tail(Node node, int depth) {
if (node instanceof Element)
inElement = false;
}
}, pre);
2020-05-02 15:51:15 +00:00
pre.tagName("div");
2020-05-05 16:43:37 +00:00
pre.attr("x-plain", "true");
2020-05-02 15:51:15 +00:00
}
2019-03-10 11:14:39 +00:00
2019-03-10 15:21:46 +00:00
// Code
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code
2019-09-21 16:10:41 +00:00
document.select("code").tagName("strong");
2019-03-10 15:21:46 +00:00
// Lines
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr
2022-02-04 09:24:30 +00:00
for (Element hr : document.select("hr"))
hr.attr("x-keep-line", "true");
2019-02-10 12:01:21 +00:00
2019-03-10 15:21:46 +00:00
// Descriptions
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl
2019-03-10 15:21:46 +00:00
document.select("dl").tagName("div");
2020-11-06 18:39:31 +00:00
for (Element dt : document.select("dt"))
2019-03-11 08:27:56 +00:00
dt.tagName("strong");
for (Element dd : document.select("dd")) {
dd.tagName("em");
2020-11-06 18:39:31 +00:00
dd.attr("x-line-after", "true");
2019-03-11 08:27:56 +00:00
}
2018-11-24 11:27:44 +00:00
2019-03-12 12:13:53 +00:00
// Abbreviations
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/abbr
2019-03-12 12:13:53 +00:00
document.select("abbr").tagName("u");
2019-03-30 16:48:04 +00:00
// Tables
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
2020-11-09 16:30:33 +00:00
for (Element table : document.select("table")) {
table.tagName("div");
2020-11-09 18:45:57 +00:00
// Ignore summary attribute
2020-11-09 16:30:33 +00:00
for (Element row : table.children()) {
row.tagName("div");
2021-07-04 19:22:40 +00:00
Element separate = null;
2020-11-09 21:42:09 +00:00
List<Node> merge = new ArrayList<>();
2020-11-09 16:30:33 +00:00
for (Element col : row.children()) {
2020-11-09 21:42:09 +00:00
Element next = col.nextElementSibling();
2020-11-10 08:57:08 +00:00
2020-11-11 09:47:08 +00:00
// Get nodes with content
List<Node> nodes = new ArrayList<>(col.childNodes());
while (nodes.size() > 0) {
Node first = nodes.get(0);
if (first instanceof TextNode && ((TextNode) first).isBlank()) {
nodes.remove(0);
continue;
}
Node last = nodes.get(nodes.size() - 1);
if (last instanceof TextNode && ((TextNode) last).isBlank()) {
nodes.remove(nodes.size() - 1);
continue;
}
break;
}
2020-11-10 08:57:08 +00:00
// Merge single images into next column
2020-11-11 09:47:08 +00:00
if (nodes.size() == 1) {
Node lonely = nodes.get(0);
// prevent extra newlines
lonely.removeAttr("x-paragraph");
if (next == null ||
next.attr("x-align")
.equals(col.attr("x-align"))) {
if (lonely instanceof Element &&
"img".equals(lonely.nodeName())) {
lonely.remove();
lonely.removeAttr("x-block");
merge.add(lonely);
if (next != null)
continue;
}
2020-11-09 21:42:09 +00:00
}
2020-11-14 19:09:06 +00:00
if (lonely instanceof TextNode &&
"\u00a0".equals(((TextNode) lonely).getWholeText()))
lonely.remove(); // -> column separator
2020-11-09 21:42:09 +00:00
}
if (merge.size() > 0) {
for (int m = merge.size() - 1; m >= 0; m--)
col.prependChild(merge.get(m));
merge.clear();
}
2020-11-09 16:30:33 +00:00
if ("th".equals(col.tagName())) {
Element strong = new Element("strong");
for (Node child : new ArrayList<>(col.childNodes())) {
child.remove();
strong.appendChild(child);
2020-11-07 09:34:34 +00:00
}
2020-11-09 16:30:33 +00:00
col.appendChild(strong);
2020-11-07 09:34:34 +00:00
}
2019-06-18 19:56:34 +00:00
2020-11-10 08:57:08 +00:00
// Flow not / left aligned columns
2020-11-09 16:30:33 +00:00
String align = col.attr("x-align");
2020-11-17 11:38:03 +00:00
//if (next == null && row.childrenSize() == 2) {
// align = "end";
// String style = col.attr("style");
// col.attr("style",
// mergeStyles(style, "text-align:" + align));
//}
2020-11-09 16:30:33 +00:00
if (TextUtils.isEmpty(align) ||
"left".equals(align) ||
2021-07-04 19:22:40 +00:00
"start".equals(align)) {
2020-11-15 08:09:51 +00:00
col.removeAttr("x-block");
2021-07-04 19:22:40 +00:00
if (separate != null)
separate.attr("x-column", "true");
separate = col;
} else {
separate = null;
2020-11-11 12:40:09 +00:00
if ("true".equals(col.attr("x-line-before")))
col.removeAttr("x-line-before");
}
2020-11-07 15:44:33 +00:00
2021-07-04 19:22:40 +00:00
col.tagName("div");
2020-11-07 15:44:33 +00:00
}
2020-11-09 21:42:09 +00:00
if (merge.size() != 0)
throw new AssertionError("merge");
2020-11-09 16:30:33 +00:00
if (text_separators && view)
row.appendElement("hr")
.attr("x-block", "true")
.attr("x-dashed", "true");
2020-11-07 09:34:34 +00:00
}
2020-11-09 16:30:33 +00:00
}
2019-03-30 16:48:04 +00:00
2020-11-08 12:01:47 +00:00
// Fix dangling table elements
2020-11-09 16:30:33 +00:00
document.select("tr,th,td").tagName("div");
2020-11-08 12:01:47 +00:00
2020-11-17 13:33:55 +00:00
// Lists
2020-11-20 14:31:27 +00:00
for (Element e : document.select("ol,ul,blockquote")) {
2022-05-22 07:33:27 +00:00
Element parent = e.parent();
2020-11-17 13:33:55 +00:00
if (view) {
2021-05-05 13:40:10 +00:00
if ("blockquote".equals(e.tagName()) || parent == null ||
2022-05-20 13:28:28 +00:00
!("li".equals(parent.tagName()) ||
"ol".equals(parent.tagName()) ||
"ul".equals(parent.tagName()))) {
2021-05-05 13:40:10 +00:00
if (!"false".equals(e.attr("x-line-before")))
e.attr("x-line-before", "true");
if (!"false".equals(e.attr("x-line-after")))
e.attr("x-line-after", "true");
}
2022-05-22 07:47:31 +00:00
// Unflatten list for viewing
if ((parent != null && "li".equals(parent.tagName())) &&
("ol".equals(e.tagName()) || "ul".equals(e.tagName())))
2022-05-21 12:33:45 +00:00
e.attr("x-list-level", "false");
2020-11-17 13:33:55 +00:00
} else {
2022-01-07 15:56:19 +00:00
if (!BuildConfig.DEBUG) {
String style = e.attr("style");
e.attr("style",
mergeStyles(style, "margin-top:0;margin-bottom:0"));
int ltr = 0;
int rtl = 0;
for (Element li : e.children()) {
if ("rtl".equals(li.attr("dir")))
rtl++;
else
ltr++;
li.removeAttr("dir");
}
e.attr("dir", rtl > ltr ? "rtl" : "ltr");
2021-05-08 19:48:39 +00:00
}
2022-05-22 07:33:27 +00:00
// Flatten list for editor
if (parent != null && "li".equals(parent.tagName())) {
List<Node> children = parent.childNodes();
for (Node child : children) {
child.remove();
if (child instanceof Element &&
"ol".equals(child.nodeName()) || "ul".equals(child.nodeName()))
parent.before(child);
else
2022-05-23 07:12:15 +00:00
parent.before(parent.shallowClone().appendChild(child));
2022-05-22 07:33:27 +00:00
}
parent.remove();
}
2020-11-17 13:33:55 +00:00
}
}
2019-09-13 11:46:52 +00:00
// Images
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
for (Element img : document.select("img")) {
2019-10-14 06:50:27 +00:00
String alt = img.attr("alt");
String src = img.attr("src");
2020-05-05 16:49:55 +00:00
String tracking = img.attr("x-tracking");
2020-11-16 21:10:48 +00:00
boolean isInline = src.startsWith("cid:");
2019-10-14 06:50:27 +00:00
2020-11-15 19:37:27 +00:00
if (TextUtils.isEmpty(src)) {
2020-11-16 17:53:56 +00:00
Log.i("Removing empty image");
2020-11-15 19:37:27 +00:00
img.remove();
continue;
}
2020-11-16 17:53:56 +00:00
2020-11-16 21:10:48 +00:00
if (!show_images && !(inline_images && isInline) && !image_placeholders) {
2020-11-16 17:53:56 +00:00
Log.i("Removing placeholder");
img.removeAttr("src");
continue;
}
2020-11-15 19:37:27 +00:00
2020-11-16 17:53:56 +00:00
// Remove spacer, etc
2020-11-16 21:10:48 +00:00
if (!show_images && !(inline_images && isInline) &&
2020-11-16 17:53:56 +00:00
TextUtils.isEmpty(img.attr("x-tracking"))) {
Log.i("Removing small image");
Integer width = Helper.parseInt(img.attr("width").trim());
Integer height = Helper.parseInt(img.attr("height").trim());
2021-08-03 06:04:40 +00:00
if (width != null && height != null) {
if (width == 0 && height != 0)
width = height;
if (width != 0 && height == 0)
height = width;
}
2020-11-16 17:53:56 +00:00
if ((width != null && width <= SMALL_IMAGE_SIZE) ||
(height != null && height <= SMALL_IMAGE_SIZE)) {
img.remove();
continue;
}
}
2020-05-04 18:19:05 +00:00
if (alt.length() > MAX_ALT)
alt = alt.substring(0, MAX_ALT) + "";
2021-05-29 14:15:01 +00:00
if (!show_images && !(inline_images && isInline))
if (TextUtils.isEmpty(tracking)) {
if (TextUtils.isEmpty(alt)) {
boolean linked = false;
Element p = img.parent();
while (p != null && !linked)
2021-07-07 04:55:08 +00:00
if ("a".equals(p.tagName())) {
String href = p.attr("href");
2021-09-23 15:38:54 +00:00
if (TextUtils.isEmpty(href))
2021-07-07 04:55:08 +00:00
break;
2021-08-04 14:06:54 +00:00
if (!TextUtils.isEmpty(p.text()))
break;
2021-05-29 14:15:01 +00:00
linked = true;
2021-07-07 04:55:08 +00:00
} else
2021-05-29 14:15:01 +00:00
p = p.parent();
if (linked)
alt = context.getString(R.string.title_image_link);
}
2021-08-04 15:19:43 +00:00
if (!TextUtils.isEmpty(alt)) {
Element span = document.createElement("span")
.text("[" + alt + "]")
.attr("x-font-size-abs", Integer.toString(textSizeSmall));
img.appendChild(span);
}
2021-05-29 14:15:01 +00:00
} else if (!TextUtils.isEmpty(alt)) {
2021-08-04 15:19:43 +00:00
Element a = document.createElement("a")
.attr("href", tracking)
.text("[" + alt + "]")
.attr("x-font-size-abs", Integer.toString(textSizeSmall));
2019-10-19 08:19:05 +00:00
img.appendChild(a);
2019-06-30 07:41:18 +00:00
}
}
2019-03-30 16:48:04 +00:00
2019-09-12 08:45:54 +00:00
// Selective new lines
2020-11-06 18:39:31 +00:00
for (Element div : document.select("div"))
2019-09-12 08:45:54 +00:00
div.tagName("span");
2020-04-13 17:31:02 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
for (Element span : document.select("span"))
if (!TextUtils.isEmpty(span.attr("color")))
span.tagName("font");
2019-11-22 18:16:02 +00:00
if (document.body() == null) {
Log.e("Sanitize without body");
document.normalise();
}
2019-11-19 20:53:12 +00:00
return document;
2018-08-02 13:33:06 +00:00
}
2018-12-14 09:11:45 +00:00
static void removeRelativeLinks(Document document) {
2021-10-02 17:48:23 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
2021-10-01 17:24:06 +00:00
Elements b = document.select("base");
String base = (b.size() > 0 ? b.get(0).attr("href") : null);
for (Element e : document.select("a,img")) {
String attr = ("a".equals(e.tagName()) ? "href" : "src");
String link = e.attr(attr);
2021-10-07 08:29:51 +00:00
2021-10-02 17:48:23 +00:00
if (!TextUtils.isEmpty(base))
2021-10-01 17:24:06 +00:00
try {
// https://developer.android.com/reference/java/net/URI
link = URI.create(base).resolve(link.replace(" ", "%20")).toString();
e.attr(attr, link);
2021-10-01 17:24:06 +00:00
} catch (Throwable ex) {
Log.w(ex);
}
2021-10-02 17:48:23 +00:00
if ("a".equals(e.tagName()) &&
link.trim().startsWith("#")) {
e.tagName("span");
e.removeAttr(attr);
2021-10-02 17:48:23 +00:00
}
2021-10-01 17:24:06 +00:00
}
2021-09-23 15:38:54 +00:00
}
2021-03-22 18:38:14 +00:00
static void autoLink(Document document) {
2022-04-08 11:25:26 +00:00
autoLink(document, false);
}
static void autoLink(Document document, boolean outbound) {
2021-03-22 18:38:14 +00:00
// https://en.wikipedia.org/wiki/List_of_URI_schemes
// xmpp:[<user>]@<host>[:<port>]/[<resource>][?<query>]
// geo:<lat>,<lon>[,<alt>][;u=<uncertainty>]
// tel:<phonenumber>
2021-12-29 11:37:12 +00:00
final Pattern GPA_PATTERN = Pattern.compile("GPA\\.\\d{4}-\\d{4}-\\d{4}-\\d{5}");
2022-02-17 09:06:05 +00:00
final String BOUNDARY = "(?:\\b|$|^)";
2021-03-22 18:38:14 +00:00
final Pattern pattern = Pattern.compile(
2022-02-17 09:06:05 +00:00
"(" + BOUNDARY + "((?i:mailto):)?" + Helper.EMAIL_ADDRESS + "(\\?[^\\s]*)?" + BOUNDARY + ")" +
2022-02-16 15:07:25 +00:00
"|" +
2021-03-22 18:38:14 +00:00
PatternsCompat.AUTOLINK_WEB_URL.pattern()
.replace("(?i:http|https|rtsp)://",
2022-02-16 15:07:25 +00:00
"(((?i:http|https)://)|((?i:xmpp):))") +
"|" +
"(?i:geo:\\d+,\\d+(,\\d+)?(;u=\\d+)?)" +
"|" +
2021-12-29 11:37:12 +00:00
"(?i:tel:" + Patterns.PHONE.pattern() + ")" +
(BuildConfig.DEBUG ? "|(" + GPA_PATTERN + ")" : ""));
2021-03-22 18:38:14 +00:00
NodeTraversor.traverse(new NodeVisitor() {
private int links = 0;
@Override
public void head(Node node, int depth) {
if (links < MAX_AUTO_LINK && node instanceof TextNode) {
TextNode tnode = (TextNode) node;
String text = tnode.getWholeText();
2022-02-06 21:41:57 +00:00
if (BuildConfig.DEBUG && node.parentNode() instanceof Element) {
Element parent = (Element) node.parentNode();
if ("faircode_txn_id".equals(parent.className())) {
Element a = document.createElement("a");
2022-04-08 18:02:16 +00:00
a.attr("href", BuildConfig.TX_URI + text.trim());
2022-02-06 21:41:57 +00:00
a.text(text);
tnode.before(a);
tnode.text("");
return;
}
}
2021-03-22 18:38:14 +00:00
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
Element span = document.createElement("span");
int pos = 0;
do {
boolean linked = false;
Node parent = tnode.parent();
while (parent != null) {
if ("a".equals(parent.nodeName())) {
linked = true;
break;
}
parent = parent.parent();
}
String group = matcher.group();
int start = matcher.start();
int end = matcher.end();
// Workarounds
if (group.endsWith(".")) {
end--;
group = group.substring(0, group.length() - 1);
}
if (group.startsWith("(")) {
start++;
group = group.substring(1);
}
if (group.endsWith(")")) {
end--;
group = group.substring(0, group.length() - 1);
}
boolean email = group.contains("@") && !group.contains(":");
2021-06-15 10:39:57 +00:00
Log.i("Web url=" + group + " " + start + "..." + end + "/" + text.length() +
2021-03-22 18:38:14 +00:00
" linked=" + linked + " email=" + email + " count=" + links);
if (linked)
span.appendText(text.substring(pos, end));
else {
span.appendText(text.substring(pos, start));
Element a = document.createElement("a");
2021-12-29 11:37:12 +00:00
if (BuildConfig.DEBUG && GPA_PATTERN.matcher(group).matches())
2022-02-07 07:24:15 +00:00
a.attr("href", BuildConfig.GPA_URI + group);
2022-04-08 11:25:26 +00:00
else {
String url = (email ? "mailto:" : "") + group;
2022-04-08 16:59:56 +00:00
if (outbound)
try {
Uri uri = UriHelper.guessScheme(Uri.parse(url));
a.attr("href", uri.toString());
} catch (Throwable ex) {
Log.e(ex);
a.attr("href", url);
}
else
2022-04-08 11:25:26 +00:00
a.attr("href", url);
}
2021-03-22 18:38:14 +00:00
a.text(group);
span.appendChild(a);
links++;
}
pos = end;
} while (links < MAX_AUTO_LINK && matcher.find());
span.appendText(text.substring(pos));
tnode.before(span);
tnode.text("");
}
}
}
@Override
public void tail(Node node, int depth) {
}
}, document);
}
2021-09-05 17:08:52 +00:00
static void guessSchemes(Document document) {
for (Element e : document.select("a,img"))
2021-09-05 17:08:52 +00:00
try {
String attr = ("a".equals(e.tagName()) ? "href" : "src");
String url = e.attr(attr);
if (TextUtils.isEmpty(url))
2021-09-05 17:08:52 +00:00
continue;
Uri uri = UriHelper.guessScheme(Uri.parse(url));
e.attr(attr, uri.toString());
2021-09-05 17:08:52 +00:00
} catch (Throwable ex) {
Log.e(ex);
}
}
2020-12-29 08:04:29 +00:00
static void normalizeNamespaces(Document parsed, boolean display_hidden) {
// <html xmlns:v="urn:schemas-microsoft-com:vml"
// xmlns:o="urn:schemas-microsoft-com:office:office"
// xmlns:w="urn:schemas-microsoft-com:office:word"
// xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
// xmlns="http://www.w3.org/TR/REC-html40">
// <o:p>&nbsp;</o:p></span>
2022-12-07 20:51:18 +00:00
// <w:Sdt DocPart="0C3EDB8F875B40C899499DE56A431990" ...
2020-12-29 08:04:29 +00:00
// Default XHTML namespace: http://www.w3.org/1999/xhtml
2022-04-30 18:36:34 +00:00
// https://developer.mozilla.org/en-US/docs/Related/IMSC/Namespaces
2020-12-29 08:04:29 +00:00
String ns = null;
for (Element h : parsed.select("html"))
for (Attribute a : h.attributes()) {
String key = a.getKey();
2022-05-06 18:58:39 +00:00
String value = a.getValue().toLowerCase(Locale.ROOT);
if ("xmlns".equals(key) && value.contains(W3NS)) {
2022-04-30 18:36:34 +00:00
ns = key;
break;
2022-05-06 18:58:39 +00:00
} else if (key.startsWith("xmlns:") && value.contains(W3NS)) {
2020-12-29 08:04:29 +00:00
ns = key.split(":")[1];
break;
}
}
2022-04-30 18:36:34 +00:00
2020-12-29 08:04:29 +00:00
for (Element e : parsed.select("*")) {
String tag = e.tagName();
if (tag.contains(":")) {
2022-05-06 21:03:21 +00:00
boolean show = (ns == null || tag.startsWith(ns) ||
2022-12-07 20:51:18 +00:00
tag.startsWith("html:") || tag.startsWith("body:") || tag.startsWith("w:"));
2022-03-03 17:19:06 +00:00
if (display_hidden || show) {
2020-12-29 08:04:29 +00:00
String[] nstag = tag.split(":");
2022-10-25 20:20:08 +00:00
String t = nstag[nstag.length > 1 ? 1 : 0];
if (!TextUtils.isEmpty(t)) {
e.tagName(t);
Log.i("Updated tag=" + tag + " to=" + t);
}
2022-03-03 17:19:06 +00:00
if (!show) {
String style = e.attr("style");
e.attr("style", mergeStyles(style, "text-decoration:line-through;"));
}
2020-12-29 08:04:29 +00:00
} else {
e.remove();
2022-12-07 20:51:18 +00:00
Log.i("Removed tag=" + tag + " ns=" + ns + " content=" + e.text());
2020-12-29 08:04:29 +00:00
}
2022-12-07 20:51:18 +00:00
} else if (!"html".equals(tag) && !"body".equals(tag) && !"w".equals(tag)) {
2022-05-06 21:03:21 +00:00
String xmlns = e.attr("xmlns").toLowerCase(Locale.ROOT);
if (!TextUtils.isEmpty(xmlns) && !xmlns.contains(W3NS)) {
if (display_hidden) {
String style = e.attr("style");
e.attr("style", mergeStyles(style, "text-decoration:line-through;"));
} else {
e.remove();
2022-12-07 20:51:18 +00:00
Log.i("Removed tag=" + tag + " ns=" + ns + " xmlns=" + xmlns + " content=" + e.text());
2022-05-06 21:03:21 +00:00
}
2022-04-30 18:36:34 +00:00
}
}
2020-12-29 08:04:29 +00:00
}
}
2020-07-16 20:06:52 +00:00
static List<CSSStyleSheet> parseStyles(Elements styles) {
List<CSSStyleSheet> sheets = new ArrayList<>();
for (Element style : styles) {
if (BuildConfig.DEBUG)
Log.i("Style=" + style.data());
try {
InputSource source = new InputSource(new StringReader(style.data()));
String media = style.attr("media");
if (!TextUtils.isEmpty(media))
source.setMedia(media);
CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
parser.setErrorHandler(new ErrorHandler() {
@Override
public void warning(CSSParseException ex) throws CSSException {
Log.i("CSS warning=" + ex.getMessage());
}
@Override
public void error(CSSParseException ex) throws CSSException {
Log.i("CSS error=" + ex.getMessage());
}
@Override
public void fatalError(CSSParseException ex) throws CSSException {
Log.w(ex);
}
});
long start = new Date().getTime();
sheets.add(parser.parseStyleSheet(source, null, null));
long elapsed = new Date().getTime() - start;
Log.i("Style parse=" + elapsed + " ms");
} catch (Throwable ex) {
Log.w(ex);
}
}
return sheets;
}
2020-07-16 20:25:16 +00:00
static String processStyles(String tag, String clazz, String style, List<CSSStyleSheet> sheets) {
2020-04-21 07:04:55 +00:00
for (CSSStyleSheet sheet : sheets)
2020-04-22 14:32:35 +00:00
if (isScreenMedia(sheet.getMedia())) {
style = processStyles(null, clazz, style, sheet.getCssRules(), Selector.SAC_ELEMENT_NODE_SELECTOR);
style = processStyles(tag, clazz, style, sheet.getCssRules(), Selector.SAC_ELEMENT_NODE_SELECTOR);
style = processStyles(tag, clazz, style, sheet.getCssRules(), Selector.SAC_CONDITIONAL_SELECTOR);
}
2020-04-21 07:04:55 +00:00
return style;
}
2020-04-22 14:32:35 +00:00
private static String processStyles(String tag, String clazz, String style, CSSRuleList rules, int stype) {
2020-04-21 07:04:55 +00:00
for (int i = 0; rules != null && i < rules.getLength(); i++) {
CSSRule rule = rules.item(i);
switch (rule.getType()) {
case CSSRule.STYLE_RULE:
CSSStyleRuleImpl srule = (CSSStyleRuleImpl) rule;
for (int j = 0; j < srule.getSelectors().getLength(); j++) {
Selector selector = srule.getSelectors().item(j);
2020-04-22 14:32:35 +00:00
if (selector.getSelectorType() != stype)
continue;
2020-04-21 07:04:55 +00:00
switch (selector.getSelectorType()) {
2020-04-22 14:32:35 +00:00
case Selector.SAC_ELEMENT_NODE_SELECTOR:
ElementSelectorImpl eselector = (ElementSelectorImpl) selector;
2020-04-22 14:54:50 +00:00
if (tag == null
? eselector.getLocalName() == null
2020-04-22 14:32:35 +00:00
: tag.equals(eselector.getLocalName()))
style = mergeStyles(style, srule.getStyle().getCssText());
break;
2020-04-21 07:04:55 +00:00
case Selector.SAC_CONDITIONAL_SELECTOR:
ConditionalSelectorImpl cselector = (ConditionalSelectorImpl) selector;
if (cselector.getCondition().getConditionType() == SAC_CLASS_CONDITION) {
ClassConditionImpl ccondition = (ClassConditionImpl) cselector.getCondition();
if (clazz.equals(ccondition.getValue()))
2020-04-22 14:32:35 +00:00
style = mergeStyles(style, srule.getStyle().getCssText());
2020-04-21 07:04:55 +00:00
}
break;
}
}
break;
case CSSRule.MEDIA_RULE:
CSSMediaRuleImpl mrule = (CSSMediaRuleImpl) rule;
if (isScreenMedia(mrule.getMedia()))
2020-04-22 14:32:35 +00:00
style = processStyles(tag, clazz, style, mrule.getCssRules(), stype);
2020-04-21 07:04:55 +00:00
break;
}
}
return style;
}
private static boolean isScreenMedia(MediaList media) {
// https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
2020-04-21 09:41:52 +00:00
// https://developers.google.com/gmail/design/reference/supported_css#supported_types
2020-04-21 07:04:55 +00:00
if (media instanceof MediaListImpl) {
MediaListImpl _media = (MediaListImpl) media;
for (int i = 0; i < _media.getLength(); i++) {
String query = _media.mediaQuery(i).getCssText(null);
if ("all".equals(query) ||
"screen".equals(query) || "only screen".equals(query))
return true;
}
} else
Log.e("Media class=" + media.getClass().getName());
return false;
}
2020-07-16 20:25:16 +00:00
static String mergeStyles(String base, String style) {
2022-03-08 18:42:54 +00:00
return mergeStyles(base, style, false);
2020-04-21 18:29:58 +00:00
}
2022-03-08 18:42:54 +00:00
static String mergeElementStyles(String base, String style) {
return mergeStyles(base, style, true);
}
2020-04-20 13:01:05 +00:00
2022-03-08 18:42:54 +00:00
private static String mergeStyles(String base, String style, boolean element) {
Map<String, String> result = new HashMap<>();
2022-03-08 14:20:41 +00:00
// Base style
2022-03-08 18:42:54 +00:00
Map<String, String> baseParams = new HashMap<>();
2020-04-20 13:01:05 +00:00
if (!TextUtils.isEmpty(base))
2022-03-08 14:20:41 +00:00
for (String param : base.split(";")) {
int colon = param.indexOf(':');
if (colon < 0) {
Log.w("CSS invalid=" + param);
continue;
}
String key = param.substring(0, colon).trim().toLowerCase(Locale.ROOT);
2022-03-08 18:42:54 +00:00
baseParams.put(key, param);
2022-03-08 14:20:41 +00:00
}
// Element style
2020-04-20 13:01:05 +00:00
if (!TextUtils.isEmpty(style))
2022-03-08 14:20:41 +00:00
for (String param : style.split(";")) {
int colon = param.indexOf(':');
if (colon < 0) {
Log.w("CSS invalid=" + param);
continue;
}
2020-04-20 13:01:05 +00:00
String key = param.substring(0, colon).trim().toLowerCase(Locale.ROOT);
2022-03-08 14:20:41 +00:00
String value = param.substring(colon + 1).trim().toUpperCase(Locale.ROOT);
2022-03-08 18:42:54 +00:00
//https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#controlling_inheritance
boolean initial = false; // no value
boolean inherit = false; // parent value
if (element)
switch (value) {
case "inherit":
inherit = true;
break;
case "initial":
initial = true;
break;
case "unset":
case "revert":
inherit = !STYLE_NO_INHERIT.contains(key);
break;
}
if (initial || inherit)
Log.i("CSS " + value + "=" + key);
if (inherit) {
param = baseParams.get(key);
if (param != null)
result.put(key, param);
} else if (!initial)
2020-04-21 18:29:58 +00:00
result.put(key, param);
2022-03-08 18:42:54 +00:00
baseParams.remove(key);
2022-03-08 14:20:41 +00:00
}
2020-04-20 13:01:05 +00:00
2022-03-08 18:42:54 +00:00
for (String key : baseParams.keySet())
if (!STYLE_NO_INHERIT.contains(key))
result.put(key, baseParams.get(key));
2020-04-20 13:01:05 +00:00
return TextUtils.join(";", result.values());
}
private static Integer getFontWeight(String value) {
2020-04-30 07:28:24 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
if (TextUtils.isEmpty(value))
return null;
value = value.toLowerCase(Locale.ROOT).trim();
switch (value) {
2020-04-30 07:28:24 +00:00
case "thin":
return 100;
2020-04-26 14:02:21 +00:00
case "light":
case "lighter":
return 300;
case "normal":
2020-04-28 05:53:22 +00:00
case "regular":
return 400;
case "bolder":
2020-04-28 05:53:22 +00:00
case "strong":
return 600;
case "bold":
return 700;
2020-04-30 07:28:24 +00:00
case "heavy":
return 900;
2020-04-28 18:13:49 +00:00
case "none":
2020-04-30 07:28:24 +00:00
case "auto":
2020-05-04 16:27:46 +00:00
case "unset":
2020-04-30 07:28:24 +00:00
case "initial":
2020-04-27 14:23:32 +00:00
case "inherit":
return null;
}
try {
return Integer.parseInt(value);
2020-04-25 18:35:45 +00:00
} catch (NumberFormatException ex) {
2020-05-28 06:48:28 +00:00
Log.i(ex);
}
return null;
}
private static Float getFontSize(String value, float current) {
2020-04-22 08:50:58 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-size
if (TextUtils.isEmpty(value))
return null;
2020-04-22 08:50:58 +00:00
if (value.contains("calc") ||
2020-04-30 07:28:24 +00:00
"none".equals(value) ||
2020-04-22 08:50:58 +00:00
"auto".equals(value) ||
2020-05-04 16:27:46 +00:00
"unset".equals(value) ||
2020-04-22 12:31:12 +00:00
"initial".equals(value) ||
2020-04-22 08:50:58 +00:00
"inherit".equals(value))
return null;
2020-04-20 07:57:42 +00:00
// Absolute
switch (value) {
case "xx-small":
case "x-small":
2022-08-27 15:48:36 +00:00
return FONT_XSMALL;
2020-04-20 07:57:42 +00:00
case "small":
return FONT_SMALL;
case "medium":
return 1.0f;
case "large":
2022-08-27 15:48:36 +00:00
return FONT_LARGE;
2020-04-20 07:57:42 +00:00
case "x-large":
case "xx-large":
case "xxx-large":
2022-08-27 15:48:36 +00:00
return FONT_XLARGE;
2020-04-20 07:57:42 +00:00
}
// Relative
switch (value) {
case "smaller":
2020-04-28 07:02:07 +00:00
return FONT_SMALL * current;
2020-04-20 07:57:42 +00:00
case "larger":
2020-04-28 07:02:07 +00:00
return FONT_LARGE * current;
2020-04-20 07:57:42 +00:00
}
try {
2020-04-20 07:57:42 +00:00
if (value.endsWith("%"))
2020-04-28 07:02:07 +00:00
return Float.parseFloat(value.substring(0, value.length() - 1).trim()) / 100 * current;
2020-02-20 10:28:55 +00:00
if (value.endsWith("rem"))
return Float.parseFloat(value.substring(0, value.length() - 3).trim());
2021-01-05 13:08:39 +00:00
if (value.endsWith("em"))
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) * current;
2021-04-24 16:54:18 +00:00
if (value.endsWith("ex")) // 1 ex = 0.5 em
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) / 2 * current;
2020-04-28 16:32:10 +00:00
if (value.endsWith("pt"))
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) / DEFAULT_FONT_SIZE_PT;
if (value.endsWith("px"))
2020-04-22 12:31:12 +00:00
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) / DEFAULT_FONT_SIZE;
2020-06-16 18:39:00 +00:00
// https://www.w3.org/Style/Examples/007/units.en.html
if (value.endsWith("pc")) // 6 pc = 72 pt
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) / 12 / DEFAULT_FONT_SIZE_PT;
if (value.endsWith("cm")) // 1 inch = 2.54 cm
2021-02-25 12:32:33 +00:00
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) / 2.54f * 72 / DEFAULT_FONT_SIZE_PT;
if (value.endsWith("mm")) // 1 inch = 25.4 mm
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) / 25.4f * 72 / DEFAULT_FONT_SIZE_PT;
2020-06-16 18:39:00 +00:00
if (value.endsWith("in")) // 1 inch = 72pt
2021-02-25 12:32:33 +00:00
return Float.parseFloat(value.substring(0, value.length() - 2).trim()) * 72 / DEFAULT_FONT_SIZE_PT;
2020-04-22 12:31:12 +00:00
return Float.parseFloat(value.trim()) / DEFAULT_FONT_SIZE;
2020-04-20 07:57:42 +00:00
} catch (NumberFormatException ex) {
2020-04-24 10:07:29 +00:00
Log.i(ex);
2020-04-22 12:31:12 +00:00
return null;
}
}
2021-07-05 14:55:31 +00:00
private static Integer parseColor(String value) {
if (TextUtils.isEmpty(value))
return null;
2022-03-03 17:00:34 +00:00
if ("transparent".equals(value))
return Color.TRANSPARENT;
2020-01-31 12:52:57 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
String c = value
2020-02-04 09:19:17 +00:00
.replace("null", "")
2020-01-31 12:52:57 +00:00
.replace("none", "")
.replace("unset", "")
2020-02-10 08:34:15 +00:00
.replace("auto", "")
2020-01-31 12:52:57 +00:00
.replace("inherit", "")
.replace("initial", "")
.replace("windowtext", "")
2020-02-07 08:58:22 +00:00
.replace("currentcolor", "")
2020-01-31 12:52:57 +00:00
.replace("transparent", "")
2020-02-04 09:19:17 +00:00
.replaceAll("[^a-z0-9(),.%#]", "")
.replaceAll("#+", "#");
2020-01-31 12:52:57 +00:00
Integer color = null;
2021-07-05 14:55:31 +00:00
boolean hasAlpha = false;
2020-01-31 12:52:57 +00:00
try {
if (TextUtils.isEmpty(c))
return null;
2020-02-04 09:00:07 +00:00
else if (c.startsWith("#")) {
2020-02-04 09:19:17 +00:00
if (c.length() > 1) {
String code = c.substring(1);
if (x11ColorMap.containsKey(code)) // workaround
2020-02-08 17:45:28 +00:00
color = x11ColorMap.get(code);
2021-07-05 14:55:31 +00:00
else {
color = parseWebColor(c);
hasAlpha = true;
}
2020-02-04 09:19:17 +00:00
}
2020-02-04 09:00:07 +00:00
} else if (c.startsWith("rgb") || c.startsWith("hsl")) {
2020-01-31 12:52:57 +00:00
int s = c.indexOf("(");
int e = c.indexOf(")");
if (s > 0 && e > s) {
String[] component = c.substring(s + 1, e).split(",");
for (int i = 0; i < component.length; i++)
if (component[i].endsWith("%"))
if (c.startsWith("rgb")) {
int percent = Integer.parseInt(component[i].replace("%", ""));
component[i] = Integer.toString(Math.round(255 * (percent / 100f)));
} else
component[i] = component[i].replace("%", "");
if (c.startsWith("rgb") && component.length >= 3)
color = Color.rgb(
Integer.parseInt(component[0]),
Integer.parseInt(component[1]),
Integer.parseInt(component[2]));
else if (c.startsWith("hsl") && component.length >= 3)
color = ColorUtils.HSLToColor(new float[]{
Float.parseFloat(component[0]),
Integer.parseInt(component[1]) / 100f,
Integer.parseInt(component[2]) / 100f});
2021-07-05 14:55:31 +00:00
if (color != null && component.length >= 4) {
int alpha = Math.round(Float.parseFloat(component[3]) * 255);
color = ColorUtils.setAlphaComponent(color, alpha);
hasAlpha = true;
}
2020-01-31 12:52:57 +00:00
}
} else if (x11ColorMap.containsKey(c))
2020-02-08 17:45:28 +00:00
color = x11ColorMap.get(c);
2021-07-05 14:55:31 +00:00
else {
2021-07-05 14:35:31 +00:00
color = parseWebColor(c);
2021-07-05 14:55:31 +00:00
hasAlpha = true;
}
if (color != null && !hasAlpha)
color = ColorUtils.setAlphaComponent(color, 255);
2020-01-31 12:52:57 +00:00
if (BuildConfig.DEBUG)
2021-07-05 14:55:31 +00:00
Log.i("Color " + c + "=" + (color == null ? null : encodeWebColor(color)));
2020-01-31 12:52:57 +00:00
} catch (Throwable ex) {
2020-05-28 06:48:28 +00:00
Log.i("Color=" + c + ": " + ex);
2020-01-31 12:52:57 +00:00
}
2020-06-29 12:21:19 +00:00
return color;
}
2020-01-31 13:45:51 +00:00
2021-07-05 14:55:31 +00:00
private static int parseWebColor(@NonNull String value) {
if (value.startsWith("#"))
value = value.substring(1);
if (value.length() == 3)
value = "FF" +
value.charAt(0) + value.charAt(0) +
value.charAt(1) + value.charAt(1) +
value.charAt(2) + value.charAt(2);
else if (value.length() == 6)
value = "FF" + value;
else if (value.length() == 8)
value = value.substring(6, 8) + value.substring(0, 6);
else
2021-07-05 14:35:31 +00:00
throw new IllegalArgumentException("Unknown color=" + value);
2021-07-05 14:55:31 +00:00
return (int) Long.parseLong(value, 16);
}
static String encodeWebColor(int color) {
int alpha = Color.alpha(color);
int rgb = 0xFFFFFF & color;
if (alpha == 255)
2021-07-05 14:55:31 +00:00
return String.format("#%06X", rgb);
else
return String.format("#%06X%02X", rgb, alpha);
2021-07-05 14:35:31 +00:00
}
2021-07-05 04:55:24 +00:00
private static Integer adjustColor(boolean dark, int textColorPrimary, Integer color) {
2021-07-05 14:55:31 +00:00
// Special case:
// shades of gray
2020-06-29 12:21:19 +00:00
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
2021-07-05 14:55:31 +00:00
float a = Color.alpha(color) / 255f;
if (r == g && r == b && (dark ? 255 - r : r) * a < GRAY_THRESHOLD)
2021-07-05 04:55:24 +00:00
color = textColorPrimary;
2020-01-31 12:52:57 +00:00
return adjustLuminance(color, dark, MIN_LUMINANCE_VIEW);
2021-07-05 14:55:31 +00:00
}
static int adjustLuminance(int color, boolean dark, float min) {
int c = ColorUtils.compositeColors(color, dark ? Color.BLACK : Color.WHITE);
float lum = (float) ColorUtils.calculateLuminance(c);
if (dark ? lum < min : lum > 1 - min)
color = ColorUtils.blendARGB(color,
dark ? Color.WHITE : Color.BLACK,
dark ? min - lum : lum - (1 - min));
return color;
2020-01-31 12:52:57 +00:00
}
2021-08-04 06:10:39 +00:00
private static boolean hasColor(int color) {
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
return (Math.abs(r - g) >= COLOR_THRESHOLD ||
Math.abs(r - b) >= COLOR_THRESHOLD);
}
2020-04-07 17:43:02 +00:00
// https://tools.ietf.org/html/rfc3676
2022-02-12 22:18:05 +00:00
static String flow(String text, boolean delsp) {
2022-03-14 09:17:40 +00:00
boolean inquote = false;
2022-03-14 10:33:10 +00:00
boolean continuation = false;
2020-04-07 17:43:02 +00:00
StringBuilder flowed = new StringBuilder();
2020-11-02 07:04:42 +00:00
String[] lines = text.split("\\r?\\n");
for (int l = 0; l < lines.length; l++) {
String line = lines[l];
lines[l] = null;
2022-02-13 08:15:34 +00:00
if (delsp && line.endsWith(" "))
2022-02-12 22:18:05 +00:00
line = line.substring(0, line.length() - 1);
2022-03-14 09:17:40 +00:00
boolean q = line.startsWith(">");
if (q != inquote) {
int len = flowed.length();
if (len > 0 && flowed.charAt(len - 1) != '\n')
flowed.append("\n");
continuation = false;
}
inquote = q;
2020-04-07 17:43:02 +00:00
if (continuation)
while (line.startsWith(">")) {
line = line.substring(1);
if (line.startsWith(" "))
line = line.substring(1);
}
continuation = (line.endsWith(" ") && !"-- ".equals(line));
flowed.append(line);
2022-03-14 10:33:10 +00:00
2020-04-07 17:43:02 +00:00
if (!continuation)
2022-03-14 10:33:10 +00:00
flowed.append("\n");
2020-04-07 17:43:02 +00:00
}
2022-03-14 10:33:10 +00:00
2020-04-07 17:43:02 +00:00
return flowed.toString();
}
2022-01-09 18:09:55 +00:00
static String formatPlainText(String text) {
return formatPlainText(text, true);
2020-05-22 18:07:58 +00:00
}
2022-01-09 18:09:55 +00:00
static String formatPlainText(String text, boolean view) {
2019-11-19 08:57:55 +00:00
int level = 0;
StringBuilder sb = new StringBuilder();
2022-01-09 18:09:55 +00:00
String[] lines = text
.replaceAll("\\r(?!\\n)", "\n")
.split("\\r?\\n");
2020-11-02 07:04:42 +00:00
for (int l = 0; l < lines.length; l++) {
String line = lines[l];
lines[l] = null;
2019-11-19 08:57:55 +00:00
// Opening quotes
2020-05-20 08:56:05 +00:00
// https://tools.ietf.org/html/rfc3676#section-4.5
2021-05-23 18:07:10 +00:00
if (view) {
2020-05-22 18:07:58 +00:00
int tlevel = 0;
while (line.startsWith(">")) {
tlevel++;
if (tlevel > level)
2021-07-08 14:55:42 +00:00
sb.append("<blockquote style=\"")
.append(getQuoteStyle(line, 0, line.length()))
.append("\">");
2019-11-19 08:57:55 +00:00
2020-05-22 18:07:58 +00:00
line = line.substring(1); // >
2020-05-20 13:28:19 +00:00
2020-05-22 18:07:58 +00:00
if (line.startsWith(" >"))
line = line.substring(1);
}
if (tlevel > 0)
if (line.length() > 0 && line.charAt(0) == ' ')
line = line.substring(1);
2019-11-19 08:57:55 +00:00
2020-05-22 18:07:58 +00:00
// Closing quotes
for (int i = 0; i < level - tlevel; i++)
sb.append("</blockquote>");
level = tlevel;
}
2019-11-19 08:57:55 +00:00
// Tabs characters
2020-11-02 07:04:42 +00:00
StringBuilder sbl = new StringBuilder();
2019-11-19 08:57:55 +00:00
for (int j = 0; j < line.length(); j++) {
char kar = line.charAt(j);
if (kar == '\t') {
2020-11-02 07:04:42 +00:00
sbl.append(' ');
while (sbl.length() % TAB_SIZE != 0)
sbl.append(' ');
2019-11-19 08:57:55 +00:00
} else
2020-11-02 07:04:42 +00:00
sbl.append(kar);
2019-11-19 08:57:55 +00:00
}
2020-11-02 07:04:42 +00:00
line = sbl.toString();
2019-11-19 08:57:55 +00:00
// Html characters
2020-05-02 09:14:17 +00:00
// This will handle spaces / word wrapping as well
2019-11-19 08:57:55 +00:00
line = Html.escapeHtml(line);
2020-05-02 09:14:17 +00:00
sb.append(line);
2021-05-23 18:07:10 +00:00
if (view ||
2021-05-23 18:33:12 +00:00
l + 1 < lines.length ||
text.endsWith("\n"))
2021-05-23 18:07:10 +00:00
sb.append("<br>");
2019-11-19 08:57:55 +00:00
}
// Closing quotes
for (int i = 0; i < level; i++)
sb.append("</blockquote>");
return sb.toString();
}
static void restorePre(Document document) {
document.select("div[x-plain=true]")
.tagName("pre")
.removeAttr("x-plain");
}
2020-11-16 17:53:56 +00:00
static void removeTrackingPixels(Context context, Document document) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean disconnect_images = (prefs.getBoolean("disconnect_images", false) && BuildConfig.DEBUG);
2022-08-04 13:24:27 +00:00
Drawable d = ContextCompat.getDrawable(context, R.drawable.twotone_my_location_24);
2019-10-04 21:04:03 +00:00
d.setTint(Helper.resolveColor(context, R.attr.colorWarning));
2019-10-05 07:38:36 +00:00
2019-10-04 21:04:03 +00:00
Bitmap bm = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
d.setBounds(0, 0, c.getWidth(), c.getHeight());
d.draw(c);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
StringBuilder sb = new StringBuilder();
2019-10-05 07:38:36 +00:00
sb.append("data:image/png;base64,");
2019-10-05 09:57:54 +00:00
sb.append(Base64.encodeToString(bos.toByteArray(), Base64.NO_WRAP));
2019-10-04 21:04:03 +00:00
// Build list of allowed hosts
List<String> hosts = new ArrayList<>();
for (Element img : document.select("img")) {
String src = img.attr("src");
if (!TextUtils.isEmpty(src) && !isTrackingPixel(img)) {
Uri uri = Uri.parse(img.attr("src"));
String host = uri.getHost();
2020-10-30 18:01:24 +00:00
if (host != null && !hosts.contains(host) &&
!isTrackingHost(host, disconnect_images))
hosts.add(host);
}
}
2019-10-04 13:25:04 +00:00
// Images
for (Element img : document.select("img")) {
2020-05-05 16:49:55 +00:00
img.removeAttr("x-tracking");
2019-10-04 13:25:04 +00:00
String src = img.attr("src");
2020-11-15 19:37:27 +00:00
if (TextUtils.isEmpty(src))
continue;
Uri uri = Uri.parse(src);
String host = uri.getHost();
2020-11-16 17:53:56 +00:00
if (host == null || hosts.contains(host))
continue;
2020-10-30 18:01:24 +00:00
if (isTrackingPixel(img) || isTrackingHost(host, disconnect_images)) {
img.attr("src", sb.toString());
img.attr("alt", context.getString(R.string.title_legend_tracking_pixel));
img.attr("height", "24");
img.attr("width", "24");
img.attr("style", "display:block !important; width:24px !important; height:24px !important;");
img.attr("x-tracking", src);
2019-10-04 13:25:04 +00:00
}
}
}
private static boolean isTrackingPixel(Element img) {
// Newton mail
if ("cloudmagic-smart-beacon".equals(img.className()))
return true;
2019-10-04 19:25:52 +00:00
String width = img.attr("width").trim();
String height = img.attr("height").trim();
2019-03-30 16:55:00 +00:00
2019-10-04 19:25:52 +00:00
if (TextUtils.isEmpty(width) || TextUtils.isEmpty(height))
return false;
2018-12-14 09:11:45 +00:00
2019-10-03 06:55:37 +00:00
try {
2021-08-03 06:04:40 +00:00
int w = Integer.parseInt(width);
int h = Integer.parseInt(height);
if (w == 0 && h != 0)
w = h;
if (w != 0 && h == 0)
h = w;
return (w * h <= TRACKING_PIXEL_SURFACE);
2019-10-04 19:25:52 +00:00
} catch (NumberFormatException ignored) {
return false;
}
}
2019-10-03 06:55:37 +00:00
2020-10-30 18:01:24 +00:00
private static boolean isTrackingHost(String host, boolean disconnect_images) {
if (TRACKING_HOSTS.contains(host))
return true;
if (disconnect_images && DisconnectBlacklist.isTracking(host))
return true;
return false;
}
2020-02-28 09:01:18 +00:00
static void embedInlineImages(Context context, long id, Document document, boolean local) throws IOException {
2019-10-04 19:25:52 +00:00
DB db = DB.getInstance(context);
for (Element img : document.select("img")) {
String src = img.attr("src");
if (src.startsWith("cid:")) {
String cid = '<' + src.substring(4) + '>';
2019-10-03 06:55:37 +00:00
EntityAttachment attachment = db.attachment().getAttachment(id, cid);
2019-10-04 19:25:52 +00:00
if (attachment != null && attachment.available) {
File file = attachment.getFile(context);
2020-02-28 09:01:18 +00:00
if (local) {
Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file);
img.attr("src", uri.toString());
Log.i("Inline image uri=" + uri);
} else {
try (InputStream is = new FileInputStream(file)) {
byte[] bytes = new byte[(int) file.length()];
if (is.read(bytes) != bytes.length)
throw new IOException("length");
StringBuilder sb = new StringBuilder();
sb.append("data:");
sb.append(attachment.type);
sb.append(";base64,");
sb.append(Base64.encodeToString(bytes, Base64.NO_WRAP));
img.attr("src", sb.toString());
}
2019-04-30 08:33:03 +00:00
}
}
2019-10-04 19:25:52 +00:00
}
2019-07-15 10:17:01 +00:00
}
}
static void setViewport(Document document, boolean overview) {
2019-10-08 17:54:52 +00:00
// https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
2021-07-02 16:35:52 +00:00
// https://drafts.csswg.org/css-device-adapt/#viewport-meta
2020-09-18 10:40:30 +00:00
Elements meta = document.select("meta").select("[name=viewport]");
// Note that the browser will recognize meta elements in the body too
2021-12-04 15:31:48 +00:00
if (overview) {
// fit width
meta.remove();
2021-12-04 15:31:48 +00:00
document.head().prependElement("meta")
.attr("name", "viewport")
.attr("content", "width=device-width");
} else {
2020-08-28 15:03:03 +00:00
if (meta.size() == 1) {
2020-09-18 10:40:30 +00:00
String content = meta.attr("content");
String[] param = content.split("[;,]");
for (int i = 0; i < param.length; i++) {
String[] kv = param[i].split("=");
2020-09-29 07:27:07 +00:00
if (kv.length == 2) {
2021-07-02 16:35:52 +00:00
String key = kv[0]
.replaceAll("\\s+", "")
.toLowerCase(Locale.ROOT);
switch (key) {
2020-09-29 07:27:07 +00:00
case "user-scalable":
kv[1] = "yes";
param[i] = TextUtils.join("=", kv);
break;
case "minimum-scale":
case "maximum-scale":
kv[0] = "disabled-scaling";
param[i] = TextUtils.join("=", kv);
break;
}
2020-09-18 10:40:30 +00:00
}
}
2021-07-02 16:35:52 +00:00
meta.attr("content", TextUtils.join(",", param));
2020-08-28 15:03:03 +00:00
} else {
meta.remove();
document.head().prependElement("meta")
.attr("name", "viewport")
.attr("content", "width=device-width, initial-scale=1.0");
2020-08-28 15:03:03 +00:00
}
}
2019-10-08 17:54:52 +00:00
2021-07-02 16:35:52 +00:00
if (BuildConfig.DEBUG)
Log.i(document.head().html());
}
2021-12-04 16:42:52 +00:00
static void overrideWidth(Document document) {
List<String> tags = new ArrayList<>();
for (Element e : document.select("*")) {
String tag = e.tagName();
if ("img".equals(tag))
continue;
if (tags.contains(tag))
continue;
tags.add(tag);
2021-12-04 13:10:11 +00:00
}
2021-12-04 16:42:52 +00:00
StringBuilder sb = new StringBuilder();
sb.append("<style type=\"text/css\">");
for (String tag : tags)
2022-08-11 12:35:39 +00:00
sb.append(tag).append("{width: auto !important; min-width: 0 !important; max-width: 100% !important; overflow: auto !important;}");
2021-12-04 16:42:52 +00:00
sb.append("</style>");
document.select("head").append(sb.toString());
2021-12-03 08:12:01 +00:00
}
2022-07-04 10:48:28 +00:00
static boolean hasColorScheme(Document document, String name) {
List<CSSStyleSheet> sheets = parseStyles(document.head().select("style"));
for (CSSStyleSheet sheet : sheets)
if (sheet.getCssRules() != null) {
for (int i = 0; i < sheet.getCssRules().getLength(); i++) {
CSSRule rule = sheet.getCssRules().item(i);
if (rule instanceof CSSMediaRuleImpl) {
MediaList list = ((CSSMediaRuleImpl) rule).getMedia();
String media = (list == null ? null : list.getMediaText());
if (media != null &&
media.toLowerCase(Locale.ROOT).contains("prefers-color-scheme") &&
media.toLowerCase(Locale.ROOT).contains(name)) {
Log.i("@media=" + media);
return true;
}
}
}
}
return false;
}
2022-07-04 06:11:26 +00:00
static void fakeDark(Document document) {
2022-07-04 10:48:28 +00:00
// https://issuetracker.google.com/issues/237785596
2022-07-04 06:11:26 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/invert
// https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/hue-rotate
2022-07-04 10:48:28 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
// https://developer.android.com/reference/android/webkit/WebSettings#setAlgorithmicDarkeningAllowed(boolean)
2022-07-06 07:16:02 +00:00
if (true || hasColorScheme(document, "dark"))
2022-07-04 10:48:28 +00:00
return;
2022-07-04 06:11:26 +00:00
document.head().appendElement("style").html(
"body { filter: invert(100%) hue-rotate(180deg) !important; background: black !important; }" +
"img { filter: invert(100%) hue-rotate(180deg) !important; }");
}
2021-01-25 13:49:56 +00:00
static String getLanguage(Context context, String subject, String text) {
2020-02-20 09:35:01 +00:00
try {
2020-03-26 14:25:44 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2020-03-26 19:28:17 +00:00
boolean language_detection = prefs.getBoolean("language_detection", false);
if (!language_detection)
2020-03-26 14:25:44 +00:00
return null;
2021-01-25 13:49:56 +00:00
StringBuilder sb = new StringBuilder();
if (!TextUtils.isEmpty(subject))
sb.append(subject).append('\n');
if (!TextUtils.isEmpty(text))
sb.append(text);
if (sb.length() == 0)
return null;
Locale locale = TextHelper.detectLanguage(context, sb.toString());
2020-11-16 14:46:55 +00:00
return (locale == null ? null : locale.getLanguage());
2020-03-26 14:25:44 +00:00
} catch (Throwable ex) {
2020-02-20 09:35:01 +00:00
Log.e(ex);
return null;
}
}
2021-01-19 11:18:03 +00:00
static String getPreview(String text) {
2021-01-19 10:57:59 +00:00
if (text == null)
2019-11-11 19:23:34 +00:00
return null;
2021-01-19 10:57:59 +00:00
String preview = text
.replace("\u200C", "") // Zero-width non-joiner
.replaceAll("\\s+", " ");
return truncate(preview, PREVIEW_SIZE);
2019-11-11 19:23:34 +00:00
}
2020-02-11 19:07:00 +00:00
static String getFullText(String body) {
try {
2020-02-20 09:35:01 +00:00
if (body == null)
return null;
Document d = JsoupEx.parse(body);
2021-01-19 10:57:59 +00:00
return _getText(d);
2020-02-11 19:07:00 +00:00
} catch (OutOfMemoryError ex) {
Log.e(ex);
return null;
}
}
2020-02-20 09:35:01 +00:00
static String getFullText(File file) throws IOException {
try {
Document d = JsoupEx.parse(file);
2021-01-19 10:57:59 +00:00
return _getText(d);
2020-02-20 09:35:01 +00:00
} catch (OutOfMemoryError ex) {
Log.e(ex);
2019-10-03 16:07:56 +00:00
return null;
2020-02-20 09:35:01 +00:00
}
}
2019-10-03 16:07:56 +00:00
2021-01-19 10:57:59 +00:00
private static String _getText(Document d) {
2021-01-19 11:02:49 +00:00
truncate(d, MAX_FULL_TEXT_SIZE);
2020-02-14 10:06:48 +00:00
2021-07-07 13:12:35 +00:00
for (Element bq : d.select("blockquote"))
2021-07-07 16:41:26 +00:00
bq.prependChild(new TextNode("> "));
2021-10-24 07:11:40 +00:00
return d.body().text();
2020-07-14 06:57:46 +00:00
}
2021-07-07 18:07:11 +00:00
static String getQuoteStyle(Element e) {
CharSequence text = e.text();
return getQuoteStyle(text, 0, text.length());
}
static String getQuoteStyle(CharSequence quoted, int start, int end) {
2022-01-19 17:02:09 +00:00
String dir = "left";
2021-07-07 18:07:11 +00:00
try {
2021-08-09 19:59:16 +00:00
int count = end - start;
if (TextDirectionHeuristics.FIRSTSTRONG_LTR.isRtl(quoted, start, count))
2022-01-19 17:02:09 +00:00
dir = "right";
2021-07-07 18:07:11 +00:00
} catch (Throwable ex) {
2021-08-09 19:59:16 +00:00
Log.e(new Throwable("getQuoteStyle " + start + "..." + end, ex));
2021-07-07 18:07:11 +00:00
}
2022-03-26 13:37:03 +00:00
return "border-" + dir + ":3px solid #ccc; padding-" + dir + ":10px;margin:0;";
2021-07-07 18:07:11 +00:00
}
2022-01-19 17:59:12 +00:00
static String getIndentStyle(CharSequence quoted, int start, int end) {
return "margin-top:0; margin-bottom:0;";
}
2021-07-07 13:12:35 +00:00
static boolean hasBorder(Element e) {
2021-07-23 16:00:09 +00:00
if ("true".equals(e.attr("x-border")))
return true;
// https://groups.google.com/g/mozilla.support.thunderbird/c/rwLNk3MU3Gs?pli=1
if ("cite".equals(e.attr("type")))
return true;
2021-07-23 16:00:09 +00:00
String style = e.attr("style");
String[] params = style.split(";");
for (String param : params) {
int colon = param.indexOf(':');
if (colon < 0)
continue;
String key = param.substring(0, colon).trim().toLowerCase(Locale.ROOT);
String value = param.substring(colon + 1);
if ("border-left".equals(key) || "border-right".equals(key)) {
Float border = getFontSize(value.trim().split("\\s+")[0], 1.0f);
if (border != null && border > 0)
return true;
}
}
return false;
2021-07-07 13:12:35 +00:00
}
2022-02-17 12:38:01 +00:00
static boolean isStyled(Document d) {
ObjectHolder<Boolean> result = new ObjectHolder<>(false);
d.body().filter(new NodeFilter() {
private final List<String> STRUCTURE = Collections.unmodifiableList(Arrays.asList(
"body", "div", "p", "span", "br",
"strong", "b", "em", "i", "blockquote", "hr"
));
@Override
public FilterResult head(Node node, int depth) {
if (node instanceof Element) {
Element e = (Element) node;
2022-11-17 06:58:17 +00:00
String style = e.attr("style");
if (!TextUtils.isEmpty(style)) {
String[] params = style.split(";");
for (String param : params) {
int colon = param.indexOf(':');
if (colon <= 0)
continue;
String key = param.substring(0, colon).trim();
if ("color".equalsIgnoreCase(key) ||
"background-color".equalsIgnoreCase(key) ||
"font-family".equalsIgnoreCase(key) ||
"font-size".equalsIgnoreCase(key) ||
"text-align".equalsIgnoreCase(key) ||
"text-decoration".equalsIgnoreCase(key) /* line-through */) {
Log.i("Style element=" + node + " style=" + style);
result.value = true;
return FilterResult.STOP;
}
}
}
2022-02-17 12:38:01 +00:00
if (STRUCTURE.contains(e.tagName()))
return FilterResult.CONTINUE;
if (!TextUtils.isEmpty(e.attr("fairemail")))
return FilterResult.CONTINUE;
//Element p = e.parent();
//if ("blockquote".equals(e.tagName()) &&
// p != null &&
// !TextUtils.isEmpty(p.attr("fairemail")))
// return FilterResult.CONTINUE;
Log.i("Style element=" + node);
result.value = true;
return FilterResult.STOP;
} else
return FilterResult.CONTINUE;
}
@Override
public FilterResult tail(Node node, int depth) {
return FilterResult.CONTINUE;
}
});
return result.value;
}
2021-07-07 16:08:57 +00:00
static void collapseQuotes(Document document) {
document.body().filter(new NodeFilter() {
private int level = 0;
@Override
public FilterResult head(Node node, int depth) {
if (level > 0)
return FilterResult.REMOVE;
if (node instanceof Element) {
Element element = (Element) node;
if ("blockquote".equals(element.tagName()) && hasBorder(element)) {
Element prev = element.previousElementSibling();
if (prev != null &&
"blockquote".equals(prev.tagName()) && hasBorder(prev))
return FilterResult.REMOVE;
2021-07-07 17:39:09 +00:00
else {
level++;
element.html("&#8230;");
}
2021-07-07 16:08:57 +00:00
}
}
2021-07-07 17:39:09 +00:00
2021-07-07 16:08:57 +00:00
return FilterResult.CONTINUE;
}
@Override
public FilterResult tail(Node node, int depth) {
if ("blockquote".equals(node.nodeName()))
level--;
2021-07-07 17:39:09 +00:00
2021-07-07 16:08:57 +00:00
return FilterResult.CONTINUE;
}
});
}
2022-09-20 07:51:33 +00:00
static void removeSignatures(Document d) {
d.body().filter(new NodeFilter() {
private boolean remove = false;
private boolean noremove = false;
@Override
public FilterResult head(Node node, int depth) {
if (node instanceof TextNode) {
TextNode tnode = (TextNode) node;
String text = tnode.getWholeText()
.replaceAll("[\r\n]+$", "")
.replaceAll("^[\r\n]+", "");
if ("-- ".equals(text)) {
if (tnode.getWholeText().endsWith("\n"))
remove = true;
else {
Node next = node.nextSibling();
if (next == null) {
Node parent = node.parent();
if (parent != null)
next = parent.nextSibling();
}
if (next != null && "br".equals(next.nodeName()))
remove = true;
}
}
} else if (node instanceof Element) {
Element element = (Element) node;
if (remove && "blockquote".equals(element.tagName()))
noremove = true;
}
return (remove && !noremove
? FilterResult.REMOVE : FilterResult.CONTINUE);
}
@Override
public FilterResult tail(Node node, int depth) {
return FilterResult.CONTINUE;
}
});
}
2020-07-14 06:57:46 +00:00
static String truncate(String text, int at) {
if (text.length() < at)
return text;
2019-10-03 16:07:56 +00:00
2020-07-14 06:57:46 +00:00
String preview = text.substring(0, at);
int space = preview.lastIndexOf(' ');
if (space > 0)
preview = preview.substring(0, space + 1);
return preview + "";
2019-01-05 11:17:33 +00:00
}
2020-09-10 09:14:51 +00:00
@NonNull
2020-05-02 12:23:11 +00:00
static String getText(Context context, String html) {
2020-11-07 15:03:33 +00:00
Document d = sanitizeCompose(context, html, false);
2020-02-14 10:06:48 +00:00
truncate(d, getMaxFormatTextSize(context));
2020-02-14 10:06:48 +00:00
2020-11-08 20:09:31 +00:00
SpannableStringBuilder ssb = fromDocument(context, d, null, null);
2019-01-05 11:17:33 +00:00
2021-02-20 20:08:28 +00:00
for (StyleSpan span : ssb.getSpans(0, ssb.length(), StyleSpan.class)) {
int start = ssb.getSpanStart(span);
int end = ssb.getSpanEnd(span);
if (span.getStyle() == Typeface.ITALIC) {
ssb.insert(end, "/");
ssb.insert(start, "/");
} else if (span.getStyle() == Typeface.BOLD) {
2021-02-20 20:08:28 +00:00
ssb.insert(end, "*");
ssb.insert(start, "*");
}
}
for (UnderlineSpan span : ssb.getSpans(0, ssb.length(), UnderlineSpan.class)) {
int start = ssb.getSpanStart(span);
int end = ssb.getSpanEnd(span);
ssb.insert(end, "_");
ssb.insert(start, "_");
}
2020-05-02 12:23:11 +00:00
for (URLSpan span : ssb.getSpans(0, ssb.length(), URLSpan.class)) {
String url = span.getURL();
if (TextUtils.isEmpty(url))
continue;
2022-02-14 17:39:56 +00:00
2020-05-02 12:23:11 +00:00
if (url.toLowerCase(Locale.ROOT).startsWith("mailto:"))
url = url.substring("mailto:".length());
2022-02-14 17:39:56 +00:00
2020-05-02 12:23:11 +00:00
int start = ssb.getSpanStart(span);
int end = ssb.getSpanEnd(span);
String text = ssb.subSequence(start, end).toString();
if (!text.contains(url))
ssb.insert(end, "[" + url + "]");
}
2019-11-22 19:42:45 +00:00
2020-05-02 12:23:11 +00:00
for (ImageSpan span : ssb.getSpans(0, ssb.length(), ImageSpan.class)) {
String source = span.getSource();
if (TextUtils.isEmpty(source))
continue;
2022-02-14 17:39:56 +00:00
2020-05-02 12:23:11 +00:00
int start = ssb.getSpanStart(span);
int end = ssb.getSpanEnd(span);
2022-02-14 21:41:28 +00:00
if (!source.toLowerCase(Locale.ROOT).startsWith("data:"))
ssb.insert(end, "[" + source + "]");
2020-05-02 12:23:11 +00:00
for (int i = start; i < end; i++)
2022-02-14 21:41:28 +00:00
if (ssb.charAt(i) == '\uFFFC') {
ssb.delete(i, i + 1);
end--;
}
2020-05-02 12:23:11 +00:00
}
2019-02-11 15:36:42 +00:00
2020-05-20 08:56:05 +00:00
// https://tools.ietf.org/html/rfc3676#section-4.5
2020-05-02 12:23:11 +00:00
for (QuoteSpan span : ssb.getSpans(0, ssb.length(), QuoteSpan.class)) {
int start = ssb.getSpanStart(span);
int end = ssb.getSpanEnd(span);
2020-05-20 08:56:05 +00:00
2020-05-26 20:15:55 +00:00
for (int i = end - 2; i >= start; i--)
2020-05-02 12:23:11 +00:00
if (ssb.charAt(i) == '\n')
2020-05-20 13:28:19 +00:00
if (i + 1 < ssb.length() && ssb.charAt(i + 1) == '>')
ssb.insert(i + 1, ">");
else
ssb.insert(i + 1, "> ");
2020-05-20 08:56:05 +00:00
2020-05-25 16:57:59 +00:00
if (start < ssb.length())
ssb.insert(start, ssb.charAt(start) == '>' ? ">" : "> ");
2020-05-02 12:23:11 +00:00
}
2019-11-22 19:42:45 +00:00
2020-05-02 12:23:11 +00:00
for (BulletSpan span : ssb.getSpans(0, ssb.length(), BulletSpan.class)) {
int start = ssb.getSpanStart(span);
2021-05-06 06:22:04 +00:00
if (span instanceof NumberSpan) {
2021-05-06 18:54:38 +00:00
NumberSpan ns = (NumberSpan) span;
ssb.insert(start, ns.getIndex() + ". ");
int level = ns.getLevel();
2021-05-06 06:22:04 +00:00
for (int l = 1; l <= level; l++)
2021-07-09 07:36:11 +00:00
ssb.insert(start, " ");
2021-05-06 06:22:04 +00:00
} else {
if (span instanceof BulletSpanEx) {
2021-05-06 18:54:38 +00:00
BulletSpanEx bs = (BulletSpanEx) span;
2021-07-09 07:36:11 +00:00
if (!"none".equals(bs.getLType()))
ssb.insert(start, "* ");
2021-05-06 18:54:38 +00:00
int level = bs.getLevel();
2021-05-06 06:22:04 +00:00
for (int l = 1; l <= level; l++)
2021-07-09 07:36:11 +00:00
ssb.insert(start, " ");
} else
ssb.insert(start, "* ");
2021-05-06 06:22:04 +00:00
}
2020-05-02 12:23:11 +00:00
}
2019-02-10 12:01:21 +00:00
2022-02-04 09:24:30 +00:00
for (LineSpan span : ssb.getSpans(0, ssb.length(), LineSpan.class)) {
int start = ssb.getSpanStart(span);
int end = ssb.getSpanEnd(span);
ssb.replace(start, end, LINE);
}
2020-05-02 12:23:11 +00:00
return ssb.toString();
2018-12-24 20:09:47 +00:00
}
2020-03-08 15:05:43 +00:00
2021-07-01 07:19:59 +00:00
static Spanned highlightHeaders(Context context, String headers, boolean blocklist) {
2021-09-09 10:52:10 +00:00
SpannableStringBuilder ssb = new SpannableStringBuilderEx(headers);
2021-06-17 06:58:44 +00:00
int textColorLink = Helper.resolveColor(context, android.R.attr.textColorLink);
2022-01-08 12:35:45 +00:00
int colorVerified = Helper.resolveColor(context, R.attr.colorVerified);
int colorWarning = Helper.resolveColor(context, R.attr.colorWarning);
2021-06-15 13:15:03 +00:00
2019-08-29 19:57:04 +00:00
int index = 0;
for (String line : headers.split("\n")) {
if (line.length() > 0 && !Character.isWhitespace(line.charAt(0))) {
int colon = line.indexOf(':');
if (colon > 0)
2021-06-17 06:58:44 +00:00
ssb.setSpan(new ForegroundColorSpan(textColorLink), index, index + colon, 0);
2019-08-29 19:57:04 +00:00
}
index += line.length() + 1;
}
2021-06-15 13:15:03 +00:00
try {
// https://datatracker.ietf.org/doc/html/rfc2821#section-4.4
final DateFormat DTF = Helper.getDateTimeInstance(context, DateFormat.SHORT, DateFormat.MEDIUM);
2022-03-30 18:20:24 +00:00
MailDateFormat mdf = new MailDateFormat();
2021-06-15 13:15:03 +00:00
ByteArrayInputStream bis = new ByteArrayInputStream(headers.getBytes());
2022-08-13 12:03:41 +00:00
InternetHeaders iheaders = new InternetHeaders(bis, true);
2022-03-30 18:20:24 +00:00
String dh = iheaders.getHeader("Date", null);
Date tx = null;
try {
if (dh != null)
tx = mdf.parse(dh);
} catch (ParseException ex) {
Log.w(ex);
}
String[] received = iheaders.getHeader("Received");
2022-01-06 15:14:31 +00:00
if (received != null && received.length > 0) {
2021-06-15 13:15:03 +00:00
for (int i = received.length - 1; i >= 0; i--) {
2022-01-08 13:03:13 +00:00
ssb.append('\n');
2021-06-15 13:15:03 +00:00
String h = MimeUtility.unfold(received[i]);
int semi = h.lastIndexOf(';');
2022-03-30 18:20:24 +00:00
Date rx = null;
2021-06-15 13:15:03 +00:00
if (semi > 0) {
2022-03-30 18:20:24 +00:00
rx = mdf.parse(h, new ParsePosition(semi + 1));
2021-06-15 13:15:03 +00:00
h = h.substring(0, semi);
}
int s = ssb.length();
ssb.append('#').append(Integer.toString(received.length - i));
2022-03-30 18:20:24 +00:00
if (rx != null) {
ssb.append(' ').append(DTF.format(rx));
if (tx != null) {
long ms = rx.getTime() - tx.getTime();
ssb.append(" \u0394").append(DateUtils.formatElapsedTime(ms / 1000));
}
}
2021-06-15 13:15:03 +00:00
ssb.setSpan(new StyleSpan(Typeface.BOLD), s, ssb.length(), 0);
2021-07-01 07:19:59 +00:00
if (blocklist && i == received.length - 1) {
2022-08-04 13:24:27 +00:00
Drawable d = ContextCompat.getDrawable(context, R.drawable.twotone_flag_24);
2021-07-01 07:19:59 +00:00
int iconSize = context.getResources().getDimensionPixelSize(R.dimen.menu_item_icon_size);
d.setBounds(0, 0, iconSize, iconSize);
d.setTint(colorWarning);
ssb.append(" \uFFFC"); // Object replacement character
ssb.setSpan(new ImageSpan(d), ssb.length() - 1, ssb.length(), 0);
if (!TextUtils.isEmpty(BuildConfig.MXTOOLBOX_URI)) {
final String header = received[i];
ClickableSpan click = new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
DnsBlockList.show(widget.getContext(), header);
}
};
ssb.setSpan(click, ssb.length() - 1, ssb.length(), 0);
}
}
2021-06-15 13:15:03 +00:00
ssb.append('\n');
int j = 0;
boolean p = false;
2021-06-15 13:15:03 +00:00
String[] w = h.split("\\s+");
while (j < w.length) {
if (w[j].startsWith("("))
p = true;
2021-06-15 13:15:03 +00:00
if (j > 0)
ssb.append(' ');
s = ssb.length();
ssb.append(w[j]);
2022-01-07 20:48:15 +00:00
if (!p && MessageHelper.RECEIVED_WORDS.contains(w[j].toLowerCase(Locale.ROOT)))
2021-06-17 06:58:44 +00:00
ssb.setSpan(new ForegroundColorSpan(textColorLink), s, ssb.length(), 0);
if (w[j].endsWith(")"))
p = false;
2021-06-15 13:15:03 +00:00
j++;
}
2022-01-08 12:35:45 +00:00
Boolean tls = MessageHelper.isTLS(h, i == received.length - 1);
2022-01-08 12:35:45 +00:00
ssb.append(" TLS=");
int t = ssb.length();
ssb.append(tls == null ? "?" : Boolean.toString(tls));
if (tls != null)
ssb.setSpan(new ForegroundColorSpan(tls ? colorVerified : colorWarning), t, ssb.length(), 0);
2022-01-08 13:03:13 +00:00
ssb.append("\n");
2021-06-15 13:15:03 +00:00
}
}
} catch (Throwable ex) {
Log.w(ex);
}
2019-08-29 19:57:04 +00:00
return ssb;
}
2022-12-16 19:13:07 +00:00
static void highlightSearched(Context context, Document document, String query) {
try {
int color = Helper.resolveColor(context, R.attr.colorHighlight);
2022-12-20 17:55:27 +00:00
StringBuilder sb = new StringBuilder();
for (String word : query.trim().split("\\s+")) {
if (word.startsWith("+") || word.startsWith("-"))
continue;
for (String w : Fts4DbHelper.breakText(word).split("\\s+")) {
if (sb.length() > 0)
sb.append("\\s*");
sb.append(Pattern.quote(w));
}
}
sb.insert(0, ".*?\\b(");
sb.append(")\\b.*?");
2022-12-16 19:13:07 +00:00
2022-12-20 17:55:27 +00:00
Pattern p = Pattern.compile(sb.toString(), Pattern.DOTALL);
NodeTraversor.traverse(new NodeVisitor() {
@Override
public void head(Node node, int depth) {
if (node instanceof TextNode)
try {
TextNode tnode = (TextNode) node;
String text = Fts4DbHelper.preprocessText(tnode.getWholeText());
2022-12-20 17:55:27 +00:00
Matcher result = p.matcher(text);
2022-12-20 17:55:27 +00:00
int prev = 0;
Element holder = document.createElement("span");
while (result.find()) {
int start = result.start(1);
int end = result.end(1);
2022-10-13 11:17:21 +00:00
2022-12-20 17:55:27 +00:00
holder.appendText(text.substring(prev, start));
2022-12-20 17:55:27 +00:00
Element span = document.createElement("span");
span.attr("style", mergeStyles(
span.attr("style"),
"font-size:larger; background-color:" + encodeWebColor(color)
));
span.text(text.substring(start, end));
holder.appendChild(span);
2022-12-20 17:55:27 +00:00
prev = end;
}
2021-11-12 15:12:54 +00:00
2022-12-20 17:55:27 +00:00
if (prev == 0) // No matches
return;
if (prev < text.length())
holder.appendText(text.substring(prev));
tnode.before(holder);
tnode.text("");
} catch (Throwable ex) {
Log.e(ex);
}
}
@Override
public void tail(Node node, int depth) {
}
}, document);
2022-12-16 19:13:07 +00:00
} catch (Throwable ex) {
Log.e(ex);
}
2021-11-12 15:12:54 +00:00
}
2022-04-04 12:42:58 +00:00
static Document markText(Document document) {
for (Element mark : document.select("mark")) {
String style = mark.attr("style");
mark.attr("style", mergeStyles(style, "font-style: italic;"));
}
return document;
}
2020-02-14 12:31:34 +00:00
static void cleanup(Document d) {
2020-02-14 15:57:09 +00:00
// https://www.chromestatus.com/feature/5756335865987072
// Some messages contain 100 thousands of Apple spaces
2020-02-14 14:40:47 +00:00
for (Element aspace : d.select(".Apple-converted-space")) {
Node next = aspace.nextSibling();
if (next instanceof TextNode) {
TextNode tnode = (TextNode) next;
2020-02-14 15:57:09 +00:00
tnode.text(" " + tnode.text());
2020-02-14 12:31:34 +00:00
aspace.remove();
} else
aspace.replaceWith(new TextNode(" "));
2020-02-14 14:40:47 +00:00
}
2020-02-14 12:31:34 +00:00
}
2021-06-02 05:54:14 +00:00
static void quoteLimit(Document d, int maxLevel) {
for (Element bq : d.select("blockquote")) {
int level = 1;
Element parent = bq.parent();
while (parent != null) {
2021-07-07 16:56:23 +00:00
if ("blockquote".equals(parent.tagName())) // TODO: indentation
2021-06-02 05:54:14 +00:00
level++;
parent = parent.parent();
}
if (level >= maxLevel)
bq.html("&#8230;");
}
}
2021-01-19 11:02:49 +00:00
static boolean truncate(Document d, int max) {
2020-11-01 18:17:07 +00:00
final int[] length = new int[1];
2020-02-14 10:06:48 +00:00
2020-11-01 18:17:07 +00:00
NodeTraversor.filter(new NodeFilter() {
@Override
public FilterResult head(Node node, int depth) {
if (length[0] >= max)
return FilterResult.REMOVE;
else if (node instanceof TextNode) {
TextNode tnode = ((TextNode) node);
2020-02-16 09:08:46 +00:00
String text = tnode.getWholeText();
2020-11-01 18:17:07 +00:00
if (length[0] + text.length() >= max) {
text = text.substring(0, max - length[0]) + " ...";
tnode.text(text);
length[0] += text.length();
return FilterResult.SKIP_ENTIRELY;
} else
length[0] += text.length();
2020-02-16 09:08:46 +00:00
}
2020-11-01 18:17:07 +00:00
return FilterResult.CONTINUE;
2020-02-16 09:08:46 +00:00
}
2020-11-01 18:17:07 +00:00
@Override
public FilterResult tail(Node node, int depth) {
return FilterResult.CONTINUE;
}
2021-07-07 17:03:20 +00:00
}, d.body());
2020-11-01 18:17:07 +00:00
Log.i("Message size=" + length[0]);
return (length[0] > max);
2020-02-14 10:06:48 +00:00
}
static boolean contains(Document d, String[] texts) {
Map<String, Boolean> condition = new HashMap<>();
for (String t : texts)
condition.put(t, false);
2021-07-07 17:03:20 +00:00
for (Element elm : d.body().select("*"))
for (Node child : elm.childNodes()) {
if (child instanceof TextNode) {
TextNode tnode = ((TextNode) child);
String text = tnode.getWholeText();
for (String t : texts)
if (!condition.get(t) && text.contains(t)) {
condition.put(t, true);
boolean found = true;
for (String c : texts)
if (!condition.get(c)) {
found = false;
break;
}
if (found)
return true;
}
}
}
return false;
}
2020-06-28 19:23:33 +00:00
static SpannableStringBuilder fromDocument(
2020-11-08 20:09:31 +00:00
Context context, @NonNull Document document,
@Nullable ImageGetterEx imageGetter, @Nullable Html.TagHandler tagHandler) {
2020-04-24 14:12:07 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2020-04-25 08:11:01 +00:00
boolean debug = prefs.getBoolean("debug", false);
boolean monospaced_pre = prefs.getBoolean("monospaced_pre", false);
final int colorPrimary = Helper.resolveColor(context, R.attr.colorPrimary);
final int colorAccent = Helper.resolveColor(context, R.attr.colorAccent);
2021-07-05 04:53:21 +00:00
final int colorBlockquote = Helper.resolveColor(context, R.attr.colorBlockquote, colorPrimary);
2020-05-04 18:29:18 +00:00
final int colorSeparator = Helper.resolveColor(context, R.attr.colorSeparator);
2021-05-07 12:09:16 +00:00
int bulletGap = context.getResources().getDimensionPixelSize(R.dimen.bullet_gap_size);
int bulletRadius = context.getResources().getDimensionPixelSize(R.dimen.bullet_radius_size);
int bulletIndent = context.getResources().getDimensionPixelSize(R.dimen.bullet_indent_size);
2021-07-07 13:12:35 +00:00
int intentSize = context.getResources().getDimensionPixelSize(R.dimen.indent_size);
2021-05-07 12:19:59 +00:00
int quoteGap = context.getResources().getDimensionPixelSize(R.dimen.quote_gap_size);
int quoteStripe = context.getResources().getDimensionPixelSize(R.dimen.quote_stripe_width);
2021-06-27 20:09:59 +00:00
int line_dash_length = context.getResources().getDimensionPixelSize(R.dimen.line_dash_length);
2020-04-24 14:12:07 +00:00
2020-08-14 18:15:52 +00:00
int message_zoom = prefs.getInt("message_zoom", 100);
float textSize = Helper.getTextSize(context, 0) * message_zoom / 100f;
2020-04-27 15:50:58 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
NodeTraversor.traverse(new NodeVisitor() {
private Element element;
2020-05-05 14:15:49 +00:00
private int plain = 0;
2020-04-27 15:50:58 +00:00
private List<TextNode> block = new ArrayList<>();
2021-04-29 17:11:11 +00:00
private final Pattern FOLD_WHITESPACE = Pattern.compile("[ \t\f\r\n]+");
2020-04-27 15:50:58 +00:00
2020-05-04 17:08:34 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
2020-04-27 15:50:58 +00:00
@Override
public void head(Node node, int depth) {
2020-05-05 14:15:49 +00:00
if (node instanceof TextNode) {
if (plain == 0)
block.add((TextNode) node);
} else if (node instanceof Element) {
2020-04-27 15:50:58 +00:00
element = (Element) node;
2020-11-07 15:03:33 +00:00
if ("true".equals(element.attr("x-plain")))
2020-05-05 14:15:49 +00:00
plain++;
2020-11-08 08:17:06 +00:00
if (element.isBlock() /* x-block is never false */ ||
"true".equals(element.attr("x-block"))) {
2020-04-27 15:50:58 +00:00
normalizeText(block);
block.clear();
2020-04-25 07:58:52 +00:00
}
}
2020-04-27 15:50:58 +00:00
}
2020-04-24 18:35:39 +00:00
2020-04-27 15:50:58 +00:00
@Override
public void tail(Node node, int depth) {
if (node instanceof Element) {
element = (Element) node;
2020-11-07 15:03:33 +00:00
if ("true".equals(element.attr("x-plain")))
2020-05-05 14:15:49 +00:00
plain--;
2020-11-08 08:17:06 +00:00
if (element.isBlock() /* x-block is never false */ ||
"true".equals(element.attr("x-block")) ||
2020-11-02 08:34:43 +00:00
"br".equals(element.tagName())) {
2020-04-27 15:50:58 +00:00
normalizeText(block);
block.clear();
2020-04-25 07:58:52 +00:00
}
}
2020-04-27 15:50:58 +00:00
}
2020-04-24 18:35:39 +00:00
2020-04-27 15:50:58 +00:00
private void normalizeText(List<TextNode> block) {
// https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace
TextNode tnode;
String text;
for (int i = 0; i < block.size(); ) {
tnode = block.get(i);
text = tnode.getWholeText();
2020-04-24 18:35:39 +00:00
2020-05-02 12:23:11 +00:00
if ("-- ".equals(text)) {
2020-05-26 19:01:31 +00:00
tnode.text(text);
2020-05-02 12:23:11 +00:00
i++;
continue;
}
2021-04-29 17:11:11 +00:00
// Fold white space
text = FOLD_WHITESPACE.matcher(text).replaceAll(" ");
2020-04-24 18:35:39 +00:00
2021-04-29 17:11:11 +00:00
// Conditionally remove leading whitespace
if (isSpace(text, 0) &&
(i == 0 || endsWithSpace(block.get(i - 1).text())))
text = text.substring(1);
2020-05-16 15:44:25 +00:00
2022-02-15 14:57:53 +00:00
// Soft hyphen
if (text.trim().equals("\u00ad"))
text = "";
2020-04-27 15:50:58 +00:00
tnode.text(text);
2020-04-26 18:22:48 +00:00
2020-04-27 15:50:58 +00:00
if (TextUtils.isEmpty(text))
block.remove(i);
else
i++;
}
2020-04-25 08:11:01 +00:00
// Remove trailing whitespace
while (block.size() > 0) {
tnode = block.get(block.size() - 1);
text = tnode.getWholeText();
if (endsWithSpace(text) && !"-- ".equals(text)) {
text = text.substring(0, text.length() - 1);
tnode.text(text);
}
if (TextUtils.isEmpty(text))
block.remove(block.size() - 1);
else
break;
}
2021-04-29 17:11:11 +00:00
// Remove all blank blocks
2020-11-03 10:12:54 +00:00
boolean blank = true;
for (int i = 0; i < block.size(); i++) {
text = block.get(i).getWholeText();
for (int j = 0; j < text.length(); j++) {
char kar = text.charAt(j);
2021-04-30 04:52:46 +00:00
if (kar != ' ') {
2020-11-03 10:12:54 +00:00
blank = false;
break;
}
}
}
if (blank)
for (int i = 0; i < block.size(); i++)
block.get(i).text("");
2020-04-27 15:50:58 +00:00
if (debug) {
if (block.size() > 0) {
2020-05-03 07:33:10 +00:00
TextNode first = block.get(0);
TextNode last = block.get(block.size() - 1);
first.text("(" + first.getWholeText());
last.text(last.getWholeText() + ")");
2020-04-25 07:58:52 +00:00
}
}
2020-04-27 15:50:58 +00:00
}
2021-04-29 17:11:11 +00:00
boolean isSpace(String text, int index) {
2020-05-16 14:45:04 +00:00
if (index < 0 || index >= text.length())
2020-04-27 15:50:58 +00:00
return false;
2021-04-29 17:11:11 +00:00
return (text.charAt(index) == ' ');
2020-04-27 15:50:58 +00:00
}
2021-04-29 17:11:11 +00:00
boolean endsWithSpace(String text) {
return isSpace(text, text.length() - 1);
2020-04-27 15:50:58 +00:00
}
}, document.body());
2020-04-25 07:58:52 +00:00
2020-04-27 15:50:58 +00:00
// https://developer.android.com/guide/topics/text/spans
2021-09-09 10:52:10 +00:00
SpannableStringBuilder ssb = new SpannableStringBuilderEx();
2020-04-25 07:58:52 +00:00
2020-04-27 15:50:58 +00:00
NodeTraversor.traverse(new NodeVisitor() {
private Element element;
private TextNode tnode;
2022-07-18 05:11:40 +00:00
private Typeface wingdings = null;
2020-04-25 07:58:52 +00:00
2020-04-27 15:50:58 +00:00
@Override
public void head(Node node, int depth) {
if (node instanceof Element) {
element = (Element) node;
2021-07-08 14:47:35 +00:00
Element prev = element.previousElementSibling();
2020-11-06 18:39:31 +00:00
2020-11-07 09:34:34 +00:00
if ("true".equals(element.attr("x-block")))
2020-11-07 17:39:24 +00:00
if (ssb.length() > 0 && ssb.charAt(ssb.length() - 1) != '\n')
2020-11-06 18:39:31 +00:00
ssb.append('\n');
2020-11-07 09:34:34 +00:00
2020-11-07 17:14:15 +00:00
if ("true".equals(element.attr("x-paragraph")) &&
!"false".equals(element.attr("x-line-before")))
2020-11-07 17:39:24 +00:00
if (ssb.length() > 1 &&
2020-11-07 09:34:34 +00:00
(ssb.charAt(ssb.length() - 2) != '\n' ||
ssb.charAt(ssb.length() - 1) != '\n'))
ssb.append('\n');
2020-11-06 18:39:31 +00:00
if ("true".equals(element.attr("x-line-before")) &&
2021-07-08 14:47:35 +00:00
(prev == null || !"true".equals(prev.attr("x-line-after"))) &&
2020-11-06 18:39:31 +00:00
ssb.length() > 0 && ssb.charAt(ssb.length() - 1) == '\n')
ssb.append('\n');
2020-04-27 15:50:58 +00:00
element.attr("start-index", Integer.toString(ssb.length()));
2020-11-06 18:39:31 +00:00
2020-04-27 15:50:58 +00:00
if (debug)
2020-11-08 17:14:28 +00:00
ssb.append("[" + element.tagName() + "/" + element.className() +
":" + "bl=" + element.attr("x-block") +
":" + "pa=" + element.attr("x-paragraph") +
":" + "fo=" + element.attr("x-line-before") +
":" + "af=" + element.attr("x-line-after") +
":" + element.attr("style") + "]");
2020-04-27 15:50:58 +00:00
} else if (node instanceof TextNode) {
tnode = (TextNode) node;
String text = tnode.getWholeText();
ssb.append(text);
}
2020-04-27 15:50:58 +00:00
}
2020-04-27 15:50:58 +00:00
@Override
public void tail(Node node, int depth) {
if (node instanceof Element) {
element = (Element) node;
int start = Integer.parseInt(element.attr("start-index"));
2020-04-28 07:14:22 +00:00
// Apply style
String style = element.attr("style");
if (!TextUtils.isEmpty(style)) {
String[] params = style.split(";");
for (String param : params) {
int semi = param.indexOf(":");
if (semi < 0)
continue;
String key = param.substring(0, semi);
String value = param.substring(semi + 1);
switch (key) {
case "color":
case "background":
2021-07-04 09:58:54 +00:00
case "background-color":
2020-05-16 17:35:46 +00:00
if (!TextUtils.isEmpty(value))
try {
2021-07-05 14:55:31 +00:00
int color = parseWebColor(value);
2021-07-04 09:58:54 +00:00
CharacterStyle span;
if ("color".equals(key))
span = new ForegroundColorSpan(color);
else
span = new BackgroundColorSpan(color);
setSpan(ssb, span, start, ssb.length());
2021-07-10 05:02:49 +00:00
} catch (Throwable ex) {
2020-05-28 06:48:28 +00:00
Log.i(ex);
2020-05-16 17:35:46 +00:00
}
2020-04-28 07:14:22 +00:00
break;
2020-06-28 13:59:02 +00:00
case "font-family":
2021-06-01 11:34:57 +00:00
if ("wingdings".equalsIgnoreCase(value)) {
2022-07-18 05:11:40 +00:00
if (wingdings == null)
wingdings = ResourcesCompat.getFont(context.getApplicationContext(), R.font.wingdings);
int from = start;
for (int i = start; i < ssb.length(); i++) {
2020-10-29 18:06:54 +00:00
int kar = ssb.charAt(i);
if (MAP_WINGDINGS.containsKey(kar)) {
if (from < i) {
TypefaceSpan span = new CustomTypefaceSpan("wingdings", wingdings);
setSpan(ssb, span, from, i);
}
int codepoint = MAP_WINGDINGS.get(kar);
2020-10-29 18:06:54 +00:00
String replacement = new String(Character.toChars(codepoint));
2022-07-16 08:55:20 +00:00
ssb.replace(i, i + 1, replacement);
i += replacement.length() - 1;
from = i + 1;
2020-10-29 18:06:54 +00:00
}
}
2022-07-18 05:11:40 +00:00
if (from < ssb.length()) {
TypefaceSpan span = new CustomTypefaceSpan("wingdings", wingdings);
setSpan(ssb, span, from, ssb.length());
}
2020-06-29 07:42:11 +00:00
} else
2021-06-01 11:34:57 +00:00
setSpan(ssb, StyleHelper.getTypefaceSpan(value, context), start, ssb.length());
2020-06-28 13:59:02 +00:00
break;
2022-04-04 12:49:23 +00:00
case "font-style":
if ("italic".equals(value))
setSpan(ssb, new StyleSpan(Typeface.ITALIC), start, ssb.length());
break;
2020-04-28 07:14:22 +00:00
case "text-decoration":
if ("line-through".equals(value))
2020-09-26 08:18:05 +00:00
setSpan(ssb, new StrikethroughSpan(), start, ssb.length());
2022-03-03 14:26:25 +00:00
else if ("underline".equals(value))
setSpan(ssb, new UnderlineSpan(), start, ssb.length());
2020-04-28 07:14:22 +00:00
break;
2020-05-03 17:29:02 +00:00
case "text-align":
2020-11-06 12:57:11 +00:00
// https://developer.mozilla.org/en-US/docs/Web/CSS/text-align
2020-11-07 09:34:34 +00:00
Layout.Alignment alignment = null;
2021-08-01 05:13:38 +00:00
boolean rtl;
try {
rtl = TextDirectionHeuristics.FIRSTSTRONG_LTR.isRtl(ssb, start, ssb.length() - start);
} catch (Throwable ex) {
// IllegalArgumentException
Log.e(ex);
rtl = false;
}
2020-11-07 09:34:34 +00:00
switch (value) {
case "left":
case "start":
2021-01-30 14:28:43 +00:00
alignment = (rtl ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL);
2020-11-07 09:34:34 +00:00
break;
case "center":
alignment = Layout.Alignment.ALIGN_CENTER;
break;
case "right":
case "end":
2021-01-30 14:28:43 +00:00
alignment = (rtl ? Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_OPPOSITE);
2020-11-07 09:34:34 +00:00
break;
case "justify":
// Not supported by Android
break;
2020-05-03 17:29:02 +00:00
}
2020-11-07 09:34:34 +00:00
if (alignment != null)
setSpan(ssb, new AlignmentSpan.Standard(alignment), start, ssb.length());
2020-05-03 17:29:02 +00:00
break;
2022-04-04 14:54:13 +00:00
case "visibility":
2022-04-04 18:25:13 +00:00
if ("hidden".equals(value)) {
for (ForegroundColorSpan span : ssb.getSpans(start, ssb.length(), ForegroundColorSpan.class))
ssb.removeSpan(span);
for (BackgroundColorSpan span : ssb.getSpans(start, ssb.length(), BackgroundColorSpan.class))
ssb.removeSpan(span);
2022-04-04 14:54:13 +00:00
setSpan(ssb, new ForegroundColorSpan(Color.TRANSPARENT), start, ssb.length());
2022-04-04 18:25:13 +00:00
}
2022-04-04 14:54:13 +00:00
break;
2020-04-28 07:14:22 +00:00
}
}
}
// Apply calculated font size
2021-08-04 15:19:43 +00:00
String xFontSizeAbs = element.attr("x-font-size-abs");
if (TextUtils.isEmpty(xFontSizeAbs)) {
String xFontSizeRel = element.attr("x-font-size-rel");
if (!TextUtils.isEmpty(xFontSizeRel)) {
float fsize = Float.parseFloat(xFontSizeRel);
if (fsize != 1.0f)
setSpan(ssb, new RelativeSizeSpan(fsize), start, ssb.length());
}
} else {
int px = Integer.parseInt(xFontSizeAbs);
setSpan(ssb, new AbsoluteSizeSpan(px), start, ssb.length());
2020-04-28 07:14:22 +00:00
}
// Apply element
2020-08-12 20:21:55 +00:00
try {
String tag = element.tagName();
int semi = tag.indexOf(':');
if (semi >= 0)
tag = tag.substring(semi + 1);
switch (tag) {
case "a":
String href = element.attr("href");
if (!TextUtils.isEmpty(href)) {
2022-06-07 05:06:18 +00:00
if (false && BuildConfig.DEBUG) {
Uri uri = UriHelper.guessScheme(Uri.parse(href));
if (UriHelper.isHyperLink(uri))
ssb.append("\uD83D\uDD17"); // 🔗
2022-06-06 18:37:19 +00:00
// Unicode 6.0, supported since Android 4.1
// https://developer.android.com/guide/topics/resources/internationalization
}
2020-09-26 08:18:05 +00:00
setSpan(ssb, new URLSpan(href), start, ssb.length());
}
2020-08-12 20:21:55 +00:00
break;
case "big":
2020-09-26 08:18:05 +00:00
setSpan(ssb, new RelativeSizeSpan(FONT_LARGE), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "blockquote":
if (start == 0 || ssb.charAt(start - 1) != '\n')
ssb.insert(start++, "\n");
2020-09-06 14:47:49 +00:00
if (start == ssb.length())
ssb.append(' ');
2020-08-12 20:21:55 +00:00
if (ssb.length() == 0 || ssb.charAt(ssb.length() - 1) != '\n')
ssb.append("\n");
2021-07-07 13:12:35 +00:00
if (hasBorder(element)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P)
setSpan(ssb, new QuoteSpan(colorBlockquote), start, ssb.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
else
setSpan(ssb, new QuoteSpan(colorBlockquote, quoteStripe, quoteGap), start, ssb.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
} else
2021-08-01 10:36:22 +00:00
setSpan(ssb, new IndentSpan(intentSize), start, ssb.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
2020-08-12 20:21:55 +00:00
break;
case "br":
2020-11-06 18:39:31 +00:00
ssb.append('\n');
2021-09-06 10:16:59 +00:00
int l = ssb.length() - 1;
List<Object> spans = new ArrayList<>();
spans.addAll(Arrays.asList(ssb.getSpans(l, l, AbsoluteSizeSpan.class)));
spans.addAll(Arrays.asList(ssb.getSpans(l, l, RelativeSizeSpan.class)));
for (Object span : spans) {
int s = ssb.getSpanStart(span);
int e = ssb.getSpanEnd(span);
int f = ssb.getSpanFlags(span);
if (e == l) {
ssb.removeSpan(span);
if (span instanceof AbsoluteSizeSpan) {
int size = ((AbsoluteSizeSpan) span).getSize();
setSpan(ssb, new AbsoluteSizeSpan(size), s, e + 1, f);
} else if (span instanceof RelativeSizeSpan) {
float size = ((RelativeSizeSpan) span).getSizeChange();
setSpan(ssb, new RelativeSizeSpan(size), s, e + 1, f);
}
}
}
2020-08-12 20:21:55 +00:00
break;
2020-11-07 15:47:12 +00:00
case "body":
// Do nothing
break;
2020-11-09 07:25:09 +00:00
case "div": // signature
// Do nothing
break;
2020-08-12 20:21:55 +00:00
case "i":
case "em":
2020-09-26 08:18:05 +00:00
setSpan(ssb, new StyleSpan(Typeface.ITALIC), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "font":
2020-09-22 07:22:47 +00:00
String face = element.attr("face");
if (!TextUtils.isEmpty(face))
2022-02-12 11:18:29 +00:00
setSpan(ssb, StyleHelper.getTypefaceSpan(face, context), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
2020-11-15 07:28:58 +00:00
// Font size is already set
2020-09-26 08:18:05 +00:00
setSpan(ssb, new StyleSpan(Typeface.BOLD), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "hr":
2021-06-05 10:33:28 +00:00
// Suppress successive lines
2022-02-04 09:24:30 +00:00
if (!"true".equals(element.attr("x-keep-line"))) {
LineSpan[] lines = ssb.getSpans(0, ssb.length(), LineSpan.class);
int last = -1;
if (lines != null)
for (LineSpan line : lines) {
int e = ssb.getSpanEnd(line);
if (e > last)
last = e;
}
if (last >= 0) {
boolean blank = true;
for (int i = last; i < ssb.length(); i++) {
char kar = ssb.charAt(i);
if (kar != ' ' && kar != '\n' && kar != '\u00a0') {
blank = false;
break;
}
2020-11-15 07:39:13 +00:00
}
2022-02-04 09:24:30 +00:00
if (blank)
break;
}
}
2020-11-13 16:23:24 +00:00
2020-11-15 07:39:13 +00:00
boolean dashed = "true".equals(element.attr("x-dashed"));
2020-11-13 16:23:24 +00:00
float stroke = context.getResources().getDisplayMetrics().density;
2021-06-27 20:09:59 +00:00
float dash = (dashed ? line_dash_length : 0f);
2022-02-04 09:24:30 +00:00
ssb.append("\uFFFC"); // Object replacement character
2020-11-13 16:23:24 +00:00
setSpan(ssb, new LineSpan(colorSeparator, stroke, dash), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "img":
String src = element.attr("src");
if (!TextUtils.isEmpty(src)) {
Drawable d = (imageGetter == null
2022-08-04 13:24:27 +00:00
? ContextCompat.getDrawable(context, R.drawable.twotone_broken_image_24)
: imageGetter.getDrawable(element));
ssb.insert(start, "\uFFFC"); // Object replacement character
setSpan(ssb, new ImageSpanEx(d, element), start, start + 1);
}
2020-08-12 20:21:55 +00:00
break;
case "li":
if (start == 0 || ssb.charAt(start - 1) != '\n')
ssb.insert(start++, "\n");
if (ssb.length() == 0 || ssb.charAt(ssb.length() - 1) != '\n')
ssb.append("\n");
2021-05-06 06:22:04 +00:00
int level = 0;
2021-07-08 12:11:20 +00:00
Element list = null;
2022-02-09 08:23:31 +00:00
String ltype = element.attr("type");
if (TextUtils.isEmpty(ltype))
ltype = element.attr("x-list-style");
2020-08-12 20:21:55 +00:00
Element parent = element.parent();
2021-05-06 06:22:04 +00:00
while (parent != null) {
if ("ol".equals(parent.tagName()) || "ul".equals(parent.tagName())) {
2022-05-21 12:33:45 +00:00
if (!"false".equals(parent.attr("x-list-level")))
level++;
2021-07-08 12:11:20 +00:00
if (list == null)
list = parent;
2022-02-09 08:23:31 +00:00
if (TextUtils.isEmpty(ltype))
ltype = parent.attr("type");
2021-07-08 12:11:20 +00:00
if (TextUtils.isEmpty(ltype))
ltype = parent.attr("x-list-style");
2021-05-06 06:22:04 +00:00
}
2020-10-02 17:13:59 +00:00
parent = parent.parent();
2021-05-06 06:22:04 +00:00
}
if (level > 0)
level--;
2021-10-14 17:02:50 +00:00
if (list == null ||
("ul".equals(list.tagName()) &&
!NumberSpan.isSupportedType(ltype))) {
2021-07-08 12:11:20 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul
2021-07-08 06:18:35 +00:00
Object ul;
2020-08-12 20:21:55 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P)
2021-07-08 06:18:35 +00:00
ul = new BulletSpanEx(bulletIndent, bulletGap, colorAccent, level, ltype);
2020-08-12 20:21:55 +00:00
else
2021-07-08 06:18:35 +00:00
ul = new BulletSpanEx(bulletIndent, bulletGap, colorAccent, bulletRadius, level, ltype);
setSpan(ssb, ul, start, ssb.length());
2021-05-06 06:22:04 +00:00
} else {
2020-09-02 07:13:35 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol
2020-08-12 20:21:55 +00:00
int index = 0;
2021-07-08 12:11:20 +00:00
String s = list.attr("start");
2020-09-02 07:13:35 +00:00
if (!TextUtils.isEmpty(s) && TextUtils.isDigitsOnly(s))
index = Integer.parseInt(s) - 1;
2021-07-08 12:11:20 +00:00
for (Node child : list.childNodes()) {
2020-08-12 20:21:55 +00:00
if (child instanceof Element &&
child.nodeName().equals(element.tagName())) {
index++;
if (child == element)
break;
}
2020-04-24 21:13:32 +00:00
}
2021-10-14 17:02:50 +00:00
setSpan(ssb, new NumberSpan(bulletIndent, bulletGap, colorAccent, textSize, level, index, ltype), start, ssb.length());
2020-08-12 20:21:55 +00:00
}
2021-05-06 06:22:04 +00:00
2022-04-04 06:23:20 +00:00
break;
case "mark":
2022-05-04 09:30:00 +00:00
setSpan(ssb, new StyleHelper.MarkSpan(), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
2020-11-24 14:53:42 +00:00
case "pre":
2022-02-12 15:13:07 +00:00
case "tt":
2020-11-24 14:53:42 +00:00
// Signature
2022-02-12 15:33:26 +00:00
setSpan(ssb, StyleHelper.getTypefaceSpan("Cousine", context), start, ssb.length());
2020-11-24 14:53:42 +00:00
break;
2020-12-06 08:17:39 +00:00
case "style":
// signatures
break;
2020-08-12 20:21:55 +00:00
case "ol":
case "ul":
break;
2020-11-20 12:40:27 +00:00
case "meta":
// Signature
break;
case "p":
// Signature
2020-11-08 20:15:50 +00:00
break;
2020-08-12 20:21:55 +00:00
case "small":
2020-09-26 08:18:05 +00:00
setSpan(ssb, new RelativeSizeSpan(FONT_SMALL), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "span":
// Do nothing
break;
case "sub":
2022-10-15 08:41:07 +00:00
setSpan(ssb, new SubscriptSpanEx(), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "sup":
2022-10-15 08:41:07 +00:00
setSpan(ssb, new SuperscriptSpanEx(), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
2020-11-20 12:40:27 +00:00
case "table":
2020-12-09 08:10:36 +00:00
case "thead":
case "tbody":
case "tfoot":
2020-11-20 12:40:27 +00:00
case "tr":
case "th":
case "td":
// Signature
break;
2020-08-12 20:21:55 +00:00
case "b":
2020-11-24 17:31:28 +00:00
case "code": // Signature
2020-08-12 20:21:55 +00:00
case "strong":
2020-09-26 08:18:05 +00:00
setSpan(ssb, new StyleSpan(Typeface.BOLD), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
case "s":
case "del":
case "strike":
2020-09-26 08:18:05 +00:00
setSpan(ssb, new StrikethroughSpan(), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
2020-12-18 09:52:53 +00:00
case "title":
// Signature, etc
break;
2020-08-12 20:21:55 +00:00
case "u":
2020-09-26 08:18:05 +00:00
setSpan(ssb, new UnderlineSpan(), start, ssb.length());
2020-08-12 20:21:55 +00:00
break;
default:
2021-06-05 12:09:10 +00:00
Log.w("Unknown tag=" + element.tagName());
2020-08-12 20:21:55 +00:00
}
2020-11-10 18:18:19 +00:00
if (monospaced_pre &&
"true".equals(element.attr("x-plain")))
2022-02-12 15:33:26 +00:00
setSpan(ssb, StyleHelper.getTypefaceSpan("Cousine", context), start, ssb.length());
2020-08-12 20:21:55 +00:00
} catch (Throwable ex) {
Log.e(ex);
2022-02-15 15:07:24 +00:00
if (BuildConfig.DEBUG || debug) {
int s = ssb.length();
ssb.append(ex.toString()).append('\n')
.append(android.util.Log.getStackTraceString(ex)).append('\n');
setSpan(ssb, StyleHelper.getTypefaceSpan("Cousine", context), s, ssb.length());
setSpan(ssb, new RelativeSizeSpan(HtmlHelper.FONT_SMALL), s, ssb.length());
2022-02-15 17:57:41 +00:00
int colorWarning = Helper.resolveColor(context, R.attr.colorWarning);
setSpan(ssb, new ForegroundColorSpan(colorWarning), s, ssb.length());
2022-02-15 15:07:24 +00:00
}
2020-04-27 15:50:58 +00:00
}
2020-11-06 18:39:31 +00:00
2020-11-07 09:34:34 +00:00
if ("true".equals(element.attr("x-block")))
2020-11-07 17:39:24 +00:00
if (ssb.length() > 0 && ssb.charAt(ssb.length() - 1) != '\n')
2020-11-06 18:39:31 +00:00
ssb.append('\n');
2020-11-07 09:34:34 +00:00
2020-11-07 17:14:15 +00:00
if ("true".equals(element.attr("x-paragraph")) &&
!"false".equals(element.attr("x-line-after")))
2020-11-07 17:39:24 +00:00
if (ssb.length() > 1 &&
2020-11-07 09:34:34 +00:00
(ssb.charAt(ssb.length() - 2) != '\n' ||
ssb.charAt(ssb.length() - 1) != '\n'))
ssb.append('\n');
2020-11-06 18:39:31 +00:00
if ("true".equals(element.attr("x-line-after")) &&
ssb.length() > 0 && ssb.charAt(ssb.length() - 1) == '\n')
ssb.append('\n');
2020-11-14 19:02:33 +00:00
if ("true".equals(element.attr("x-column")) &&
ssb.length() > 1 &&
ssb.charAt(ssb.length() - 1) != '\n' &&
2020-11-15 07:45:45 +00:00
ssb.charAt(ssb.length() - 1) != '\u00a0' &&
2020-11-14 19:02:33 +00:00
ssb.charAt(ssb.length() - 1) != '\u2002')
ssb.append('\u2002'); // ensp
2020-11-06 18:39:31 +00:00
if (debug)
ssb.append("[/" + element.tagName() + "]");
}
2020-04-27 15:50:58 +00:00
}
2020-04-25 09:04:12 +00:00
2020-09-26 08:18:05 +00:00
private void setSpan(SpannableStringBuilder ssb, Object span, int start, int end) {
setSpan(ssb, span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private void setSpan(SpannableStringBuilder ssb, Object span, int start, int end, int flags) {
if (start == end)
return;
int len = ssb.length();
if (start >= 0 && start < len && end <= len)
ssb.setSpan(span, start, end, flags);
else
Log.e("Invalid span " + start + "..." + end + " len=" + len + " type=" + span.getClass().getName());
}
2020-04-27 15:50:58 +00:00
}, document.body());
2020-04-24 16:05:50 +00:00
2022-03-29 19:59:14 +00:00
for (LineSpan line : ssb.getSpans(0, ssb.length(), LineSpan.class)) {
2022-03-27 13:18:02 +00:00
int end = ssb.getSpanEnd(line);
2022-03-29 19:59:14 +00:00
if (end < ssb.length() && ssb.charAt(end) != '\n')
2022-03-27 13:18:02 +00:00
ssb.insert(end, "\n");
}
2020-04-27 15:50:58 +00:00
if (debug)
2020-11-14 18:48:34 +00:00
for (int i = ssb.length() - 1; i >= 0; i--) {
char kar = ssb.charAt(i);
if (kar == '\n')
2020-04-27 15:50:58 +00:00
ssb.insert(i, "|");
2020-11-14 18:48:34 +00:00
else if (kar == ' ')
2020-05-03 07:33:10 +00:00
ssb.replace(i, i + 1, "_");
2020-11-14 18:48:34 +00:00
else if (kar == '\u00A0')
2020-05-03 07:33:10 +00:00
ssb.replace(i, i + 1, "");
2021-05-05 13:36:00 +00:00
else if (!Helper.isPrintableChar(kar))
2020-11-15 07:41:04 +00:00
ssb.replace(i, i + 1, "{" + Integer.toHexString(kar) + "}");
2020-11-14 18:48:34 +00:00
}
2020-04-25 09:04:12 +00:00
2020-05-02 12:23:11 +00:00
Object[] spans = ssb.getSpans(0, ssb.length(), Object.class);
Map<Object, Integer> start = new HashMap<>();
Map<Object, Integer> end = new HashMap<>();
Map<Object, Integer> flags = new HashMap<>();
for (Object span : spans) {
start.put(span, ssb.getSpanStart(span));
end.put(span, ssb.getSpanEnd(span));
flags.put(span, ssb.getSpanFlags(span));
ssb.removeSpan(span);
}
2020-08-12 06:41:14 +00:00
for (int i = spans.length - 1; i >= 0; i--) {
int s = start.get(spans[i]);
int e = end.get(spans[i]);
int f = flags.get(spans[i]);
2020-10-03 12:26:03 +00:00
if (spans[i] instanceof AlignmentSpan ||
spans[i] instanceof BulletSpan ||
2020-10-03 14:56:59 +00:00
spans[i] instanceof NumberSpan) {
if (spans[i] instanceof AlignmentSpan &&
2021-04-26 15:16:53 +00:00
!(e > 0 && ssb.charAt(e - 1) == '\n') &&
2020-10-03 14:56:59 +00:00
e < ssb.length() && ssb.charAt(e) == '\n')
e++;
2021-04-26 15:16:53 +00:00
if (s > 0 && ssb.charAt(s - 1) == '\n' &&
e > 0 && ssb.charAt(e - 1) == '\n')
2020-08-12 06:41:14 +00:00
f |= Spanned.SPAN_PARAGRAPH;
2020-10-03 14:56:59 +00:00
}
2020-08-12 06:41:14 +00:00
ssb.setSpan(spans[i], s, e, f);
}
2020-05-02 12:23:11 +00:00
return ssb;
2020-04-24 12:00:53 +00:00
}
2020-12-19 19:12:22 +00:00
static void clearAnnotations(Document d) {
d.select("*")
2021-07-05 13:58:43 +00:00
.removeAttr("x-background")
2021-07-05 14:55:31 +00:00
.removeAttr("x-color")
2020-12-19 19:12:22 +00:00
.removeAttr("x-block")
.removeAttr("x-inline")
.removeAttr("x-paragraph")
.removeAttr("x-font-size")
.removeAttr("x-font-size-rel")
2021-08-04 15:19:43 +00:00
.removeAttr("x-font-size-abs")
2020-12-19 19:12:22 +00:00
.removeAttr("x-line-before")
.removeAttr("x-line-after")
.removeAttr("x-align")
.removeAttr("x-column")
.removeAttr("x-dashed")
2021-07-07 13:12:35 +00:00
.removeAttr("x-tracking")
2021-07-08 06:16:30 +00:00
.removeAttr("x-border")
.removeAttr("x-list-style")
2022-05-21 12:33:45 +00:00
.removeAttr("x-list-level")
2022-02-04 09:24:30 +00:00
.removeAttr("x-plain")
.remove("x-keep-line");
2020-12-19 19:12:22 +00:00
}
2020-11-08 20:09:31 +00:00
static Spanned fromHtml(@NonNull String html, Context context) {
2020-06-28 18:43:20 +00:00
Document document = JsoupEx.parse(html);
2022-11-13 18:53:10 +00:00
return fromDocument(context, document, null, null);
2019-02-10 12:01:21 +00:00
}
2020-06-28 18:43:20 +00:00
static String toHtml(Spanned spanned, Context context) {
HtmlEx converter = new HtmlEx(context);
2020-08-11 16:46:26 +00:00
String html = converter.toHtml(spanned, TO_HTML_PARAGRAPH_LINES_INDIVIDUAL);
2019-05-01 13:58:41 +00:00
2019-10-03 16:19:22 +00:00
Document doc = JsoupEx.parse(html);
2022-01-07 15:56:19 +00:00
2022-06-05 08:28:35 +00:00
if (doc.head().select("meta[name=viewport]").first() == null)
doc.head().prependElement("meta")
.attr("name", "viewport")
.attr("content", "width=device-width, initial-scale=1.0");
2020-10-03 13:53:52 +00:00
for (Element span : doc.select("span")) {
2022-01-07 15:56:19 +00:00
if (span.attr("dir").equals("rtl")) {
Element next = span.nextElementSibling();
if (next != null && next.tagName().equals("br")) {
span.tagName("div");
span.appendElement("br");
next.remove();
}
}
2020-10-03 13:53:52 +00:00
String style = span.attr("style");
2020-10-03 12:04:06 +00:00
if (TextUtils.isEmpty(style))
continue;
StringBuilder sb = new StringBuilder();
String[] params = style.split(";");
for (String param : params) {
int semi = param.indexOf(":");
if (semi < 0) {
sb.append(param).append(';');
continue;
}
String key = param.substring(0, semi).trim();
String value = param.substring(semi + 1).trim();
switch (key) {
case "text-align":
sb.append(" display:block;");
// fall through
default:
sb.append(param).append(';');
}
if (sb.length() == 0)
2020-10-03 13:53:52 +00:00
span.removeAttr("style");
2020-10-03 12:04:06 +00:00
else
2020-10-03 13:53:52 +00:00
span.attr("style", sb.toString());
2019-05-01 13:58:41 +00:00
}
}
2022-01-07 15:56:19 +00:00
for (Element e : doc.select("ol,ul")) {
int ltr = 0;
int rtl = 0;
for (Element li : e.children()) {
if ("rtl".equals(li.attr("dir")))
rtl++;
else
ltr++;
li.removeAttr("dir");
}
e.attr("dir", rtl > ltr ? "rtl" : "ltr");
2022-05-28 08:22:27 +00:00
Element parent = e.parent();
Element prev = e.previousElementSibling();
if (parent != null && !"li".equals(parent.tagName()) &&
prev != null && "li".equals(prev.tagName())) {
e.remove();
prev.appendChild(e);
}
2022-01-07 15:56:19 +00:00
}
2020-10-03 13:54:11 +00:00
for (Element quote : doc.select("blockquote")) {
Element prev = quote.previousElementSibling();
if (prev != null && "br".equals(prev.tagName()))
prev.remove();
Element last = quote.children().last();
if (last != null && "br".equals(last.tagName()))
last.remove();
}
2022-02-04 09:24:30 +00:00
for (Element line : doc.select("hr")) {
Element next = line.nextElementSibling();
if (next != null && "br".equals(next.tagName()))
next.remove();
2022-02-04 09:24:30 +00:00
}
2019-09-23 17:18:21 +00:00
return doc.html();
2019-02-10 12:01:21 +00:00
}
2020-04-23 17:45:33 +00:00
2020-04-24 21:13:32 +00:00
private static Spanned reverseSpans(Spanned spanned) {
2020-04-23 17:45:33 +00:00
Object[] spans = spanned.getSpans(0, spanned.length(), Object.class);
Spannable reverse = Spannable.Factory.getInstance().newSpannable(spanned.toString());
if (spans != null && spans.length > 0)
2020-05-02 20:01:41 +00:00
for (int i = spans.length - 1; i >= 0; i--)
2020-04-23 17:45:33 +00:00
reverse.setSpan(
spans[i],
spanned.getSpanStart(spans[i]),
spanned.getSpanEnd(spans[i]),
spanned.getSpanFlags(spans[i]));
return reverse;
}
interface ImageGetterEx {
Drawable getDrawable(Element element);
}
2018-08-02 13:33:06 +00:00
}