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