StylingHelper.java

  1/*
  2 * Copyright (c) 2017, 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.content.Context;
 33import android.graphics.Color;
 34import android.graphics.Typeface;
 35import android.preference.PreferenceManager;
 36import android.text.Editable;
 37import android.text.ParcelableSpan;
 38import android.text.Spannable;
 39import android.text.SpannableString;
 40import android.text.Spanned;
 41import android.text.TextWatcher;
 42import android.text.style.BackgroundColorSpan;
 43import android.text.style.ForegroundColorSpan;
 44import android.text.style.RelativeSizeSpan;
 45import android.text.style.StrikethroughSpan;
 46import android.text.style.StyleSpan;
 47import android.text.style.TypefaceSpan;
 48import android.widget.EditText;
 49import android.widget.TextView;
 50
 51import androidx.annotation.ColorInt;
 52import androidx.core.content.ContextCompat;
 53
 54import com.google.android.material.color.MaterialColors;
 55
 56import java.util.ArrayList;
 57import java.util.Arrays;
 58import java.util.List;
 59
 60import eu.siacs.conversations.R;
 61import eu.siacs.conversations.entities.Message;
 62import eu.siacs.conversations.ui.adapter.MessageAdapter;
 63import eu.siacs.conversations.ui.text.QuoteSpan;
 64
 65public class StylingHelper {
 66
 67	public static final int XHTML_IGNORE = 1;
 68	public static final int XHTML_REMOVE = 2;
 69	public static final int XHTML_EMPHASIS = 3;
 70	public static final int XHTML_CODE = 4;
 71	public static final int NOLINKIFY = 0xf0;
 72
 73	private static final List<? extends Class<? extends ParcelableSpan>> SPAN_CLASSES = Arrays.asList(
 74			StyleSpan.class,
 75			StrikethroughSpan.class,
 76			TypefaceSpan.class,
 77			ForegroundColorSpan.class,
 78			RelativeSizeSpan.class
 79	);
 80
 81	public static void clear(final Editable editable) {
 82		final int end = editable.length() - 1;
 83		for (Class<? extends ParcelableSpan> clazz : SPAN_CLASSES) {
 84			for (ParcelableSpan span : editable.getSpans(0, end, clazz)) {
 85				editable.removeSpan(span);
 86			}
 87		}
 88	}
 89
 90	public static void format(final Editable editable, int start, int end, @ColorInt int textColor, final boolean composing) {
 91		for (ImStyleParser.Style style : ImStyleParser.parse(editable, start, end)) {
 92			final int keywordLength = style.getKeyword().length();
 93			int keywordLengthStart = keywordLength;
 94			if ("```".equals(style.getKeyword())) {
 95				int i;
 96				for (i = style.getStart(); i < editable.length(); i++) {
 97					if (editable.charAt(i) == '\n') break;
 98				}
 99				keywordLengthStart = i - style.getStart() + 1;
100			}
101
102			editable.setSpan(
103				createSpanForStyle(style),
104				style.getStart() + keywordLengthStart,
105				style.getEnd() - keywordLength + 1,
106				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE |
107					("*".equals(style.getKeyword()) || "_".equals(style.getKeyword()) ? XHTML_EMPHASIS << Spanned.SPAN_USER_SHIFT : 0) |
108					("```".equals(style.getKeyword()) && keywordLengthStart > 4 ? XHTML_CODE << Spanned.SPAN_USER_SHIFT : 0) |
109					("`".equals(style.getKeyword()) || "```".equals(style.getKeyword()) ? NOLINKIFY << Spanned.SPAN_USER_SHIFT : 0)
110			);
111			makeKeywordOpaque(editable, style.getStart(), style.getStart() + keywordLengthStart, textColor, composing);
112			makeKeywordOpaque(editable, style.getEnd() - keywordLength + 1, style.getEnd() + 1, textColor, composing);
113		}
114	}
115
116	public static void format(final Editable editable, @ColorInt int textColor) {
117		format(editable, textColor, false);
118	}
119
120	public static void format(final Editable editable, @ColorInt int textColor, final boolean composing) {
121		int end = 0;
122		Message.MergeSeparator[] spans = editable.getSpans(0, editable.length() - 1, Message.MergeSeparator.class);
123		for (Message.MergeSeparator span : spans) {
124			format(editable, end, editable.getSpanStart(span), textColor, composing);
125			end = editable.getSpanEnd(span);
126		}
127		format(editable, end, editable.length() - 1, textColor, composing);
128	}
129
130	public static void highlight(final TextView view, final Editable editable, final List<String> needles) {
131		for (final String needle : needles) {
132			if (!FtsUtils.isKeyword(needle)) {
133				highlight(view, editable, needle);
134			}
135		}
136	}
137
138	public static List<String> filterHighlightedWords(List<String> terms) {
139		List<String> words = new ArrayList<>();
140		for (String term : terms) {
141			if (!FtsUtils.isKeyword(term)) {
142				StringBuilder builder = new StringBuilder();
143				for (int codepoint, i = 0; i < term.length(); i += Character.charCount(codepoint)) {
144					codepoint = term.codePointAt(i);
145					if (Character.isLetterOrDigit(codepoint)) {
146						builder.append(Character.toChars(codepoint));
147					} else if (builder.length() > 0) {
148						words.add(builder.toString());
149						builder.delete(0, builder.length());
150					}
151				}
152				if (builder.length() > 0) {
153					words.add(builder.toString());
154				}
155			}
156		}
157		return words;
158	}
159
160	private static void highlight(final TextView view, final Editable editable, final String needle) {
161		final int length = needle.length();
162		String string = editable.toString();
163		int start = indexOfIgnoreCase(string, needle, 0);
164		while (start != -1) {
165			int end = start + length;
166			editable.setSpan(new BackgroundColorSpan(MaterialColors.getColor(view, com.google.android.material.R.attr.colorPrimaryFixedDim)), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
167			editable.setSpan(new ForegroundColorSpan(MaterialColors.getColor(view, com.google.android.material.R.attr.colorOnPrimaryFixed)), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
168			start = indexOfIgnoreCase(string, needle, start + length);
169		}
170
171	}
172
173	static CharSequence subSequence(CharSequence charSequence, int start, int end) {
174		if (start == 0 && charSequence.length() + 1 == end) {
175			return charSequence;
176		}
177		if (charSequence instanceof Spannable spannable) {
178			Spannable sub = (Spannable) spannable.subSequence(start, end);
179			for (Class<? extends ParcelableSpan> clazz : SPAN_CLASSES) {
180				ParcelableSpan[] spannables = spannable.getSpans(start, end, clazz);
181				for (ParcelableSpan parcelableSpan : spannables) {
182					int beginSpan = spannable.getSpanStart(parcelableSpan);
183					int endSpan = spannable.getSpanEnd(parcelableSpan);
184					if (beginSpan >= start && endSpan <= end) {
185						continue;
186					}
187					sub.setSpan(clone(parcelableSpan), Math.max(beginSpan - start, 0), Math.min(Math.max(sub.length() - 1, 0), endSpan), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
188				}
189			}
190			return sub;
191		} else {
192			return charSequence.subSequence(start, end);
193		}
194	}
195
196	private static ParcelableSpan clone(ParcelableSpan span) {
197		if (span instanceof ForegroundColorSpan) {
198			return new ForegroundColorSpan(((ForegroundColorSpan) span).getForegroundColor());
199		} else if (span instanceof TypefaceSpan) {
200			return new TypefaceSpan(((TypefaceSpan) span).getFamily());
201		} else if (span instanceof StyleSpan) {
202			return new StyleSpan(((StyleSpan) span).getStyle());
203		} else if (span instanceof StrikethroughSpan) {
204			return new StrikethroughSpan();
205		} else {
206			throw new AssertionError("Unknown Span");
207		}
208	}
209
210	private static ParcelableSpan createSpanForStyle(final ImStyleParser.Style style) {
211        return switch (style.getKeyword()) {
212            case "*" -> new StyleSpan(Typeface.BOLD);
213            case "_" -> new StyleSpan(Typeface.ITALIC);
214            case "~" -> new StrikethroughSpan();
215            case "`", "```" -> new TypefaceSpan("monospace");
216            default -> throw new AssertionError("Unknown Style");
217        };
218	}
219
220	private static void makeKeywordOpaque(final Editable editable, int start, int end, @ColorInt int fallbackTextColor, final boolean composing) {
221		QuoteSpan[] quoteSpans = editable.getSpans(start, end, QuoteSpan.class);
222		@ColorInt int textColor = quoteSpans.length > 0 ? quoteSpans[0].getColor() : fallbackTextColor;
223		@ColorInt int keywordColor = transformColor(textColor);
224		if (composing) {
225			if (end-start > 1) {
226				editable.setSpan(new ForegroundColorSpan(keywordColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | XHTML_REMOVE << Spanned.SPAN_USER_SHIFT);
227			} else {
228				editable.setSpan(new RelativeSizeSpan(0), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | XHTML_REMOVE << Spanned.SPAN_USER_SHIFT);
229			}
230		} else {
231			editable.setSpan(new ForegroundColorSpan(keywordColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
232		}
233	}
234
235	private static
236	@ColorInt
237	int transformColor(@ColorInt int c) {
238		return Color.argb(Math.round(Color.alpha(c) * 0.45f), Color.red(c), Color.green(c), Color.blue(c));
239	}
240
241	private static int indexOfIgnoreCase(final String haystack, final String needle, final int start) {
242		if (haystack == null || needle == null) {
243			return -1;
244		}
245		final int endLimit = haystack.length() - needle.length() + 1;
246		if (start > endLimit) {
247			return -1;
248		}
249		if (needle.length() == 0) {
250			return start;
251		}
252		for (int i = start; i < endLimit; i++) {
253			if (haystack.regionMatches(true, i, needle, 0, needle.length())) {
254				return i;
255			}
256		}
257		return -1;
258	}
259
260	public static class MessageEditorStyler implements TextWatcher {
261
262		private final EditText mEditText;
263		private final MessageAdapter mAdapter;
264
265		public MessageEditorStyler(EditText editText, MessageAdapter adapter) {
266			this.mEditText = editText;
267			this.mAdapter = adapter;
268		}
269
270		@Override
271		public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
272
273		}
274
275		@Override
276		public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
277
278		}
279
280		@Override
281		public void afterTextChanged(Editable editable) {
282			clear(editable);
283			final var p = PreferenceManager.getDefaultSharedPreferences(mEditText.getContext());
284			if (!p.getBoolean("compose_rich_text", mEditText.getContext().getResources().getBoolean(R.bool.compose_rich_text))) return;
285			for (final var span : editable.getSpans(0, editable.length() - 1, QuoteSpan.class)) {
286				editable.removeSpan(span);
287			}
288			format(editable, mEditText.getCurrentTextColor(), true);
289			mAdapter.handleTextQuotes(mEditText, editable, false);
290		}
291	}
292}