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