1package eu.siacs.conversations.ui.adapter;
2
3import android.Manifest;
4import android.app.Activity;
5import android.content.Intent;
6import android.content.pm.PackageManager;
7import android.graphics.PorterDuff;
8import android.graphics.drawable.Drawable;
9import android.content.res.ColorStateList;
10import android.graphics.Typeface;
11import android.net.Uri;
12import android.os.AsyncTask;
13import android.os.Build;
14import android.preference.PreferenceManager;
15import android.text.Editable;
16import android.text.Spanned;
17import android.text.Spannable;
18import android.text.SpannableString;
19import android.text.SpannableStringBuilder;
20import android.text.style.ImageSpan;
21import android.text.style.ClickableSpan;
22import android.text.format.DateUtils;
23import android.text.style.ForegroundColorSpan;
24import android.text.style.RelativeSizeSpan;
25import android.text.style.StyleSpan;
26import android.text.style.URLSpan;
27import android.util.DisplayMetrics;
28import android.util.LruCache;
29import android.view.accessibility.AccessibilityEvent;
30import android.view.Gravity;
31import android.view.MotionEvent;
32import android.view.View;
33import android.view.ViewGroup;
34import android.view.WindowManager;
35import android.widget.ArrayAdapter;
36import android.widget.ImageView;
37import android.widget.LinearLayout;
38import android.widget.ListAdapter;
39import android.widget.ListView;
40import android.widget.RelativeLayout;
41import android.widget.TextView;
42import android.widget.Toast;
43
44import androidx.annotation.AttrRes;
45import androidx.annotation.ColorInt;
46import androidx.annotation.DrawableRes;
47import androidx.annotation.NonNull;
48import androidx.annotation.Nullable;
49import androidx.core.app.ActivityCompat;
50import androidx.core.content.ContextCompat;
51import androidx.core.content.res.ResourcesCompat;
52import androidx.core.widget.ImageViewCompat;
53
54import com.google.android.material.imageview.ShapeableImageView;
55import com.google.android.material.shape.CornerFamily;
56import com.google.android.material.shape.ShapeAppearanceModel;
57
58import com.cheogram.android.BobTransfer;
59import com.cheogram.android.MessageTextActionModeCallback;
60import com.cheogram.android.SwipeDetector;
61import com.cheogram.android.WebxdcPage;
62import com.cheogram.android.WebxdcUpdate;
63
64import com.google.android.material.button.MaterialButton;
65import com.google.android.material.color.MaterialColors;
66import com.google.common.base.Joiner;
67import com.google.common.base.Strings;
68import com.google.common.collect.ImmutableList;
69
70import com.lelloman.identicon.view.GithubIdenticonView;
71
72import io.ipfs.cid.Cid;
73
74import java.io.IOException;
75import java.net.URI;
76import java.net.URISyntaxException;
77import java.security.NoSuchAlgorithmException;
78import java.util.HashMap;
79import java.util.List;
80import java.util.Map;
81import java.util.Locale;
82import java.util.regex.Matcher;
83import java.util.regex.Pattern;
84
85import me.saket.bettermovementmethod.BetterLinkMovementMethod;
86
87import net.fellbaum.jemoji.EmojiManager;
88
89import eu.siacs.conversations.AppSettings;
90import eu.siacs.conversations.Config;
91import eu.siacs.conversations.R;
92import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
93import eu.siacs.conversations.entities.Account;
94import eu.siacs.conversations.entities.Contact;
95import eu.siacs.conversations.entities.Conversation;
96import eu.siacs.conversations.entities.Conversational;
97import eu.siacs.conversations.entities.DownloadableFile;
98import eu.siacs.conversations.entities.Message.FileParams;
99import eu.siacs.conversations.entities.Message;
100import eu.siacs.conversations.entities.MucOptions;
101import eu.siacs.conversations.entities.Roster;
102import eu.siacs.conversations.entities.RtpSessionStatus;
103import eu.siacs.conversations.entities.Transferable;
104import eu.siacs.conversations.persistance.FileBackend;
105import eu.siacs.conversations.services.MessageArchiveService;
106import eu.siacs.conversations.services.NotificationService;
107import eu.siacs.conversations.ui.Activities;
108import eu.siacs.conversations.ui.ConversationFragment;
109import eu.siacs.conversations.ui.ConversationsActivity;
110import eu.siacs.conversations.ui.XmppActivity;
111import eu.siacs.conversations.ui.service.AudioPlayer;
112import eu.siacs.conversations.ui.text.DividerSpan;
113import eu.siacs.conversations.ui.text.QuoteSpan;
114import eu.siacs.conversations.ui.util.Attachment;
115import eu.siacs.conversations.ui.util.AvatarWorkerTask;
116import eu.siacs.conversations.ui.util.MyLinkify;
117import eu.siacs.conversations.ui.util.QuoteHelper;
118import eu.siacs.conversations.ui.util.ShareUtil;
119import eu.siacs.conversations.ui.util.ViewUtil;
120import eu.siacs.conversations.utils.CryptoHelper;
121import eu.siacs.conversations.utils.Emoticons;
122import eu.siacs.conversations.utils.GeoHelper;
123import eu.siacs.conversations.utils.MessageUtils;
124import eu.siacs.conversations.utils.StylingHelper;
125import eu.siacs.conversations.utils.TimeFrameUtils;
126import eu.siacs.conversations.utils.UIHelper;
127import eu.siacs.conversations.xmpp.Jid;
128import eu.siacs.conversations.xmpp.mam.MamReference;
129import eu.siacs.conversations.xml.Element;
130
131import java.net.URI;
132import java.util.Arrays;
133import java.util.Collection;
134import java.util.List;
135import java.util.Locale;
136import java.util.regex.Matcher;
137import java.util.regex.Pattern;
138
139public class MessageAdapter extends ArrayAdapter<Message> {
140
141 public static final String DATE_SEPARATOR_BODY = "DATE_SEPARATOR";
142 private static final int SENT = 0;
143 private static final int RECEIVED = 1;
144 private static final int STATUS = 2;
145 private static final int DATE_SEPARATOR = 3;
146 private static final int RTP_SESSION = 4;
147 private final XmppActivity activity;
148 private final AudioPlayer audioPlayer;
149 private List<String> highlightedTerm = null;
150 private final DisplayMetrics metrics;
151 private ConversationFragment mConversationFragment = null;
152 private OnContactPictureClicked mOnContactPictureClickedListener;
153 private OnContactPictureClicked mOnMessageBoxClickedListener;
154 private OnContactPictureClicked mOnMessageBoxSwipedListener;
155 private OnContactPictureLongClicked mOnContactPictureLongClickedListener;
156 private OnInlineImageLongClicked mOnInlineImageLongClickedListener;
157 private boolean mUseGreenBackground = false;
158 private BubbleDesign bubbleDesign = new BubbleDesign(false, false);
159 private final boolean mForceNames;
160 private final Map<String, WebxdcUpdate> lastWebxdcUpdate = new HashMap<>();
161 private String selectionUuid = null;
162
163 public MessageAdapter(
164 final XmppActivity activity, final List<Message> messages, final boolean forceNames) {
165 super(activity, 0, messages);
166 this.audioPlayer = new AudioPlayer(this);
167 this.activity = activity;
168 metrics = getContext().getResources().getDisplayMetrics();
169 updatePreferences();
170 this.mForceNames = forceNames;
171 }
172
173 public MessageAdapter(final XmppActivity activity, final List<Message> messages) {
174 this(activity, messages, false);
175 }
176
177 private static void resetClickListener(View... views) {
178 for (View view : views) {
179 if (view != null) view.setOnClickListener(null);
180 }
181 }
182
183 public void flagScreenOn() {
184 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
185 }
186
187 public void flagScreenOff() {
188 activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
189 }
190
191 public void setVolumeControl(final int stream) {
192 activity.setVolumeControlStream(stream);
193 }
194
195 public void setOnContactPictureClicked(OnContactPictureClicked listener) {
196 this.mOnContactPictureClickedListener = listener;
197 }
198
199 public void setOnMessageBoxClicked(OnContactPictureClicked listener) {
200 this.mOnMessageBoxClickedListener = listener;
201 }
202
203 public void setOnMessageBoxSwiped(OnContactPictureClicked listener) {
204 this.mOnMessageBoxSwipedListener = listener;
205 }
206
207 public void setConversationFragment(ConversationFragment frag) {
208 mConversationFragment = frag;
209 }
210
211 public void quoteText(String text) {
212 if (mConversationFragment != null) mConversationFragment.quoteText(text);
213 }
214
215 public boolean hasSelection() {
216 return selectionUuid != null;
217 }
218
219 public Activity getActivity() {
220 return activity;
221 }
222
223 public void setOnContactPictureLongClicked(OnContactPictureLongClicked listener) {
224 this.mOnContactPictureLongClickedListener = listener;
225 }
226
227 public void setOnInlineImageLongClicked(OnInlineImageLongClicked listener) {
228 this.mOnInlineImageLongClickedListener = listener;
229 }
230
231 @Override
232 public int getViewTypeCount() {
233 return 5;
234 }
235
236 private int getItemViewType(Message message) {
237 if (message.getType() == Message.TYPE_STATUS) {
238 if (DATE_SEPARATOR_BODY.equals(message.getBody())) {
239 return DATE_SEPARATOR;
240 } else {
241 return STATUS;
242 }
243 } else if (message.getType() == Message.TYPE_RTP_SESSION) {
244 return RTP_SESSION;
245 } else if (message.getStatus() <= Message.STATUS_RECEIVED) {
246 return RECEIVED;
247 } else {
248 return SENT;
249 }
250 }
251
252 @Override
253 public int getItemViewType(int position) {
254 return this.getItemViewType(getItem(position));
255 }
256
257 private void displayStatus(
258 final ViewHolder viewHolder,
259 final Message message,
260 final int type,
261 final BubbleColor bubbleColor) {
262 final int mergedStatus = message.getMergedStatus();
263 final boolean error;
264 if (viewHolder.indicatorReceived != null) {
265 viewHolder.indicatorReceived.setVisibility(View.GONE);
266 }
267 final Transferable transferable = message.getTransferable();
268 final boolean multiReceived =
269 message.getConversation().getMode() == Conversation.MODE_MULTI
270 && mergedStatus <= Message.STATUS_RECEIVED;
271 final String fileSize;
272 if (message.isFileOrImage()
273 || transferable != null
274 || MessageUtils.unInitiatedButKnownSize(message)) {
275 final FileParams params = message.getFileParams();
276 fileSize = params.size != null ? UIHelper.filesizeToString(params.size) : null;
277 if (message.getStatus() == Message.STATUS_SEND_FAILED
278 || (transferable != null
279 && (transferable.getStatus() == Transferable.STATUS_FAILED
280 || transferable.getStatus()
281 == Transferable.STATUS_CANCELLED))) {
282 error = true;
283 } else {
284 error = message.getStatus() == Message.STATUS_SEND_FAILED;
285 }
286 } else {
287 fileSize = null;
288 error = message.getStatus() == Message.STATUS_SEND_FAILED;
289 }
290 if (type == SENT) {
291 final @DrawableRes Integer receivedIndicator =
292 getMessageStatusAsDrawable(message, mergedStatus);
293 if (receivedIndicator == null) {
294 viewHolder.indicatorReceived.setVisibility(View.INVISIBLE);
295 } else {
296 viewHolder.indicatorReceived.setImageResource(receivedIndicator);
297 if (mergedStatus == Message.STATUS_SEND_FAILED) {
298 setImageTintError(viewHolder.indicatorReceived);
299 } else {
300 setImageTint(viewHolder.indicatorReceived, bubbleColor);
301 }
302 viewHolder.indicatorReceived.setVisibility(View.VISIBLE);
303 }
304 }
305 final var additionalStatusInfo = getAdditionalStatusInfo(message, mergedStatus);
306
307 if (error && type == SENT) {
308 viewHolder.time.setTextColor(
309 MaterialColors.getColor(
310 viewHolder.time, com.google.android.material.R.attr.colorError));
311 } else {
312 setTextColor(viewHolder.time, bubbleColor);
313 }
314 setTextColor(viewHolder.subject, bubbleColor);
315 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
316 viewHolder.indicator.setVisibility(View.GONE);
317 } else {
318 boolean verified = false;
319 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
320 final FingerprintStatus status =
321 message.getConversation()
322 .getAccount()
323 .getAxolotlService()
324 .getFingerprintTrust(message.getFingerprint());
325 if (status != null && status.isVerified()) {
326 verified = true;
327 }
328 }
329 if (verified) {
330 viewHolder.indicator.setImageResource(R.drawable.ic_verified_user_24dp);
331 } else {
332 viewHolder.indicator.setImageResource(R.drawable.ic_lock_24dp);
333 }
334 if (error && type == SENT) {
335 setImageTintError(viewHolder.indicator);
336 } else {
337 setImageTint(viewHolder.indicator, bubbleColor);
338 }
339 viewHolder.indicator.setVisibility(View.VISIBLE);
340 }
341
342 if (viewHolder.edit_indicator != null) {
343 if (message.edited()) {
344 viewHolder.edit_indicator.setVisibility(View.VISIBLE);
345 if (error && type == SENT) {
346 setImageTintError(viewHolder.edit_indicator);
347 } else {
348 setImageTint(viewHolder.edit_indicator, bubbleColor);
349 }
350 } else {
351 viewHolder.edit_indicator.setVisibility(View.GONE);
352 }
353 }
354
355 final String formattedTime =
356 UIHelper.readableTimeDifferenceFull(getContext(), message.getMergedTimeSent());
357 final String bodyLanguage = message.getBodyLanguage();
358 final ImmutableList.Builder<String> timeInfoBuilder = new ImmutableList.Builder<>();
359 if (message.getStatus() <= Message.STATUS_RECEIVED) {
360 timeInfoBuilder.add(formattedTime);
361 if (fileSize != null) {
362 timeInfoBuilder.add(fileSize);
363 }
364 if (mForceNames || multiReceived || (message.getTrueCounterpart() != null && message.getContact() != null)) {
365 final String displayName = UIHelper.getMessageDisplayName(message);
366 if (displayName != null) {
367 timeInfoBuilder.add(displayName);
368 }
369 }
370 if (bodyLanguage != null) {
371 timeInfoBuilder.add(bodyLanguage.toUpperCase(Locale.US));
372 }
373 } else {
374 if (bodyLanguage != null) {
375 timeInfoBuilder.add(bodyLanguage.toUpperCase(Locale.US));
376 }
377 if (fileSize != null) {
378 timeInfoBuilder.add(fileSize);
379 }
380 // for space reasons we display only 'additional status info' (send progress or concrete
381 // failure reason) or the time
382 if (additionalStatusInfo != null) {
383 timeInfoBuilder.add(additionalStatusInfo);
384 } else {
385 timeInfoBuilder.add(formattedTime);
386 }
387 }
388 final var timeInfo = timeInfoBuilder.build();
389 viewHolder.time.setText(Joiner.on(" \u00B7 ").join(timeInfo));
390 }
391
392 public static @DrawableRes Integer getMessageStatusAsDrawable(
393 final Message message, final int status) {
394 final var transferable = message.getTransferable();
395 return switch (status) {
396 case Message.STATUS_WAITING -> R.drawable.ic_more_horiz_24dp;
397 case Message.STATUS_UNSEND -> transferable == null ? null : R.drawable.ic_upload_24dp;
398 case Message.STATUS_SEND -> R.drawable.ic_done_24dp;
399 case Message.STATUS_SEND_RECEIVED, Message.STATUS_SEND_DISPLAYED -> R.drawable
400 .ic_done_all_24dp;
401 case Message.STATUS_SEND_FAILED -> {
402 final String errorMessage = message.getErrorMessage();
403 if (Message.ERROR_MESSAGE_CANCELLED.equals(errorMessage)) {
404 yield R.drawable.ic_cancel_24dp;
405 } else {
406 yield R.drawable.ic_error_24dp;
407 }
408 }
409 case Message.STATUS_OFFERED -> R.drawable.ic_p2p_24dp;
410 default -> null;
411 };
412 }
413
414 @Nullable
415 private String getAdditionalStatusInfo(final Message message, final int mergedStatus) {
416 final String additionalStatusInfo;
417 if (mergedStatus == Message.STATUS_SEND_FAILED) {
418 final String errorMessage = Strings.nullToEmpty(message.getErrorMessage());
419 final String[] errorParts = errorMessage.split("\\u001f", 2);
420 if (errorParts.length == 2 && errorParts[0].equals("file-too-large")) {
421 additionalStatusInfo = getContext().getString(R.string.file_too_large);
422 } else {
423 additionalStatusInfo = null;
424 }
425 } else if (mergedStatus == Message.STATUS_UNSEND) {
426 final var transferable = message.getTransferable();
427 if (transferable == null) {
428 return null;
429 }
430 return getContext().getString(R.string.sending_file, transferable.getProgress());
431 } else {
432 additionalStatusInfo = null;
433 }
434 return additionalStatusInfo;
435 }
436
437 private void displayInfoMessage(
438 ViewHolder viewHolder, CharSequence text, final BubbleColor bubbleColor) {
439 viewHolder.download_button.setVisibility(View.GONE);
440 viewHolder.audioPlayer.setVisibility(View.GONE);
441 viewHolder.image.setVisibility(View.GONE);
442 viewHolder.messageBody.setVisibility(View.VISIBLE);
443 viewHolder.messageBody.setText(text);
444 viewHolder.messageBody.setTextColor(
445 bubbleToOnSurfaceVariant(viewHolder.messageBody, bubbleColor));
446 viewHolder.messageBody.setTextIsSelectable(false);
447 }
448
449 private void displayEmojiMessage(
450 final ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, int type) {
451 displayTextMessage(viewHolder, message, bubbleColor, type);
452 viewHolder.download_button.setVisibility(View.GONE);
453 viewHolder.audioPlayer.setVisibility(View.GONE);
454 viewHolder.image.setVisibility(View.GONE);
455 viewHolder.messageBody.setVisibility(View.VISIBLE);
456 setTextColor(viewHolder.messageBody, bubbleColor);
457 final var body = getSpannableBody(message);
458 ImageSpan[] imageSpans = body.getSpans(0, body.length(), ImageSpan.class);
459 float size = imageSpans.length == 1 || Emoticons.isEmoji(body.toString()) ? 5.0f : 2.0f;
460 body.setSpan(
461 new RelativeSizeSpan(size), 0, body.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
462 viewHolder.messageBody.setText(body);
463 }
464
465 private void applyQuoteSpan(
466 final TextView textView,
467 Editable body,
468 int start,
469 int end,
470 final BubbleColor bubbleColor,
471 final boolean makeEdits) {
472 if (makeEdits && start > 1 && !"\n\n".equals(body.subSequence(start - 2, start).toString())) {
473 body.insert(start++, "\n");
474 body.setSpan(
475 new DividerSpan(false), start - 2, start, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
476 end++;
477 }
478 if (makeEdits && end < body.length() - 1 && !"\n\n".equals(body.subSequence(end, end + 2).toString())) {
479 body.insert(end, "\n");
480 body.setSpan(
481 new DividerSpan(false),
482 end,
483 end + ("\n".equals(body.subSequence(end + 1, end + 2).toString()) ? 2 : 1),
484 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
485 );
486 }
487 final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
488 body.setSpan(
489 new QuoteSpan(bubbleToOnSurfaceVariant(textView, bubbleColor), metrics),
490 start,
491 end,
492 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
493 }
494
495 public boolean handleTextQuotes(final TextView textView, final Editable body) {
496 return handleTextQuotes(textView, body, true);
497 }
498
499 public boolean handleTextQuotes(final TextView textView, final Editable body, final boolean deleteMarkers) {
500 final boolean colorfulBackground = this.bubbleDesign.colorfulChatBubbles;
501 final BubbleColor bubbleColor = colorfulBackground ? (deleteMarkers ? BubbleColor.SECONDARY : BubbleColor.TERTIARY) : BubbleColor.SURFACE;
502 return handleTextQuotes(textView, body, bubbleColor, deleteMarkers);
503 }
504
505 /**
506 * Applies QuoteSpan to group of lines which starts with > or » characters. Appends likebreaks
507 * and applies DividerSpan to them to show a padding between quote and text.
508 */
509 public boolean handleTextQuotes(
510 final TextView textView,
511 final Editable body,
512 final BubbleColor bubbleColor,
513 final boolean deleteMarkers) {
514 boolean startsWithQuote = false;
515 int quoteDepth = 1;
516 while (QuoteHelper.bodyContainsQuoteStart(body) && quoteDepth <= Config.QUOTE_MAX_DEPTH) {
517 char previous = '\n';
518 int lineStart = -1;
519 int lineTextStart = -1;
520 int quoteStart = -1;
521 int skipped = 0;
522 for (int i = 0; i <= body.length(); i++) {
523 if (!deleteMarkers && QuoteHelper.isRelativeSizeSpanned(body, i)) {
524 skipped++;
525 continue;
526 }
527 char current = body.length() > i ? body.charAt(i) : '\n';
528 if (lineStart == -1) {
529 if (previous == '\n') {
530 if (i < body.length() && QuoteHelper.isPositionQuoteStart(body, i)) {
531 // Line start with quote
532 lineStart = i;
533 if (quoteStart == -1) quoteStart = i - skipped;
534 if (i == 0) startsWithQuote = true;
535 } else if (quoteStart >= 0) {
536 // Line start without quote, apply spans there
537 applyQuoteSpan(textView, body, quoteStart, i - 1, bubbleColor, deleteMarkers);
538 quoteStart = -1;
539 }
540 }
541 } else {
542 // Remove extra spaces between > and first character in the line
543 // > character will be removed too
544 if (current != ' ' && lineTextStart == -1) {
545 lineTextStart = i;
546 }
547 if (current == '\n') {
548 if (deleteMarkers) {
549 i -= lineTextStart - lineStart;
550 body.delete(lineStart, lineTextStart);
551 if (i == lineStart) {
552 // Avoid empty lines because span over empty line can be hidden
553 body.insert(i++, " ");
554 }
555 } else {
556 body.setSpan(new RelativeSizeSpan(i - (lineTextStart - lineStart) == lineStart ? 1 : 0), lineStart, lineTextStart, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE | StylingHelper.XHTML_REMOVE << Spanned.SPAN_USER_SHIFT);
557 }
558 lineStart = -1;
559 lineTextStart = -1;
560 }
561 }
562 previous = current;
563 skipped = 0;
564 }
565 if (quoteStart >= 0) {
566 // Apply spans to finishing open quote
567 applyQuoteSpan(textView, body, quoteStart, body.length(), bubbleColor, deleteMarkers);
568 }
569 quoteDepth++;
570 }
571 return startsWithQuote;
572 }
573
574 private SpannableStringBuilder getSpannableBody(final Message message) {
575 Drawable fallbackImg = ResourcesCompat.getDrawable(activity.getResources(), R.drawable.ic_photo_24dp, null);
576 return message.getMergedBody((cid) -> {
577 try {
578 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
579 if (f == null || !f.canRead()) {
580 if (!message.trusted() && !message.getConversation().canInferPresence()) return null;
581
582 try {
583 new BobTransfer(BobTransfer.uri(cid), message.getConversation().getAccount(), message.getCounterpart(), activity.xmppConnectionService).start();
584 } catch (final NoSuchAlgorithmException | URISyntaxException e) { }
585 return null;
586 }
587
588 Drawable d = activity.xmppConnectionService.getFileBackend().getThumbnail(f, activity.getResources(), (int) (metrics.density * 288), true);
589 if (d == null) {
590 new ThumbnailTask().execute(f);
591 }
592 return d;
593 } catch (final IOException e) {
594 return null;
595 }
596 }, fallbackImg);
597 }
598
599 private void displayTextMessage(
600 final ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
601 viewHolder.inReplyToQuote.setVisibility(View.GONE);
602 viewHolder.download_button.setVisibility(View.GONE);
603 viewHolder.image.setVisibility(View.GONE);
604 viewHolder.audioPlayer.setVisibility(View.GONE);
605 viewHolder.messageBody.setVisibility(View.VISIBLE);
606 setTextColor(viewHolder.messageBody, bubbleColor);
607 setTextSize(viewHolder.messageBody, this.bubbleDesign.largeFont);
608
609 final ViewGroup.LayoutParams layoutParams = viewHolder.messageBody.getLayoutParams();
610 layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
611 viewHolder.messageBody.setLayoutParams(layoutParams);
612
613 final ViewGroup.LayoutParams qlayoutParams = viewHolder.inReplyToQuote.getLayoutParams();
614 qlayoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
615 viewHolder.messageBody.setLayoutParams(qlayoutParams);
616
617 viewHolder.messageBody.setTypeface(null, Typeface.NORMAL);
618
619 if (message.getBody() != null && !message.getBody().equals("")) {
620 viewHolder.messageBody.setTextIsSelectable(true);
621 viewHolder.messageBody.setVisibility(View.VISIBLE);
622 final String nick = UIHelper.getMessageDisplayName(message);
623 SpannableStringBuilder body = getSpannableBody(message);
624 final var processMarkup = body.getSpans(0, body.length(), Message.PlainTextSpan.class).length > 0;
625 boolean hasMeCommand = message.hasMeCommand();
626 if (hasMeCommand) {
627 body = body.replace(0, Message.ME_COMMAND.length(), nick + " ");
628 }
629 if (body.length() > Config.MAX_DISPLAY_MESSAGE_CHARS) {
630 body = new SpannableStringBuilder(body, 0, Config.MAX_DISPLAY_MESSAGE_CHARS);
631 body.append("\u2026");
632 }
633 Message.MergeSeparator[] mergeSeparators =
634 body.getSpans(0, body.length(), Message.MergeSeparator.class);
635 for (Message.MergeSeparator mergeSeparator : mergeSeparators) {
636 int start = body.getSpanStart(mergeSeparator);
637 int end = body.getSpanEnd(mergeSeparator);
638 body.setSpan(new DividerSpan(true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
639 }
640 boolean startsWithQuote = false;
641 for (final android.text.style.QuoteSpan quote : body.getSpans(0, body.length(), android.text.style.QuoteSpan.class)) {
642 int start = body.getSpanStart(quote);
643 int end = body.getSpanEnd(quote);
644 body.removeSpan(quote);
645 applyQuoteSpan(viewHolder.messageBody, body, start, end, bubbleColor, true);
646 if (start == 0) {
647 if (message.getInReplyTo() == null) {
648 startsWithQuote = true;
649 } else {
650 viewHolder.inReplyToQuote.setText(body.subSequence(start, end));
651 viewHolder.inReplyToQuote.setVisibility(View.VISIBLE);
652 body.delete(start, end);
653 while (body.length() > start && body.charAt(start) == '\n') body.delete(start, 1); // Newlines after quote
654 continue;
655 }
656 }
657 }
658 startsWithQuote = (processMarkup ? handleTextQuotes(viewHolder.messageBody, body, bubbleColor, true) : false) || startsWithQuote;
659 if (!message.isPrivateMessage()) {
660 if (hasMeCommand) {
661 body.setSpan(
662 new StyleSpan(Typeface.BOLD_ITALIC),
663 0,
664 nick.length(),
665 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
666 }
667 } else {
668 String privateMarker;
669 if (message.getStatus() <= Message.STATUS_RECEIVED) {
670 privateMarker = activity.getString(R.string.private_message);
671 } else {
672 Jid cp = message.getCounterpart();
673 privateMarker =
674 activity.getString(
675 R.string.private_message_to,
676 Strings.nullToEmpty(cp == null ? null : cp.getResource()));
677 }
678 body.insert(0, privateMarker);
679 int privateMarkerIndex = privateMarker.length();
680 if (startsWithQuote) {
681 body.insert(privateMarkerIndex, "\n\n");
682 body.setSpan(
683 new DividerSpan(false),
684 privateMarkerIndex,
685 privateMarkerIndex + 2,
686 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
687 } else {
688 body.insert(privateMarkerIndex, " ");
689 }
690 body.setSpan(
691 new ForegroundColorSpan(
692 bubbleToOnSurfaceVariant(viewHolder.messageBody, bubbleColor)),
693 0,
694 privateMarkerIndex,
695 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
696 body.setSpan(
697 new StyleSpan(Typeface.BOLD),
698 0,
699 privateMarkerIndex,
700 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
701 if (hasMeCommand) {
702 body.setSpan(
703 new StyleSpan(Typeface.BOLD_ITALIC),
704 privateMarkerIndex + 1,
705 privateMarkerIndex + 1 + nick.length(),
706 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
707 }
708 }
709 if (message.getConversation().getMode() == Conversation.MODE_MULTI
710 && message.getStatus() == Message.STATUS_RECEIVED) {
711 if (message.getConversation() instanceof Conversation conversation) {
712 Pattern pattern =
713 NotificationService.generateNickHighlightPattern(
714 conversation.getMucOptions().getActualNick());
715 Matcher matcher = pattern.matcher(body);
716 while (matcher.find()) {
717 body.setSpan(
718 new StyleSpan(Typeface.BOLD),
719 matcher.start(),
720 matcher.end(),
721 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
722 }
723
724 pattern = NotificationService.generateNickHighlightPattern(conversation.getMucOptions().getActualName());
725 matcher = pattern.matcher(body);
726 while (matcher.find()) {
727 body.setSpan(new StyleSpan(Typeface.BOLD), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
728 }
729 }
730 }
731 for (final var emoji : EmojiManager.extractEmojisInOrderWithIndex(body.toString())) {
732 var end = emoji.getCharIndex() + emoji.getEmoji().getEmoji().length();
733 if (body.length() > end && body.charAt(end) == '\uFE0F') end++;
734 body.setSpan(
735 new RelativeSizeSpan(1.2f),
736 emoji.getCharIndex(),
737 end,
738 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
739 }
740 // Make custom emoji bigger too, to match emoji
741 for (final var span : body.getSpans(0, body.length(), com.cheogram.android.InlineImageSpan.class)) {
742 body.setSpan(
743 new RelativeSizeSpan(1.2f),
744 body.getSpanStart(span),
745 body.getSpanEnd(span),
746 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
747 }
748
749 if (processMarkup) StylingHelper.format(body, viewHolder.messageBody.getCurrentTextColor());
750 MyLinkify.addLinks(body, message.getConversation().getAccount(), message.getConversation().getJid());
751 if (highlightedTerm != null) {
752 StylingHelper.highlight(viewHolder.messageBody, body, highlightedTerm);
753 }
754
755 viewHolder.messageBody.setAutoLinkMask(0);
756 viewHolder.messageBody.setText(body);
757 if (body.length() <= 0) viewHolder.messageBody.setVisibility(View.GONE);
758 BetterLinkMovementMethod method = new BetterLinkMovementMethod() {
759 @Override
760 protected void dispatchUrlLongClick(TextView tv, ClickableSpan span) {
761 if (span instanceof URLSpan || mOnInlineImageLongClickedListener == null) {
762 tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
763 super.dispatchUrlLongClick(tv, span);
764 return;
765 }
766
767 Spannable body = (Spannable) tv.getText();
768 ImageSpan[] imageSpans = body.getSpans(body.getSpanStart(span), body.getSpanEnd(span), ImageSpan.class);
769 if (imageSpans.length > 0) {
770 Uri uri = Uri.parse(imageSpans[0].getSource());
771 Cid cid = BobTransfer.cid(uri);
772 if (cid == null) return;
773 if (mOnInlineImageLongClickedListener.onInlineImageLongClicked(cid)) {
774 tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
775 }
776 }
777 }
778 };
779 method.setOnLinkLongClickListener((tv, url) -> {
780 tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
781 ShareUtil.copyLinkToClipboard(activity, url);
782 return true;
783 });
784 viewHolder.messageBody.setMovementMethod(method);
785 } else {
786 viewHolder.messageBody.setText("");
787 viewHolder.messageBody.setTextIsSelectable(false);
788 toggleWhisperInfo(viewHolder, message, bubbleColor);
789 }
790 }
791
792 private void displayDownloadableMessage(
793 ViewHolder viewHolder,
794 final Message message,
795 String text,
796 final BubbleColor bubbleColor, final int type) {
797 displayTextMessage(viewHolder, message, bubbleColor, type);
798 viewHolder.image.setVisibility(View.GONE);
799 List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
800 if (thumbs != null && !thumbs.isEmpty()) {
801 for (Element thumb : thumbs) {
802 Uri uri = Uri.parse(thumb.getAttribute("uri"));
803 if (uri.getScheme().equals("data")) {
804 String[] parts = uri.getSchemeSpecificPart().split(",", 2);
805 parts = parts[0].split(";");
806 if (!parts[0].equals("image/blurhash") && !parts[0].equals("image/thumbhash") && !parts[0].equals("image/jpeg") && !parts[0].equals("image/png") && !parts[0].equals("image/webp") && !parts[0].equals("image/gif")) continue;
807 } else if (uri.getScheme().equals("cid")) {
808 Cid cid = BobTransfer.cid(uri);
809 if (cid == null) continue;
810 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
811 if (f == null || !f.canRead()) {
812 if (!message.trusted() && !message.getConversation().canInferPresence()) continue;
813
814 try {
815 new BobTransfer(BobTransfer.uri(cid), message.getConversation().getAccount(), message.getCounterpart(), activity.xmppConnectionService).start();
816 } catch (final NoSuchAlgorithmException | URISyntaxException e) { }
817 continue;
818 }
819 } else {
820 continue;
821 }
822
823 int width = message.getFileParams().width;
824 if (width < 1 && thumb.getAttribute("width") != null) width = Integer.parseInt(thumb.getAttribute("width"));
825 if (width < 1) width = 1920;
826
827 int height = message.getFileParams().height;
828 if (height < 1 && thumb.getAttribute("height") != null) height = Integer.parseInt(thumb.getAttribute("height"));
829 if (height < 1) height = 1080;
830
831 viewHolder.image.setVisibility(View.VISIBLE);
832 imagePreviewLayout(width, height, viewHolder.image, message.getInReplyTo() != null, true, type, viewHolder);
833 activity.loadBitmap(message, viewHolder.image);
834 viewHolder.image.setOnClickListener(v -> ConversationFragment.downloadFile(activity, message));
835
836 break;
837 }
838 }
839 viewHolder.audioPlayer.setVisibility(View.GONE);
840 viewHolder.download_button.setVisibility(View.VISIBLE);
841 viewHolder.download_button.setText(text);
842 final var attachment = Attachment.of(message);
843 final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
844 viewHolder.download_button.setIconResource(imageResource);
845 viewHolder.download_button.setOnClickListener(
846 v -> ConversationFragment.downloadFile(activity, message));
847 }
848
849 private void displayWebxdcMessage(ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
850 Cid webxdcCid = message.getFileParams().getCids().get(0);
851 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
852 displayTextMessage(viewHolder, message, bubbleColor, type);
853 viewHolder.image.setVisibility(View.GONE);
854 viewHolder.audioPlayer.setVisibility(View.GONE);
855 viewHolder.download_button.setVisibility(View.VISIBLE);
856 viewHolder.download_button.setText("Open " + webxdc.getName());
857 viewHolder.download_button.setOnClickListener(v -> {
858 Conversation conversation = (Conversation) message.getConversation();
859 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
860 conversation.startWebxdc(webxdc);
861 }
862 });
863
864 final WebxdcUpdate lastUpdate;
865 synchronized(lastWebxdcUpdate) { lastUpdate = lastWebxdcUpdate.get(message.getUuid()); }
866 if (lastUpdate == null) {
867 new Thread(() -> {
868 final WebxdcUpdate update = activity.xmppConnectionService.findLastWebxdcUpdate(message);
869 if (update != null) {
870 synchronized(lastWebxdcUpdate) { lastWebxdcUpdate.put(message.getUuid(), update); }
871 activity.xmppConnectionService.updateConversationUi();
872 }
873 }).start();
874 } else {
875 if (lastUpdate != null && (lastUpdate.getSummary() != null || lastUpdate.getDocument() != null)) {
876 viewHolder.messageBody.setVisibility(View.VISIBLE);
877 viewHolder.messageBody.setText(
878 (lastUpdate.getDocument() == null ? "" : lastUpdate.getDocument() + "\n") +
879 (lastUpdate.getSummary() == null ? "" : lastUpdate.getSummary())
880 );
881 }
882 }
883
884 final LruCache<String, Drawable> cache = activity.xmppConnectionService.getDrawableCache();
885 final Drawable d = cache.get("webxdc:icon:" + webxdcCid);
886 if (d == null) {
887 new Thread(() -> {
888 Drawable icon = webxdc.getIcon();
889 if (icon != null) {
890 cache.put("webxdc:icon:" + webxdcCid, icon);
891 activity.xmppConnectionService.updateConversationUi();
892 }
893 }).start();
894 } else {
895 viewHolder.image.setVisibility(View.VISIBLE);
896 viewHolder.image.setImageDrawable(d);
897 }
898 }
899
900 private void displayOpenableMessage(
901 ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
902 displayTextMessage(viewHolder, message, bubbleColor, type);
903 viewHolder.image.setVisibility(View.GONE);
904 viewHolder.audioPlayer.setVisibility(View.GONE);
905 viewHolder.download_button.setVisibility(View.VISIBLE);
906 viewHolder.download_button.setText(
907 activity.getString(
908 R.string.open_x_file,
909 UIHelper.getFileDescriptionString(activity, message)));
910 final var attachment = Attachment.of(message);
911 final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
912 viewHolder.download_button.setIconResource(imageResource);
913 viewHolder.download_button.setOnClickListener(v -> openDownloadable(message));
914 }
915
916 private void displayLocationMessage(
917 ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
918 displayTextMessage(viewHolder, message, bubbleColor, type);
919 viewHolder.image.setVisibility(View.GONE);
920 viewHolder.audioPlayer.setVisibility(View.GONE);
921 viewHolder.download_button.setVisibility(View.VISIBLE);
922 viewHolder.download_button.setText(R.string.show_location);
923 final var attachment = Attachment.of(message);
924 final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
925 viewHolder.download_button.setIconResource(imageResource);
926 viewHolder.download_button.setOnClickListener(v -> showLocation(message));
927 }
928
929 private void displayAudioMessage(
930 ViewHolder viewHolder, Message message, final BubbleColor bubbleColor, final int type) {
931 displayTextMessage(viewHolder, message, bubbleColor, type);
932 viewHolder.image.setVisibility(View.GONE);
933 viewHolder.download_button.setVisibility(View.GONE);
934 final RelativeLayout audioPlayer = viewHolder.audioPlayer;
935 audioPlayer.setVisibility(View.VISIBLE);
936 AudioPlayer.ViewHolder.get(audioPlayer).setBubbleColor(bubbleColor);
937 this.audioPlayer.init(audioPlayer, message);
938 }
939
940 private void displayMediaPreviewMessage(
941 ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
942 displayTextMessage(viewHolder, message, bubbleColor, type);
943 viewHolder.download_button.setVisibility(View.GONE);
944 viewHolder.audioPlayer.setVisibility(View.GONE);
945 viewHolder.image.setVisibility(View.VISIBLE);
946 final FileParams params = message.getFileParams();
947 imagePreviewLayout(params.width, params.height, viewHolder.image, message.getInReplyTo() != null, viewHolder.messageBody.getVisibility() != View.GONE, type, viewHolder);
948 activity.loadBitmap(message, viewHolder.image);
949 viewHolder.image.setOnClickListener(v -> openDownloadable(message));
950 }
951
952 private void imagePreviewLayout(int w, int h, ShapeableImageView image, boolean otherAbove, boolean otherBelow, int type, ViewHolder viewHolder) {
953 final float target = activity.getResources().getDimension(R.dimen.image_preview_width);
954 final int scaledW;
955 final int scaledH;
956 if (Math.max(h, w) * metrics.density <= target) {
957 scaledW = (int) (w * metrics.density);
958 scaledH = (int) (h * metrics.density);
959 } else if (Math.max(h, w) <= target) {
960 scaledW = w;
961 scaledH = h;
962 } else if (w <= h) {
963 scaledW = (int) (w / ((double) h / target));
964 scaledH = (int) target;
965 } else {
966 scaledW = (int) target;
967 scaledH = (int) (h / ((double) w / target));
968 }
969 final var bodyWidth = Math.max(viewHolder.messageBody.getWidth(), viewHolder.download_button.getWidth());
970 var targetImageWidth = 200 * metrics.density;
971 if (!otherBelow) targetImageWidth = 110 * metrics.density;
972 if (bodyWidth > 0 && bodyWidth < targetImageWidth) targetImageWidth = bodyWidth;
973 final var small = scaledW < targetImageWidth;
974 final LinearLayout.LayoutParams layoutParams =
975 new LinearLayout.LayoutParams(scaledW, scaledH);
976 image.setLayoutParams(layoutParams);
977
978 final var bubbleRadius = activity.getResources().getDimension(R.dimen.bubble_radius);
979 var shape = new ShapeAppearanceModel.Builder();
980 if (!otherAbove) {
981 shape = shape.setTopRightCorner(CornerFamily.ROUNDED, bubbleRadius);
982 if (type == SENT) {
983 shape = shape.setTopLeftCorner(CornerFamily.ROUNDED, bubbleRadius);
984 }
985 }
986 if (small) {
987 final var imageRadius = activity.getResources().getDimension(R.dimen.image_radius);
988 shape = shape.setAllCorners(CornerFamily.ROUNDED, imageRadius);
989 image.setPadding(0, (int)(8 * metrics.density), 0, 0);
990 } else {
991 image.setPadding(0, 0, 0, 0);
992 }
993 image.setShapeAppearanceModel(shape.build());
994
995 if (!small) {
996 final ViewGroup.LayoutParams blayoutParams = viewHolder.messageBody.getLayoutParams();
997 blayoutParams.width = (int) (scaledW - (22 * metrics.density));
998 viewHolder.messageBody.setLayoutParams(blayoutParams);
999
1000 final ViewGroup.LayoutParams qlayoutParams = viewHolder.inReplyToQuote.getLayoutParams();
1001 qlayoutParams.width = (int) (scaledW - (22 * metrics.density));
1002 viewHolder.messageBody.setLayoutParams(qlayoutParams);
1003 }
1004 }
1005
1006 private void toggleWhisperInfo(
1007 ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor) {
1008 if (message.isPrivateMessage()) {
1009 final String privateMarker;
1010 if (message.getStatus() <= Message.STATUS_RECEIVED) {
1011 privateMarker = activity.getString(R.string.private_message);
1012 } else {
1013 Jid cp = message.getCounterpart();
1014 privateMarker =
1015 activity.getString(
1016 R.string.private_message_to,
1017 Strings.nullToEmpty(cp == null ? null : cp.getResource()));
1018 }
1019 final SpannableString body = new SpannableString(privateMarker);
1020 body.setSpan(
1021 new ForegroundColorSpan(
1022 bubbleToOnSurfaceVariant(viewHolder.messageBody, bubbleColor)),
1023 0,
1024 privateMarker.length(),
1025 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1026 body.setSpan(
1027 new StyleSpan(Typeface.BOLD),
1028 0,
1029 privateMarker.length(),
1030 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1031 viewHolder.messageBody.setText(body);
1032 viewHolder.messageBody.setVisibility(View.VISIBLE);
1033 } else {
1034 viewHolder.messageBody.setVisibility(View.GONE);
1035 }
1036 }
1037
1038 private void loadMoreMessages(Conversation conversation) {
1039 conversation.setLastClearHistory(0, null);
1040 activity.xmppConnectionService.updateConversation(conversation);
1041 conversation.setHasMessagesLeftOnServer(true);
1042 conversation.setFirstMamReference(null);
1043 long timestamp = conversation.getLastMessageTransmitted().getTimestamp();
1044 if (timestamp == 0) {
1045 timestamp = System.currentTimeMillis();
1046 }
1047 conversation.messagesLoaded.set(true);
1048 MessageArchiveService.Query query =
1049 activity.xmppConnectionService
1050 .getMessageArchiveService()
1051 .query(conversation, new MamReference(0), timestamp, false);
1052 if (query != null) {
1053 Toast.makeText(activity, R.string.fetching_history_from_server, Toast.LENGTH_LONG)
1054 .show();
1055 } else {
1056 Toast.makeText(
1057 activity,
1058 R.string.not_fetching_history_retention_period,
1059 Toast.LENGTH_SHORT)
1060 .show();
1061 }
1062 }
1063
1064 @Override
1065 public View getView(final int position, View view, final @NonNull ViewGroup parent) {
1066 final Message message = getItem(position);
1067 final boolean omemoEncryption = message.getEncryption() == Message.ENCRYPTION_AXOLOTL;
1068 final boolean isInValidSession =
1069 message.isValidInSession() && (!omemoEncryption || message.isTrusted());
1070 final Conversational conversation = message.getConversation();
1071 final Account account = conversation.getAccount();
1072 final List<Element> commands = message.getCommands();
1073 final int type = getItemViewType(position);
1074 ViewHolder viewHolder;
1075 if (view == null) {
1076 viewHolder = new ViewHolder();
1077 switch (type) {
1078 case DATE_SEPARATOR:
1079 view =
1080 activity.getLayoutInflater()
1081 .inflate(R.layout.item_message_date_bubble, parent, false);
1082 viewHolder.status_message = view.findViewById(R.id.message_body);
1083 viewHolder.message_box = view.findViewById(R.id.message_box);
1084 break;
1085 case RTP_SESSION:
1086 view =
1087 activity.getLayoutInflater()
1088 .inflate(R.layout.item_message_rtp_session, parent, false);
1089 viewHolder.status_message = view.findViewById(R.id.message_body);
1090 viewHolder.message_box = view.findViewById(R.id.message_box);
1091 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
1092 break;
1093 case SENT:
1094 view = activity.getLayoutInflater().inflate(R.layout.item_message_sent, parent, false);
1095 viewHolder.status_line = view.findViewById(R.id.status_line);
1096 viewHolder.message_box_inner = view.findViewById(R.id.message_box_inner);
1097 viewHolder.message_box = view.findViewById(R.id.message_box);
1098 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
1099 viewHolder.download_button = view.findViewById(R.id.download_button);
1100 viewHolder.indicator = view.findViewById(R.id.security_indicator);
1101 viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
1102 viewHolder.image = view.findViewById(R.id.message_image);
1103 viewHolder.messageBody = view.findViewById(R.id.message_body);
1104 viewHolder.time = view.findViewById(R.id.message_time);
1105 viewHolder.subject = view.findViewById(R.id.message_subject);
1106 viewHolder.inReplyTo = view.findViewById(R.id.in_reply_to);
1107 viewHolder.inReplyToBox = view.findViewById(R.id.in_reply_to_box);
1108 viewHolder.inReplyToQuote = view.findViewById(R.id.in_reply_to_quote);
1109 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
1110 viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
1111 viewHolder.thread_identicon = view.findViewById(R.id.thread_identicon);
1112 break;
1113 case RECEIVED:
1114 view = activity.getLayoutInflater().inflate(R.layout.item_message_received, parent, false);
1115 viewHolder.status_line = view.findViewById(R.id.status_line);
1116 viewHolder.message_box_inner = view.findViewById(R.id.message_box_inner);
1117 viewHolder.message_box = view.findViewById(R.id.message_box);
1118 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
1119 viewHolder.download_button = view.findViewById(R.id.download_button);
1120 viewHolder.indicator = view.findViewById(R.id.security_indicator);
1121 viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
1122 viewHolder.image = view.findViewById(R.id.message_image);
1123 viewHolder.messageBody = view.findViewById(R.id.message_body);
1124 viewHolder.time = view.findViewById(R.id.message_time);
1125 viewHolder.subject = view.findViewById(R.id.message_subject);
1126 viewHolder.inReplyTo = view.findViewById(R.id.in_reply_to);
1127 viewHolder.inReplyToQuote = view.findViewById(R.id.in_reply_to_quote);
1128 viewHolder.inReplyToBox = view.findViewById(R.id.in_reply_to_box);
1129 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
1130 viewHolder.encryption = view.findViewById(R.id.message_encryption);
1131 viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
1132 viewHolder.commands_list = view.findViewById(R.id.commands_list);
1133 viewHolder.thread_identicon = view.findViewById(R.id.thread_identicon);
1134 break;
1135 case STATUS:
1136 view =
1137 activity.getLayoutInflater()
1138 .inflate(R.layout.item_message_status, parent, false);
1139 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
1140 viewHolder.status_message = view.findViewById(R.id.status_message);
1141 viewHolder.load_more_messages = view.findViewById(R.id.load_more_messages);
1142 break;
1143 default:
1144 throw new AssertionError("Unknown view type");
1145 }
1146 view.setTag(viewHolder);
1147 } else {
1148 viewHolder = (ViewHolder) view.getTag();
1149 if (viewHolder == null) {
1150 return view;
1151 }
1152 }
1153
1154 if (viewHolder.messageBody != null) {
1155 viewHolder.messageBody.setCustomSelectionActionModeCallback(new MessageTextActionModeCallback(this, viewHolder.messageBody));
1156 }
1157
1158 if (viewHolder.thread_identicon != null) {
1159 viewHolder.thread_identicon.setVisibility(View.GONE);
1160 final Element thread = message.getThread();
1161 if (thread != null) {
1162 final String threadId = thread.getContent();
1163 if (threadId != null) {
1164 viewHolder.thread_identicon.setVisibility(View.VISIBLE);
1165 viewHolder.thread_identicon.setColor(UIHelper.getColorForName(threadId));
1166 viewHolder.thread_identicon.setHash(UIHelper.identiconHash(threadId));
1167 }
1168 }
1169 }
1170
1171 if (viewHolder.time != null) {
1172 if (message.isAttention()) {
1173 viewHolder.time.setTypeface(null, Typeface.BOLD);
1174 } else {
1175 viewHolder.time.setTypeface(null, Typeface.NORMAL);
1176 }
1177 }
1178
1179 final var black = MaterialColors.getColor(view, com.google.android.material.R.attr.colorSecondaryContainer) == view.getContext().getColor(android.R.color.black);
1180 final boolean colorfulBackground = this.bubbleDesign.colorfulChatBubbles;
1181 final BubbleColor bubbleColor;
1182 if (type == RECEIVED) {
1183 if (isInValidSession) {
1184 bubbleColor = colorfulBackground || black ? BubbleColor.SECONDARY : BubbleColor.SURFACE;
1185 } else {
1186 bubbleColor = BubbleColor.WARNING;
1187 }
1188 } else {
1189 if (!colorfulBackground && black) {
1190 bubbleColor = BubbleColor.SECONDARY;
1191 } else {
1192 bubbleColor = colorfulBackground ? BubbleColor.TERTIARY : BubbleColor.SURFACE_HIGH;
1193 }
1194 }
1195
1196 if (type == DATE_SEPARATOR) {
1197 if (UIHelper.today(message.getTimeSent())) {
1198 viewHolder.status_message.setText(R.string.today);
1199 } else if (UIHelper.yesterday(message.getTimeSent())) {
1200 viewHolder.status_message.setText(R.string.yesterday);
1201 } else {
1202 viewHolder.status_message.setText(
1203 DateUtils.formatDateTime(
1204 activity,
1205 message.getTimeSent(),
1206 DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
1207 }
1208 if (colorfulBackground) {
1209 setBackgroundTint(viewHolder.message_box, BubbleColor.PRIMARY);
1210 setTextColor(viewHolder.status_message, BubbleColor.PRIMARY);
1211 } else {
1212 setBackgroundTint(viewHolder.message_box, BubbleColor.SURFACE_HIGH);
1213 setTextColor(viewHolder.status_message, BubbleColor.SURFACE_HIGH);
1214 }
1215 return view;
1216 } else if (type == RTP_SESSION) {
1217 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
1218 final RtpSessionStatus rtpSessionStatus = RtpSessionStatus.of(message.getBody());
1219 final long duration = rtpSessionStatus.duration;
1220 final String callTime = UIHelper.readableTimeDifferenceFull(activity, message.getTimeSent());
1221 if (received) {
1222 if (duration > 0) {
1223 viewHolder.status_message.setText(
1224 activity.getString(
1225 R.string.incoming_call_duration_timestamp,
1226 TimeFrameUtils.resolve(activity, duration),
1227 UIHelper.readableTimeDifferenceFull(
1228 activity, message.getTimeSent())));
1229 } else if (rtpSessionStatus.successful) {
1230 viewHolder.status_message.setText(activity.getString(R.string.incoming_call_timestamp, callTime));
1231 } else {
1232 viewHolder.status_message.setText(
1233 activity.getString(
1234 R.string.missed_call_timestamp,
1235 UIHelper.readableTimeDifferenceFull(
1236 activity, message.getTimeSent())));
1237 }
1238 } else {
1239 if (duration > 0) {
1240 viewHolder.status_message.setText(
1241 activity.getString(
1242 R.string.outgoing_call_duration_timestamp,
1243 TimeFrameUtils.resolve(activity, duration),
1244 UIHelper.readableTimeDifferenceFull(
1245 activity, message.getTimeSent())));
1246 } else {
1247 viewHolder.status_message.setText(
1248 activity.getString(
1249 R.string.outgoing_call_timestamp,
1250 UIHelper.readableTimeDifferenceFull(
1251 activity, message.getTimeSent())));
1252 }
1253 }
1254 if (colorfulBackground) {
1255 setBackgroundTint(viewHolder.message_box, BubbleColor.SECONDARY);
1256 setTextColor(viewHolder.status_message, BubbleColor.SECONDARY);
1257 setImageTint(viewHolder.indicatorReceived, BubbleColor.SECONDARY);
1258 } else {
1259 setBackgroundTint(viewHolder.message_box, BubbleColor.SURFACE_HIGH);
1260 setTextColor(viewHolder.status_message, BubbleColor.SURFACE_HIGH);
1261 setImageTint(viewHolder.indicatorReceived, BubbleColor.SURFACE_HIGH);
1262 }
1263 viewHolder.indicatorReceived.setImageResource(
1264 RtpSessionStatus.getDrawable(received, rtpSessionStatus.successful));
1265 return view;
1266 } else if (type == STATUS) {
1267 if ("LOAD_MORE".equals(message.getBody())) {
1268 viewHolder.status_message.setVisibility(View.GONE);
1269 viewHolder.contact_picture.setVisibility(View.GONE);
1270 viewHolder.load_more_messages.setVisibility(View.VISIBLE);
1271 viewHolder.load_more_messages.setOnClickListener(
1272 v -> loadMoreMessages((Conversation) message.getConversation()));
1273 } else {
1274 viewHolder.status_message.setVisibility(View.VISIBLE);
1275 viewHolder.load_more_messages.setVisibility(View.GONE);
1276 viewHolder.status_message.setText(message.getBody());
1277 boolean showAvatar;
1278 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1279 showAvatar = true;
1280 AvatarWorkerTask.loadAvatar(
1281 message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
1282 } else if (message.getCounterpart() != null
1283 || message.getTrueCounterpart() != null
1284 || (message.getCounterparts() != null
1285 && message.getCounterparts().size() > 0)) {
1286 showAvatar = true;
1287 AvatarWorkerTask.loadAvatar(
1288 message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
1289 } else {
1290 showAvatar = false;
1291 }
1292 if (showAvatar) {
1293 viewHolder.contact_picture.setAlpha(0.5f);
1294 viewHolder.contact_picture.setVisibility(View.VISIBLE);
1295 } else {
1296 viewHolder.contact_picture.setVisibility(View.GONE);
1297 }
1298 }
1299 return view;
1300 } else {
1301 // viewHolder.message_box.setClipToOutline(true); This eats the bubble tails on A14 for some reason
1302 AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar);
1303 }
1304
1305 resetClickListener(viewHolder.message_box, viewHolder.messageBody);
1306
1307 viewHolder.message_box.setOnClickListener(v -> {
1308 if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
1309 MessageAdapter.this.mOnMessageBoxClickedListener
1310 .onContactPictureClicked(message);
1311 }
1312 });
1313 SwipeDetector swipeDetector = new SwipeDetector((action) -> {
1314 if (action == SwipeDetector.Action.LR && MessageAdapter.this.mOnMessageBoxSwipedListener != null) {
1315 MessageAdapter.this.mOnMessageBoxSwipedListener.onContactPictureClicked(message);
1316 }
1317 });
1318 viewHolder.message_box.setOnTouchListener(swipeDetector);
1319 viewHolder.image.setOnTouchListener(swipeDetector);
1320 viewHolder.time.setOnTouchListener(swipeDetector);
1321
1322 // Treat touch-up as click so we don't have to touch twice
1323 // (touch twice is because it's waiting to see if you double-touch for text selection)
1324 viewHolder.messageBody.setOnTouchListener((v, event) -> {
1325 if (event.getAction() == MotionEvent.ACTION_UP) {
1326 if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
1327 MessageAdapter.this.mOnMessageBoxClickedListener
1328 .onContactPictureClicked(message);
1329 }
1330 }
1331
1332 swipeDetector.onTouch(v, event);
1333
1334 return false;
1335 });
1336 viewHolder.messageBody.setOnClickListener(v -> {
1337 if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
1338 MessageAdapter.this.mOnMessageBoxClickedListener
1339 .onContactPictureClicked(message);
1340 }
1341 });
1342 viewHolder.contact_picture.setOnClickListener(v -> {
1343 if (MessageAdapter.this.mOnContactPictureClickedListener != null) {
1344 MessageAdapter.this.mOnContactPictureClickedListener
1345 .onContactPictureClicked(message);
1346 }
1347
1348 });
1349 viewHolder.contact_picture.setOnLongClickListener(v -> {
1350 if (MessageAdapter.this.mOnContactPictureLongClickedListener != null) {
1351 MessageAdapter.this.mOnContactPictureLongClickedListener
1352 .onContactPictureLongClicked(v, message);
1353 return true;
1354 } else {
1355 return false;
1356 }
1357 });
1358 viewHolder.messageBody.setAccessibilityDelegate(null);
1359
1360 boolean footerWrap = false;
1361
1362 final Transferable transferable = message.getTransferable();
1363 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(message);
1364
1365 final boolean muted = message.getStatus() == Message.STATUS_RECEIVED && conversation.getMode() == Conversation.MODE_MULTI && activity.xmppConnectionService.isMucUserMuted(new MucOptions.User(null, conversation.getJid(), message.getOccupantId(), null, null));
1366 if (muted) {
1367 // Muted MUC participant
1368 displayInfoMessage(viewHolder, "Muted", bubbleColor);
1369 } else if (unInitiatedButKnownSize || message.isDeleted() || (transferable != null && transferable.getStatus() != Transferable.STATUS_UPLOADING)) {
1370 if (unInitiatedButKnownSize || (message.isDeleted() && message.getModerated() == null) || transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER) {
1371 displayDownloadableMessage(viewHolder, message, activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, message)), bubbleColor, type);
1372 } else if (transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER_CHECK_FILESIZE) {
1373 displayDownloadableMessage(viewHolder, message, activity.getString(R.string.check_x_filesize, UIHelper.getFileDescriptionString(activity, message)), bubbleColor, type);
1374 } else {
1375 displayInfoMessage(viewHolder, UIHelper.getMessagePreview(activity.xmppConnectionService, message).first, bubbleColor);
1376 }
1377 } else if (message.isFileOrImage()
1378 && message.getEncryption() != Message.ENCRYPTION_PGP
1379 && message.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED) {
1380 if (message.getFileParams().width > 0 && message.getFileParams().height > 0) {
1381 displayMediaPreviewMessage(viewHolder, message, bubbleColor, type);
1382 if (!black && viewHolder.image.getLayoutParams().width > metrics.density * 110) {
1383 footerWrap = true;
1384 }
1385 } else if (message.getFileParams().runtime > 0) {
1386 displayAudioMessage(viewHolder, message, bubbleColor, type);
1387 } else if ("application/xdc+zip".equals(message.getFileParams().getMediaType()) && message.getConversation() instanceof Conversation && message.getThread() != null && !message.getFileParams().getCids().isEmpty()) {
1388 displayWebxdcMessage(viewHolder, message, bubbleColor, type);
1389 } else {
1390 displayOpenableMessage(viewHolder, message, bubbleColor, type);
1391 }
1392 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
1393 if (account.isPgpDecryptionServiceConnected()) {
1394 if (conversation instanceof Conversation
1395 && !account.hasPendingPgpIntent((Conversation) conversation)) {
1396 displayInfoMessage(
1397 viewHolder,
1398 activity.getString(R.string.message_decrypting),
1399 bubbleColor);
1400 } else {
1401 displayInfoMessage(
1402 viewHolder, activity.getString(R.string.pgp_message), bubbleColor);
1403 }
1404 } else {
1405 displayInfoMessage(
1406 viewHolder, activity.getString(R.string.install_openkeychain), bubbleColor);
1407 viewHolder.message_box.setOnClickListener(this::promptOpenKeychainInstall);
1408 viewHolder.messageBody.setOnClickListener(this::promptOpenKeychainInstall);
1409 }
1410 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1411 displayInfoMessage(
1412 viewHolder, activity.getString(R.string.decryption_failed), bubbleColor);
1413 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
1414 displayInfoMessage(
1415 viewHolder,
1416 activity.getString(R.string.not_encrypted_for_this_device),
1417 bubbleColor);
1418 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1419 displayInfoMessage(
1420 viewHolder, activity.getString(R.string.omemo_decryption_failed), bubbleColor);
1421 } else {
1422 if (message.isGeoUri()) {
1423 displayLocationMessage(viewHolder, message, bubbleColor, type);
1424 } else if (message.treatAsDownloadable()) {
1425 try {
1426 final URI uri = message.getOob();
1427 displayDownloadableMessage(viewHolder,
1428 message,
1429 activity.getString(
1430 R.string.check_x_filesize_on_host,
1431 UIHelper.getFileDescriptionString(activity, message),
1432 uri.getHost()),
1433 bubbleColor, type);
1434 } catch (Exception e) {
1435 displayDownloadableMessage(
1436 viewHolder,
1437 message,
1438 activity.getString(
1439 R.string.check_x_filesize,
1440 UIHelper.getFileDescriptionString(activity, message)),
1441 bubbleColor, type);
1442 }
1443 } else if (message.bodyIsOnlyEmojis() && message.getType() != Message.TYPE_PRIVATE) {
1444 displayEmojiMessage(viewHolder, message, bubbleColor, type);
1445 } else {
1446 displayTextMessage(viewHolder, message, bubbleColor, message.getType());
1447 }
1448 }
1449
1450 viewHolder.message_box_inner.setMinimumWidth(footerWrap ? (int) (110 * metrics.density) : 0);
1451 LinearLayout.LayoutParams statusParams = (LinearLayout.LayoutParams) viewHolder.status_line.getLayoutParams();
1452 statusParams.width = footerWrap ? ViewGroup.LayoutParams.MATCH_PARENT : ViewGroup.LayoutParams.WRAP_CONTENT;
1453 viewHolder.status_line.setLayoutParams(statusParams);
1454
1455 setBackgroundTint(viewHolder.message_box, bubbleColor);
1456 setTextColor(viewHolder.messageBody, bubbleColor);
1457 viewHolder.messageBody.setLinkTextColor(bubbleToOnSurfaceColor(viewHolder.messageBody, bubbleColor));
1458
1459 if (type == RECEIVED) {
1460 if (!muted && commands != null && conversation instanceof Conversation) {
1461 CommandButtonAdapter adapter = new CommandButtonAdapter(activity);
1462 adapter.addAll(commands);
1463 viewHolder.commands_list.setAdapter(adapter);
1464 viewHolder.commands_list.setVisibility(View.VISIBLE);
1465 viewHolder.commands_list.setOnItemClickListener((p, v, pos, id) -> {
1466 final Element command = adapter.getItem(pos);
1467 activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
1468 });
1469 } else {
1470 // It's unclear if we can set this to null...
1471 ListAdapter adapter = viewHolder.commands_list.getAdapter();
1472 if (adapter instanceof ArrayAdapter) {
1473 ((ArrayAdapter<?>) adapter).clear();
1474 }
1475 viewHolder.commands_list.setVisibility(View.GONE);
1476 viewHolder.commands_list.setOnItemClickListener(null);
1477 }
1478
1479 setTextColor(viewHolder.encryption, bubbleColor);
1480
1481 if (isInValidSession) {
1482 viewHolder.encryption.setVisibility(View.GONE);
1483 } else {
1484 viewHolder.encryption.setVisibility(View.VISIBLE);
1485 if (omemoEncryption && !message.isTrusted()) {
1486 viewHolder.encryption.setText(R.string.not_trusted);
1487 } else {
1488 viewHolder.encryption.setText(
1489 CryptoHelper.encryptionTypeToText(message.getEncryption()));
1490 }
1491 }
1492 }
1493
1494 if (type == RECEIVED || type == SENT) {
1495 String subject = message.getSubject();
1496 if (subject == null && message.getThread() != null) {
1497 final var thread = ((Conversation) message.getConversation()).getThread(message.getThread().getContent());
1498 if (thread != null) subject = thread.getSubject();
1499 }
1500 if (muted || subject == null) {
1501 viewHolder.subject.setVisibility(View.GONE);
1502 } else {
1503 viewHolder.subject.setVisibility(View.VISIBLE);
1504 viewHolder.subject.setText(subject);
1505 }
1506
1507 if (message.getInReplyTo() == null) {
1508 viewHolder.inReplyToBox.setVisibility(View.GONE);
1509 } else {
1510 viewHolder.inReplyToBox.setVisibility(View.VISIBLE);
1511 viewHolder.inReplyTo.setText(UIHelper.getMessageDisplayName(message.getInReplyTo()));
1512 viewHolder.inReplyTo.setOnClickListener((v) -> mConversationFragment.jumpTo(message.getInReplyTo()));
1513 viewHolder.inReplyToQuote.setOnClickListener((v) -> mConversationFragment.jumpTo(message.getInReplyTo()));
1514 setTextColor(viewHolder.inReplyTo, bubbleColor);
1515 }
1516 }
1517
1518 displayStatus(viewHolder, message, type, bubbleColor);
1519
1520 viewHolder.messageBody.setAccessibilityDelegate(new View.AccessibilityDelegate() {
1521 @Override
1522 public void sendAccessibilityEvent(View host, int eventType) {
1523 super.sendAccessibilityEvent(host, eventType);
1524 if (eventType == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
1525 if (viewHolder.messageBody.hasSelection()) {
1526 selectionUuid = message.getUuid();
1527 } else if (message.getUuid() != null && message.getUuid().equals(selectionUuid)) {
1528 selectionUuid = null;
1529 }
1530 }
1531 }
1532 });
1533
1534 return view;
1535 }
1536
1537 private void promptOpenKeychainInstall(View view) {
1538 activity.showInstallPgpDialog();
1539 }
1540
1541 public FileBackend getFileBackend() {
1542 return activity.xmppConnectionService.getFileBackend();
1543 }
1544
1545 public void stopAudioPlayer() {
1546 audioPlayer.stop();
1547 }
1548
1549 public void unregisterListenerInAudioPlayer() {
1550 audioPlayer.unregisterListener();
1551 }
1552
1553 public void startStopPending() {
1554 audioPlayer.startStopPending();
1555 }
1556
1557 public void openDownloadable(Message message) {
1558 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
1559 && ContextCompat.checkSelfPermission(
1560 activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
1561 != PackageManager.PERMISSION_GRANTED) {
1562 ConversationFragment.registerPendingMessage(activity, message);
1563 ActivityCompat.requestPermissions(
1564 activity,
1565 new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
1566 ConversationsActivity.REQUEST_OPEN_MESSAGE);
1567 return;
1568 }
1569 final DownloadableFile file =
1570 activity.xmppConnectionService.getFileBackend().getFile(message);
1571 ViewUtil.view(activity, file);
1572 }
1573
1574 private void showLocation(Message message) {
1575 for (Intent intent : GeoHelper.createGeoIntentsFromMessage(activity, message)) {
1576 if (intent.resolveActivity(getContext().getPackageManager()) != null) {
1577 getContext().startActivity(intent);
1578 return;
1579 }
1580 }
1581 Toast.makeText(
1582 activity,
1583 R.string.no_application_found_to_display_location,
1584 Toast.LENGTH_SHORT)
1585 .show();
1586 }
1587
1588 public void updatePreferences() {
1589 final AppSettings appSettings = new AppSettings(activity);
1590 this.bubbleDesign =
1591 new BubbleDesign(appSettings.isColorfulChatBubbles(), appSettings.isLargeFont());
1592 }
1593
1594 public void setHighlightedTerm(List<String> terms) {
1595 this.highlightedTerm = terms == null ? null : StylingHelper.filterHighlightedWords(terms);
1596 }
1597
1598 public interface OnContactPictureClicked {
1599 void onContactPictureClicked(Message message);
1600 }
1601
1602 public interface OnContactPictureLongClicked {
1603 void onContactPictureLongClicked(View v, Message message);
1604 }
1605
1606 public interface OnInlineImageLongClicked {
1607 boolean onInlineImageLongClicked(Cid cid);
1608 }
1609
1610 private static void setBackgroundTint(final View view, final BubbleColor bubbleColor) {
1611 view.setBackgroundTintList(bubbleToColorStateList(view, bubbleColor));
1612 }
1613
1614 private static ColorStateList bubbleToColorStateList(
1615 final View view, final BubbleColor bubbleColor) {
1616 final @AttrRes int colorAttributeResId =
1617 switch (bubbleColor) {
1618 case SURFACE -> Activities.isNightMode(view.getContext())
1619 ? com.google.android.material.R.attr.colorSurfaceContainerHigh
1620 : com.google.android.material.R.attr.colorSurfaceContainerLow;
1621 case SURFACE_HIGH -> Activities.isNightMode(view.getContext())
1622 ? com.google.android.material.R.attr.colorSurfaceContainerHighest
1623 : com.google.android.material.R.attr.colorSurfaceContainerHigh;
1624 case PRIMARY -> com.google.android.material.R.attr.colorPrimaryContainer;
1625 case SECONDARY -> com.google.android.material.R.attr.colorSecondaryContainer;
1626 case TERTIARY -> com.google.android.material.R.attr.colorTertiaryContainer;
1627 case WARNING -> com.google.android.material.R.attr.colorErrorContainer;
1628 };
1629 return ColorStateList.valueOf(MaterialColors.getColor(view, colorAttributeResId));
1630 }
1631
1632 public static void setImageTint(final ImageView imageView, final BubbleColor bubbleColor) {
1633 ImageViewCompat.setImageTintList(
1634 imageView, bubbleToOnSurfaceColorStateList(imageView, bubbleColor));
1635 }
1636
1637 public static void setImageTintError(final ImageView imageView) {
1638 ImageViewCompat.setImageTintList(
1639 imageView,
1640 ColorStateList.valueOf(
1641 MaterialColors.getColor(
1642 imageView, com.google.android.material.R.attr.colorError)));
1643 }
1644
1645 public static void setTextColor(final TextView textView, final BubbleColor bubbleColor) {
1646 final var color = bubbleToOnSurfaceColor(textView, bubbleColor);
1647 textView.setTextColor(color);
1648 if (BubbleColor.SURFACES.contains(bubbleColor)) {
1649 textView.setLinkTextColor(
1650 MaterialColors.getColor(
1651 textView, com.google.android.material.R.attr.colorPrimary));
1652 } else {
1653 textView.setLinkTextColor(color);
1654 }
1655 }
1656
1657 private static void setTextSize(final TextView textView, final boolean largeFont) {
1658 if (largeFont) {
1659 textView.setTextAppearance(
1660 com.google.android.material.R.style.TextAppearance_Material3_BodyLarge);
1661 textView.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 18);
1662 } else {
1663 textView.setTextAppearance(
1664 com.google.android.material.R.style.TextAppearance_Material3_BodyMedium);
1665 }
1666 }
1667
1668 private static @ColorInt int bubbleToOnSurfaceVariant(
1669 final View view, final BubbleColor bubbleColor) {
1670 final @AttrRes int colorAttributeResId;
1671 if (BubbleColor.SURFACES.contains(bubbleColor)) {
1672 colorAttributeResId = com.google.android.material.R.attr.colorOnSurfaceVariant;
1673 } else {
1674 colorAttributeResId = bubbleToOnSurface(bubbleColor);
1675 }
1676 return MaterialColors.getColor(view, colorAttributeResId);
1677 }
1678
1679 private static @ColorInt int bubbleToOnSurfaceColor(
1680 final View view, final BubbleColor bubbleColor) {
1681 return MaterialColors.getColor(view, bubbleToOnSurface(bubbleColor));
1682 }
1683
1684 public static ColorStateList bubbleToOnSurfaceColorStateList(
1685 final View view, final BubbleColor bubbleColor) {
1686 return ColorStateList.valueOf(bubbleToOnSurfaceColor(view, bubbleColor));
1687 }
1688
1689 private static @AttrRes int bubbleToOnSurface(final BubbleColor bubbleColor) {
1690 return switch (bubbleColor) {
1691 case SURFACE, SURFACE_HIGH -> com.google.android.material.R.attr.colorOnSurface;
1692 case PRIMARY -> com.google.android.material.R.attr.colorOnPrimaryContainer;
1693 case SECONDARY -> com.google.android.material.R.attr.colorOnSecondaryContainer;
1694 case TERTIARY -> com.google.android.material.R.attr.colorOnTertiaryContainer;
1695 case WARNING -> com.google.android.material.R.attr.colorOnErrorContainer;
1696 };
1697 }
1698
1699 public enum BubbleColor {
1700 SURFACE,
1701 SURFACE_HIGH,
1702 PRIMARY,
1703 SECONDARY,
1704 TERTIARY,
1705 WARNING;
1706
1707 private static final Collection<BubbleColor> SURFACES =
1708 Arrays.asList(BubbleColor.SURFACE, BubbleColor.SURFACE_HIGH);
1709 }
1710
1711 private static class BubbleDesign {
1712 public final boolean colorfulChatBubbles;
1713 public final boolean largeFont;
1714
1715 private BubbleDesign(final boolean colorfulChatBubbles, final boolean largeFont) {
1716 this.colorfulChatBubbles = colorfulChatBubbles;
1717 this.largeFont = largeFont;
1718 }
1719 }
1720
1721 private static class ViewHolder {
1722
1723 public MaterialButton load_more_messages;
1724 public ImageView edit_indicator;
1725 public RelativeLayout audioPlayer;
1726 protected View status_line;
1727 protected LinearLayout message_box;
1728 protected View message_box_inner;
1729 protected MaterialButton download_button;
1730 protected ShapeableImageView image;
1731 protected ImageView indicator;
1732 protected ImageView indicatorReceived;
1733 protected TextView time;
1734 protected TextView subject;
1735 protected TextView inReplyTo;
1736 protected TextView inReplyToQuote;
1737 protected LinearLayout inReplyToBox;
1738 protected TextView messageBody;
1739 protected ImageView contact_picture;
1740 protected TextView status_message;
1741 protected TextView encryption;
1742 protected ListView commands_list;
1743 protected GithubIdenticonView thread_identicon;
1744 }
1745
1746 class ThumbnailTask extends AsyncTask<DownloadableFile, Void, Drawable[]> {
1747 @Override
1748 protected Drawable[] doInBackground(DownloadableFile... params) {
1749 if (isCancelled()) return null;
1750
1751 Drawable[] d = new Drawable[params.length];
1752 for (int i = 0; i < params.length; i++) {
1753 try {
1754 d[i] = activity.xmppConnectionService.getFileBackend().getThumbnail(params[i], activity.getResources(), (int) (metrics.density * 288), false);
1755 } catch (final IOException e) {
1756 d[i] = null;
1757 }
1758 }
1759
1760 return d;
1761 }
1762
1763 @Override
1764 protected void onPostExecute(final Drawable[] d) {
1765 if (isCancelled()) return;
1766 activity.xmppConnectionService.updateConversationUi();
1767 }
1768 }
1769}