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