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