IrregularUnicodeBlockDetector.java

  1/*
  2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
  3 *
  4 * Redistribution and use in source and binary forms, with or without modification,
  5 * are permitted provided that the following conditions are met:
  6 *
  7 * 1. Redistributions of source code must retain the above copyright notice, this
  8 * list of conditions and the following disclaimer.
  9 *
 10 * 2. Redistributions in binary form must reproduce the above copyright notice,
 11 * this list of conditions and the following disclaimer in the documentation and/or
 12 * other materials provided with the distribution.
 13 *
 14 * 3. Neither the name of the copyright holder nor the names of its contributors
 15 * may be used to endorse or promote products derived from this software without
 16 * specific prior written permission.
 17 *
 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 28 */
 29
 30package eu.siacs.conversations.utils;
 31
 32import android.annotation.TargetApi;
 33import android.content.Context;
 34import android.os.Build;
 35import android.support.annotation.ColorInt;
 36import android.text.Spannable;
 37import android.text.SpannableString;
 38import android.text.SpannableStringBuilder;
 39import android.text.style.ForegroundColorSpan;
 40import android.util.LruCache;
 41
 42import java.util.ArrayList;
 43import java.util.Collections;
 44import java.util.HashMap;
 45import java.util.HashSet;
 46import java.util.List;
 47import java.util.Map;
 48import java.util.Set;
 49import java.util.regex.Matcher;
 50import java.util.regex.Pattern;
 51
 52import eu.siacs.conversations.R;
 53import eu.siacs.conversations.ui.util.Color;
 54import rocks.xmpp.addr.Jid;
 55
 56public class IrregularUnicodeBlockDetector {
 57
 58	private static final Map<Character.UnicodeBlock, Character.UnicodeBlock> NORMALIZATION_MAP;
 59
 60	static {
 61		Map<Character.UnicodeBlock, Character.UnicodeBlock> temp = new HashMap<>();
 62		temp.put(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.BASIC_LATIN);
 63		NORMALIZATION_MAP = Collections.unmodifiableMap(temp);
 64	}
 65
 66	private static Character.UnicodeBlock normalize(Character.UnicodeBlock in) {
 67		if (NORMALIZATION_MAP.containsKey(in)) {
 68			return NORMALIZATION_MAP.get(in);
 69		} else {
 70			return in;
 71		}
 72	}
 73
 74	private static final LruCache<Jid, Pattern> CACHE = new LruCache<>(100);
 75
 76	public static Spannable style(Context context, Jid jid) {
 77		return style(jid, Color.get(context, R.attr.color_warning));
 78	}
 79
 80	private static Spannable style(Jid jid, @ColorInt int color) {
 81		SpannableStringBuilder builder = new SpannableStringBuilder();
 82		if (jid.getLocal() != null) {
 83			SpannableString local = new SpannableString(jid.getLocal());
 84			Matcher matcher = find(jid).matcher(local);
 85			while (matcher.find()) {
 86				if (matcher.start() < matcher.end()) {
 87					local.setSpan(new ForegroundColorSpan(color), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 88				}
 89			}
 90			builder.append(local);
 91			builder.append('@');
 92		}
 93		if (jid.getDomain() != null) {
 94			builder.append(jid.getDomain());
 95		}
 96		if (builder.length() != 0 && jid.getResource() != null) {
 97			builder.append('/');
 98			builder.append(jid.getResource());
 99		}
100		return builder;
101	}
102
103	private static Map<Character.UnicodeBlock, List<String>> mapCompat(Jid jid) {
104		Map<Character.UnicodeBlock, List<String>> map = new HashMap<>();
105		String local = jid.getLocal();
106		final int length = local.length();
107		for (int offset = 0; offset < length; ) {
108			final int codePoint = local.codePointAt(offset);
109			Character.UnicodeBlock block = normalize(Character.UnicodeBlock.of(codePoint));
110			List<String> codePoints;
111			if (map.containsKey(block)) {
112				codePoints = map.get(block);
113			} else {
114				codePoints = new ArrayList<>();
115				map.put(block, codePoints);
116			}
117			codePoints.add(String.copyValueOf(Character.toChars(codePoint)));
118			offset += Character.charCount(codePoint);
119		}
120		return map;
121	}
122
123	@TargetApi(Build.VERSION_CODES.N)
124	private static Map<Character.UnicodeScript, List<String>> map(Jid jid) {
125		Map<Character.UnicodeScript, List<String>> map = new HashMap<>();
126		String local = jid.getLocal();
127		final int length = local.length();
128		for (int offset = 0; offset < length; ) {
129			final int codePoint = local.codePointAt(offset);
130			Character.UnicodeScript script = Character.UnicodeScript.of(codePoint);
131			if (script != Character.UnicodeScript.COMMON) {
132				List<String> codePoints;
133				if (map.containsKey(script)) {
134					codePoints = map.get(script);
135				} else {
136					codePoints = new ArrayList<>();
137					map.put(script, codePoints);
138				}
139				codePoints.add(String.copyValueOf(Character.toChars(codePoint)));
140			}
141			offset += Character.charCount(codePoint);
142		}
143		return map;
144	}
145
146	private static Set<String> eliminateFirstAndGetCodePointsCompat(Map<Character.UnicodeBlock, List<String>> map) {
147		return eliminateFirstAndGetCodePoints(map, Character.UnicodeBlock.BASIC_LATIN);
148	}
149
150	@TargetApi(Build.VERSION_CODES.N)
151	private static Set<String> eliminateFirstAndGetCodePoints(Map<Character.UnicodeScript, List<String>> map) {
152		return eliminateFirstAndGetCodePoints(map, Character.UnicodeScript.COMMON);
153	}
154
155	private static <T> Set<String> eliminateFirstAndGetCodePoints(Map<T, List<String>> map, T defaultPick) {
156		T pick = defaultPick;
157		int size = 0;
158		for (Map.Entry<T, List<String>> entry : map.entrySet()) {
159			if (entry.getValue().size() > size) {
160				size = entry.getValue().size();
161				pick = entry.getKey();
162			}
163		}
164		map.remove(pick);
165		Set<String> all = new HashSet<>();
166		for (List<String> codePoints : map.values()) {
167			all.addAll(codePoints);
168		}
169		return all;
170	}
171
172	private static Pattern find(Jid jid) {
173		synchronized (CACHE) {
174			Pattern pattern = CACHE.get(jid);
175			if (pattern != null) {
176				return pattern;
177			}
178			Set<String> codePoints;
179			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
180				codePoints = eliminateFirstAndGetCodePointsCompat(mapCompat(jid));
181			} else {
182				codePoints = eliminateFirstAndGetCodePoints(map(jid));
183			}
184			pattern = create(codePoints);
185			CACHE.put(jid, pattern);
186			return pattern;
187		}
188	}
189
190	private static Pattern create(Set<String> codePoints) {
191		final StringBuilder pattern = new StringBuilder();
192		for (String codePoint : codePoints) {
193			if (pattern.length() != 0) {
194				pattern.append('|');
195			}
196			pattern.append(Pattern.quote(codePoint));
197		}
198		return Pattern.compile(pattern.toString());
199	}
200}