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 Spannable 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 Spannable editable, @ColorInt int textColor) {
113 format(editable, textColor, false);
114 }
115
116 public static void format(final Spannable editable, @ColorInt int textColor, final boolean composing) {
117 format(editable, 0, editable.length() - 1, textColor, composing);
118 }
119
120 public static void highlight(
121 final TextView view, final Editable editable, final List<String> needles) {
122 for (final String needle : needles) {
123 if (!FtsUtils.isKeyword(needle)) {
124 highlight(view, editable, needle);
125 }
126 }
127 }
128
129 public static List<String> filterHighlightedWords(List<String> terms) {
130 List<String> words = new ArrayList<>();
131 for (String term : terms) {
132 if (!FtsUtils.isKeyword(term)) {
133 StringBuilder builder = new StringBuilder();
134 for (int codepoint, i = 0; i < term.length(); i += Character.charCount(codepoint)) {
135 codepoint = term.codePointAt(i);
136 if (Character.isLetterOrDigit(codepoint)) {
137 builder.append(Character.toChars(codepoint));
138 } else if (builder.length() > 0) {
139 words.add(builder.toString());
140 builder.delete(0, builder.length());
141 }
142 }
143 if (builder.length() > 0) {
144 words.add(builder.toString());
145 }
146 }
147 }
148 return words;
149 }
150
151 private static void highlight(
152 final TextView view, final Spannable editable, final String needle) {
153 final int length = needle.length();
154 String string = editable.toString();
155 int start = indexOfIgnoreCase(string, needle, 0);
156 while (start != -1) {
157 int end = start + length;
158 editable.setSpan(
159 new BackgroundColorSpan(
160 MaterialColors.getColor(
161 view, com.google.android.material.R.attr.colorPrimaryFixedDim)),
162 start,
163 end,
164 SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
165 editable.setSpan(
166 new ForegroundColorSpan(
167 MaterialColors.getColor(
168 view, com.google.android.material.R.attr.colorOnPrimaryFixed)),
169 start,
170 end,
171 SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
172 start = indexOfIgnoreCase(string, needle, start + length);
173 }
174 }
175
176 static CharSequence subSequence(CharSequence charSequence, int start, int end) {
177 if (start == 0 && charSequence.length() + 1 == end) {
178 return charSequence;
179 }
180 if (charSequence instanceof Spannable spannable) {
181 Spannable sub = (Spannable) spannable.subSequence(start, end);
182 for (Class<? extends ParcelableSpan> clazz : SPAN_CLASSES) {
183 ParcelableSpan[] spannables = spannable.getSpans(start, end, clazz);
184 for (ParcelableSpan parcelableSpan : spannables) {
185 int beginSpan = spannable.getSpanStart(parcelableSpan);
186 int endSpan = spannable.getSpanEnd(parcelableSpan);
187 if (beginSpan >= start && endSpan <= end) {
188 continue;
189 }
190 sub.setSpan(
191 clone(parcelableSpan),
192 Math.max(beginSpan - start, 0),
193 Math.min(sub.length() - 1, endSpan),
194 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
195 }
196 }
197 return sub;
198 } else {
199 return charSequence.subSequence(start, end);
200 }
201 }
202
203 private static ParcelableSpan clone(ParcelableSpan span) {
204 if (span instanceof ForegroundColorSpan) {
205 return new ForegroundColorSpan(((ForegroundColorSpan) span).getForegroundColor());
206 } else if (span instanceof TypefaceSpan) {
207 return new TypefaceSpan(((TypefaceSpan) span).getFamily());
208 } else if (span instanceof StyleSpan) {
209 return new StyleSpan(((StyleSpan) span).getStyle());
210 } else if (span instanceof StrikethroughSpan) {
211 return new StrikethroughSpan();
212 } else {
213 throw new AssertionError("Unknown Span");
214 }
215 }
216
217 private static ParcelableSpan createSpanForStyle(final ImStyleParser.Style style) {
218 return switch (style.getKeyword()) {
219 case "*" -> new StyleSpan(Typeface.BOLD);
220 case "_" -> new StyleSpan(Typeface.ITALIC);
221 case "~" -> new StrikethroughSpan();
222 case "`", "```" -> new TypefaceSpan("monospace");
223 default -> throw new AssertionError("Unknown Style");
224 };
225 }
226
227 private static void makeKeywordOpaque(final Spannable editable, int start, int end, @ColorInt int fallbackTextColor, final boolean composing) {
228 QuoteSpan[] quoteSpans = editable.getSpans(start, end, QuoteSpan.class);
229 @ColorInt int textColor = quoteSpans.length > 0 ? quoteSpans[0].getColor() : fallbackTextColor;
230 @ColorInt int keywordColor = transformColor(textColor);
231 if (composing) {
232 if (end-start > 1) {
233 editable.setSpan(new ForegroundColorSpan(keywordColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | XHTML_REMOVE << Spanned.SPAN_USER_SHIFT);
234 } else {
235 editable.setSpan(new RelativeSizeSpan(0), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | XHTML_REMOVE << Spanned.SPAN_USER_SHIFT);
236 }
237 } else {
238 editable.setSpan(new ForegroundColorSpan(keywordColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
239 }
240 }
241
242 private static @ColorInt int transformColor(@ColorInt int c) {
243 return Color.argb(
244 Math.round(Color.alpha(c) * 0.45f), Color.red(c), Color.green(c), Color.blue(c));
245 }
246
247 private static int indexOfIgnoreCase(
248 final String haystack, final String needle, final int start) {
249 if (haystack == null || needle == null) {
250 return -1;
251 }
252 final int endLimit = haystack.length() - needle.length() + 1;
253 if (start > endLimit) {
254 return -1;
255 }
256 if (needle.length() == 0) {
257 return start;
258 }
259 for (int i = start; i < endLimit; i++) {
260 if (haystack.regionMatches(true, i, needle, 0, needle.length())) {
261 return i;
262 }
263 }
264 return -1;
265 }
266
267 public static class MessageEditorStyler implements TextWatcher {
268
269 private final EditText mEditText;
270 private final MessageAdapter mAdapter;
271
272 public MessageEditorStyler(EditText editText, MessageAdapter adapter) {
273 this.mEditText = editText;
274 this.mAdapter = adapter;
275 }
276
277 @Override
278 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
279
280 @Override
281 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
282
283 @Override
284 public void afterTextChanged(Editable editable) {
285 clear(editable);
286 final var p = PreferenceManager.getDefaultSharedPreferences(mEditText.getContext());
287 if (!p.getBoolean("compose_rich_text", mEditText.getContext().getResources().getBoolean(R.bool.compose_rich_text))) return;
288 for (final var span : editable.getSpans(0, editable.length() - 1, QuoteSpan.class)) {
289 editable.removeSpan(span);
290 }
291 format(editable, mEditText.getCurrentTextColor(), true);
292 mAdapter.handleTextQuotes(mEditText, editable, false);
293 }
294 }
295}