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