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.graphics.Color;
33import android.graphics.Typeface;
34import android.preference.PreferenceManager;
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.RelativeSizeSpan;
44import android.text.style.StrikethroughSpan;
45import android.text.style.StyleSpan;
46import android.text.style.TypefaceSpan;
47import android.widget.EditText;
48import android.widget.TextView;
49import androidx.annotation.ColorInt;
50import com.google.android.material.color.MaterialColors;
51import eu.siacs.conversations.ui.text.QuoteSpan;
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.adapter.MessageAdapter;
59import eu.siacs.conversations.ui.text.QuoteSpan;
60
61public class StylingHelper {
62
63 public static final int XHTML_IGNORE = 1;
64 public static final int XHTML_REMOVE = 2;
65 public static final int XHTML_EMPHASIS = 3;
66 public static final int XHTML_CODE = 4;
67 public static final int NOLINKIFY = 0xf0;
68
69 private static final List<? extends Class<? extends ParcelableSpan>> SPAN_CLASSES =
70 Arrays.asList(
71 StyleSpan.class,
72 StrikethroughSpan.class,
73 TypefaceSpan.class,
74 RelativeSizeSpan.class,
75 ForegroundColorSpan.class);
76
77 public static void clear(final Editable editable) {
78 final int end = editable.length() - 1;
79 for (Class<? extends ParcelableSpan> clazz : SPAN_CLASSES) {
80 for (ParcelableSpan span : editable.getSpans(0, end, clazz)) {
81 editable.removeSpan(span);
82 }
83 }
84 }
85
86 public static void format(final Editable editable, int start, int end, @ColorInt int textColor, final boolean composing) {
87 for (ImStyleParser.Style style : ImStyleParser.parse(editable, start, end)) {
88 final int keywordLength = style.getKeyword().length();
89 int keywordLengthStart = keywordLength;
90 if ("```".equals(style.getKeyword())) {
91 int i;
92 for (i = style.getStart(); i < editable.length(); i++) {
93 if (editable.charAt(i) == '\n') break;
94 }
95 keywordLengthStart = i - style.getStart() + 1;
96 }
97
98 editable.setSpan(
99 createSpanForStyle(style),
100 style.getStart() + keywordLengthStart,
101 style.getEnd() - keywordLength + 1,
102 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE |
103 ("*".equals(style.getKeyword()) || "_".equals(style.getKeyword()) ? XHTML_EMPHASIS << Spanned.SPAN_USER_SHIFT : 0) |
104 ("```".equals(style.getKeyword()) && keywordLengthStart > 4 ? XHTML_CODE << Spanned.SPAN_USER_SHIFT : 0) |
105 ("`".equals(style.getKeyword()) || "```".equals(style.getKeyword()) ? NOLINKIFY << Spanned.SPAN_USER_SHIFT : 0)
106 );
107 makeKeywordOpaque(editable, style.getStart(), style.getStart() + keywordLengthStart, textColor, composing);
108 makeKeywordOpaque(editable, style.getEnd() - keywordLength + 1, style.getEnd() + 1, textColor, composing);
109 }
110 }
111
112 public static void format(final Editable editable, @ColorInt int textColor) {
113 format(editable, textColor, false);
114 }
115
116 public static void format(final Editable editable, @ColorInt int textColor, final boolean composing) {
117 int end = 0;
118 format(editable, end, editable.length() - 1, textColor, composing);
119 }
120
121 public static void highlight(
122 final TextView view, final Editable editable, final List<String> needles) {
123 for (final String needle : needles) {
124 if (!FtsUtils.isKeyword(needle)) {
125 highlight(view, editable, needle);
126 }
127 }
128 }
129
130 public static List<String> filterHighlightedWords(List<String> terms) {
131 List<String> words = new ArrayList<>();
132 for (String term : terms) {
133 if (!FtsUtils.isKeyword(term)) {
134 StringBuilder builder = new StringBuilder();
135 for (int codepoint, i = 0; i < term.length(); i += Character.charCount(codepoint)) {
136 codepoint = term.codePointAt(i);
137 if (Character.isLetterOrDigit(codepoint)) {
138 builder.append(Character.toChars(codepoint));
139 } else if (builder.length() > 0) {
140 words.add(builder.toString());
141 builder.delete(0, builder.length());
142 }
143 }
144 if (builder.length() > 0) {
145 words.add(builder.toString());
146 }
147 }
148 }
149 return words;
150 }
151
152 private static void highlight(
153 final TextView view, final Editable editable, final String needle) {
154 final int length = needle.length();
155 String string = editable.toString();
156 int start = indexOfIgnoreCase(string, needle, 0);
157 while (start != -1) {
158 int end = start + length;
159 editable.setSpan(
160 new BackgroundColorSpan(
161 MaterialColors.getColor(
162 view, com.google.android.material.R.attr.colorPrimaryFixedDim)),
163 start,
164 end,
165 SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
166 editable.setSpan(
167 new ForegroundColorSpan(
168 MaterialColors.getColor(
169 view, com.google.android.material.R.attr.colorOnPrimaryFixed)),
170 start,
171 end,
172 SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
173 start = indexOfIgnoreCase(string, needle, start + length);
174 }
175 }
176
177 static CharSequence subSequence(CharSequence charSequence, int start, int end) {
178 if (start == 0 && charSequence.length() + 1 == end) {
179 return charSequence;
180 }
181 if (charSequence instanceof Spannable spannable) {
182 Spannable sub = (Spannable) spannable.subSequence(start, end);
183 for (Class<? extends ParcelableSpan> clazz : SPAN_CLASSES) {
184 ParcelableSpan[] spannables = spannable.getSpans(start, end, clazz);
185 for (ParcelableSpan parcelableSpan : spannables) {
186 int beginSpan = spannable.getSpanStart(parcelableSpan);
187 int endSpan = spannable.getSpanEnd(parcelableSpan);
188 if (beginSpan >= start && endSpan <= end) {
189 continue;
190 }
191 sub.setSpan(
192 clone(parcelableSpan),
193 Math.max(beginSpan - start, 0),
194 Math.min(sub.length() - 1, endSpan),
195 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
196 }
197 }
198 return sub;
199 } else {
200 return charSequence.subSequence(start, end);
201 }
202 }
203
204 private static ParcelableSpan clone(ParcelableSpan span) {
205 if (span instanceof ForegroundColorSpan) {
206 return new ForegroundColorSpan(((ForegroundColorSpan) span).getForegroundColor());
207 } else if (span instanceof TypefaceSpan) {
208 return new TypefaceSpan(((TypefaceSpan) span).getFamily());
209 } else if (span instanceof StyleSpan) {
210 return new StyleSpan(((StyleSpan) span).getStyle());
211 } else if (span instanceof StrikethroughSpan) {
212 return new StrikethroughSpan();
213 } else {
214 throw new AssertionError("Unknown Span");
215 }
216 }
217
218 private static ParcelableSpan createSpanForStyle(final ImStyleParser.Style style) {
219 return switch (style.getKeyword()) {
220 case "*" -> new StyleSpan(Typeface.BOLD);
221 case "_" -> new StyleSpan(Typeface.ITALIC);
222 case "~" -> new StrikethroughSpan();
223 case "`", "```" -> new TypefaceSpan("monospace");
224 default -> throw new AssertionError("Unknown Style");
225 };
226 }
227
228 private static void makeKeywordOpaque(final Editable editable, int start, int end, @ColorInt int fallbackTextColor, final boolean composing) {
229 QuoteSpan[] quoteSpans = editable.getSpans(start, end, QuoteSpan.class);
230 @ColorInt int textColor = quoteSpans.length > 0 ? quoteSpans[0].getColor() : fallbackTextColor;
231 @ColorInt int keywordColor = transformColor(textColor);
232 if (composing) {
233 if (end-start > 1) {
234 editable.setSpan(new ForegroundColorSpan(keywordColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | XHTML_REMOVE << Spanned.SPAN_USER_SHIFT);
235 } else {
236 editable.setSpan(new RelativeSizeSpan(0), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | XHTML_REMOVE << Spanned.SPAN_USER_SHIFT);
237 }
238 } else {
239 editable.setSpan(new ForegroundColorSpan(keywordColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
240 }
241 }
242
243 private static @ColorInt int transformColor(@ColorInt int c) {
244 return Color.argb(
245 Math.round(Color.alpha(c) * 0.45f), Color.red(c), Color.green(c), Color.blue(c));
246 }
247
248 private static int indexOfIgnoreCase(
249 final String haystack, final String needle, final int start) {
250 if (haystack == null || needle == null) {
251 return -1;
252 }
253 final int endLimit = haystack.length() - needle.length() + 1;
254 if (start > endLimit) {
255 return -1;
256 }
257 if (needle.length() == 0) {
258 return start;
259 }
260 for (int i = start; i < endLimit; i++) {
261 if (haystack.regionMatches(true, i, needle, 0, needle.length())) {
262 return i;
263 }
264 }
265 return -1;
266 }
267
268 public static class MessageEditorStyler implements TextWatcher {
269
270 private final EditText mEditText;
271 private final MessageAdapter mAdapter;
272
273 public MessageEditorStyler(EditText editText, MessageAdapter adapter) {
274 this.mEditText = editText;
275 this.mAdapter = adapter;
276 }
277
278 @Override
279 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
280
281 @Override
282 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
283
284 @Override
285 public void afterTextChanged(Editable editable) {
286 clear(editable);
287 final var p = PreferenceManager.getDefaultSharedPreferences(mEditText.getContext());
288 if (!p.getBoolean("compose_rich_text", mEditText.getContext().getResources().getBoolean(R.bool.compose_rich_text))) return;
289 for (final var span : editable.getSpans(0, editable.length() - 1, QuoteSpan.class)) {
290 editable.removeSpan(span);
291 }
292 format(editable, mEditText.getCurrentTextColor(), true);
293 mAdapter.handleTextQuotes(mEditText, editable, false);
294 }
295 }
296}