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.RelativeSizeSpan;
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 androidx.annotation.ColorInt;
51import androidx.core.content.ContextCompat;
52
53import com.google.android.material.color.MaterialColors;
54
55import java.util.ArrayList;
56import java.util.Arrays;
57import java.util.List;
58
59import eu.siacs.conversations.R;
60import eu.siacs.conversations.entities.Message;
61import eu.siacs.conversations.ui.adapter.MessageAdapter;
62import eu.siacs.conversations.ui.text.QuoteSpan;
63
64public class StylingHelper {
65
66 public static final int XHTML_IGNORE = 1;
67 public static final int XHTML_REMOVE = 2;
68 public static final int XHTML_EMPHASIS = 3;
69
70 private static final List<? extends Class<? extends ParcelableSpan>> SPAN_CLASSES = Arrays.asList(
71 StyleSpan.class,
72 StrikethroughSpan.class,
73 TypefaceSpan.class,
74 ForegroundColorSpan.class
75 );
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 editable.setSpan(createSpanForStyle(style), style.getStart() + keywordLength, style.getEnd() - keywordLength + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | ("*".equals(style.getKeyword()) || "_".equals(style.getKeyword()) ? XHTML_EMPHASIS << Spanned.SPAN_USER_SHIFT : 0));
90 makeKeywordOpaque(editable, style.getStart(), style.getStart() + keywordLength + ("```".equals(style.getKeyword()) ? 1 : 0), textColor, composing);
91 makeKeywordOpaque(editable, style.getEnd() - keywordLength + 1, style.getEnd() + 1, textColor, composing);
92 }
93 }
94
95 public static void format(final Editable editable, @ColorInt int textColor) {
96 format(editable, textColor, false);
97 }
98
99 public static void format(final Editable editable, @ColorInt int textColor, final boolean composing) {
100 int end = 0;
101 Message.MergeSeparator[] spans = editable.getSpans(0, editable.length() - 1, Message.MergeSeparator.class);
102 for (Message.MergeSeparator span : spans) {
103 format(editable, end, editable.getSpanStart(span), textColor, composing);
104 end = editable.getSpanEnd(span);
105 }
106 format(editable, end, editable.length() - 1, textColor, composing);
107 }
108
109 public static void highlight(final TextView view, final Editable editable, final List<String> needles) {
110 for (final String needle : needles) {
111 if (!FtsUtils.isKeyword(needle)) {
112 highlight(view, editable, needle);
113 }
114 }
115 }
116
117 public static List<String> filterHighlightedWords(List<String> terms) {
118 List<String> words = new ArrayList<>();
119 for (String term : terms) {
120 if (!FtsUtils.isKeyword(term)) {
121 StringBuilder builder = new StringBuilder();
122 for (int codepoint, i = 0; i < term.length(); i += Character.charCount(codepoint)) {
123 codepoint = term.codePointAt(i);
124 if (Character.isLetterOrDigit(codepoint)) {
125 builder.append(Character.toChars(codepoint));
126 } else if (builder.length() > 0) {
127 words.add(builder.toString());
128 builder.delete(0, builder.length());
129 }
130 }
131 if (builder.length() > 0) {
132 words.add(builder.toString());
133 }
134 }
135 }
136 return words;
137 }
138
139 private static void highlight(final TextView view, final Editable editable, final String needle) {
140 final int length = needle.length();
141 String string = editable.toString();
142 int start = indexOfIgnoreCase(string, needle, 0);
143 while (start != -1) {
144 int end = start + length;
145 editable.setSpan(new BackgroundColorSpan(MaterialColors.getColor(view, com.google.android.material.R.attr.colorPrimaryFixedDim)), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
146 editable.setSpan(new ForegroundColorSpan(MaterialColors.getColor(view, com.google.android.material.R.attr.colorOnPrimaryFixed)), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
147 start = indexOfIgnoreCase(string, needle, start + length);
148 }
149
150 }
151
152 static CharSequence subSequence(CharSequence charSequence, int start, int end) {
153 if (start == 0 && charSequence.length() + 1 == end) {
154 return charSequence;
155 }
156 if (charSequence instanceof Spannable spannable) {
157 Spannable sub = (Spannable) spannable.subSequence(start, end);
158 for (Class<? extends ParcelableSpan> clazz : SPAN_CLASSES) {
159 ParcelableSpan[] spannables = spannable.getSpans(start, end, clazz);
160 for (ParcelableSpan parcelableSpan : spannables) {
161 int beginSpan = spannable.getSpanStart(parcelableSpan);
162 int endSpan = spannable.getSpanEnd(parcelableSpan);
163 if (beginSpan >= start && endSpan <= end) {
164 continue;
165 }
166 sub.setSpan(clone(parcelableSpan), Math.max(beginSpan - start, 0), Math.min(Math.max(sub.length() - 1, 0), endSpan), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
167 }
168 }
169 return sub;
170 } else {
171 return charSequence.subSequence(start, end);
172 }
173 }
174
175 private static ParcelableSpan clone(ParcelableSpan span) {
176 if (span instanceof ForegroundColorSpan) {
177 return new ForegroundColorSpan(((ForegroundColorSpan) span).getForegroundColor());
178 } else if (span instanceof TypefaceSpan) {
179 return new TypefaceSpan(((TypefaceSpan) span).getFamily());
180 } else if (span instanceof StyleSpan) {
181 return new StyleSpan(((StyleSpan) span).getStyle());
182 } else if (span instanceof StrikethroughSpan) {
183 return new StrikethroughSpan();
184 } else {
185 throw new AssertionError("Unknown Span");
186 }
187 }
188
189 private static ParcelableSpan createSpanForStyle(final ImStyleParser.Style style) {
190 return switch (style.getKeyword()) {
191 case "*" -> new StyleSpan(Typeface.BOLD);
192 case "_" -> new StyleSpan(Typeface.ITALIC);
193 case "~" -> new StrikethroughSpan();
194 case "`", "```" -> new TypefaceSpan("monospace");
195 default -> throw new AssertionError("Unknown Style");
196 };
197 }
198
199 private static void makeKeywordOpaque(final Editable editable, int start, int end, @ColorInt int fallbackTextColor, final boolean composing) {
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 | (composing ? XHTML_REMOVE << Spanned.SPAN_USER_SHIFT : 0));
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 private final MessageAdapter mAdapter;
235
236 public MessageEditorStyler(EditText editText, MessageAdapter adapter) {
237 this.mEditText = editText;
238 this.mAdapter = adapter;
239 }
240
241 @Override
242 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
243
244 }
245
246 @Override
247 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
248
249 }
250
251 @Override
252 public void afterTextChanged(Editable editable) {
253 clear(editable);
254 for (final var span : editable.getSpans(0, editable.length() - 1, QuoteSpan.class)) {
255 editable.removeSpan(span);
256 }
257 for (final var span : editable.getSpans(0, editable.length() - 1, RelativeSizeSpan.class)) {
258 editable.removeSpan(span);
259 }
260 format(editable, mEditText.getCurrentTextColor(), true);
261 mAdapter.handleTextQuotes(mEditText, editable, false);
262 }
263 }
264}