MessageAdapter.java

   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            if (processMarkup) StylingHelper.format(body, viewHolder.messageBody.getCurrentTextColor());
 641            MyLinkify.addLinks(body, message.getConversation().getAccount(), message.getConversation().getJid());
 642            boolean startsWithQuote = processMarkup ? handleTextQuotes(viewHolder.messageBody, body, bubbleColor, true) : false;
 643            for (final android.text.style.QuoteSpan quote : body.getSpans(0, body.length(), android.text.style.QuoteSpan.class)) {
 644                int start = body.getSpanStart(quote);
 645                int end = body.getSpanEnd(quote);
 646                if (start < 0 || end < 0) continue;
 647
 648                body.removeSpan(quote);
 649                applyQuoteSpan(viewHolder.messageBody, body, start, end, bubbleColor, true);
 650                if (start == 0) {
 651                    if (message.getInReplyTo() == null) {
 652                        startsWithQuote = true;
 653                    } else {
 654                        viewHolder.inReplyToQuote.setText(body.subSequence(start, end));
 655                        viewHolder.inReplyToQuote.setVisibility(View.VISIBLE);
 656                        body.delete(start, end);
 657                        while (body.length() > start && body.charAt(start) == '\n') body.delete(start, 1); // Newlines after quote
 658                        continue;
 659                    }
 660                }
 661            }
 662            if (!message.isPrivateMessage()) {
 663                if (hasMeCommand) {
 664                    body.setSpan(
 665                            new StyleSpan(Typeface.BOLD_ITALIC),
 666                            0,
 667                            nick.length(),
 668                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 669                }
 670            } else {
 671                String privateMarker;
 672                if (message.getStatus() <= Message.STATUS_RECEIVED) {
 673                    privateMarker = activity.getString(R.string.private_message);
 674                } else {
 675                    Jid cp = message.getCounterpart();
 676                    privateMarker =
 677                            activity.getString(
 678                                    R.string.private_message_to,
 679                                    Strings.nullToEmpty(cp == null ? null : cp.getResource()));
 680                }
 681                body.insert(0, privateMarker);
 682                int privateMarkerIndex = privateMarker.length();
 683                if (startsWithQuote) {
 684                    body.insert(privateMarkerIndex, "\n\n");
 685                    body.setSpan(
 686                            new DividerSpan(false),
 687                            privateMarkerIndex,
 688                            privateMarkerIndex + 2,
 689                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 690                } else {
 691                    body.insert(privateMarkerIndex, " ");
 692                }
 693                body.setSpan(
 694                        new ForegroundColorSpan(
 695                                bubbleToOnSurfaceVariant(viewHolder.messageBody, bubbleColor)),
 696                        0,
 697                        privateMarkerIndex,
 698                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 699                body.setSpan(
 700                        new StyleSpan(Typeface.BOLD),
 701                        0,
 702                        privateMarkerIndex,
 703                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 704                if (hasMeCommand) {
 705                    body.setSpan(
 706                            new StyleSpan(Typeface.BOLD_ITALIC),
 707                            privateMarkerIndex + 1,
 708                            privateMarkerIndex + 1 + nick.length(),
 709                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 710                }
 711            }
 712            if (message.getConversation().getMode() == Conversation.MODE_MULTI
 713                    && message.getStatus() == Message.STATUS_RECEIVED) {
 714                if (message.getConversation() instanceof Conversation conversation) {
 715                    Pattern pattern =
 716                            NotificationService.generateNickHighlightPattern(
 717                                    conversation.getMucOptions().getActualNick());
 718                    Matcher matcher = pattern.matcher(body);
 719                    while (matcher.find()) {
 720                        body.setSpan(
 721                                new StyleSpan(Typeface.BOLD),
 722                                matcher.start(),
 723                                matcher.end(),
 724                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 725                    }
 726
 727                    pattern = NotificationService.generateNickHighlightPattern(conversation.getMucOptions().getActualName());
 728                    matcher = pattern.matcher(body);
 729                    while (matcher.find()) {
 730                        body.setSpan(new StyleSpan(Typeface.BOLD), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 731                    }
 732                }
 733            }
 734            for (final var emoji : EmojiManager.extractEmojisInOrderWithIndex(body.toString())) {
 735                var end = emoji.getCharIndex() + emoji.getEmoji().getEmoji().length();
 736                if (body.length() > end && body.charAt(end) == '\uFE0F') end++;
 737                body.setSpan(
 738                        new RelativeSizeSpan(1.2f),
 739                        emoji.getCharIndex(),
 740                        end,
 741                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 742            }
 743            // Make custom emoji bigger too, to match emoji
 744            for (final var span : body.getSpans(0, body.length(), com.cheogram.android.InlineImageSpan.class)) {
 745                body.setSpan(
 746                        new RelativeSizeSpan(1.2f),
 747                        body.getSpanStart(span),
 748                        body.getSpanEnd(span),
 749                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 750            }
 751
 752            if (highlightedTerm != null) {
 753                StylingHelper.highlight(viewHolder.messageBody, body, highlightedTerm);
 754            }
 755
 756            viewHolder.messageBody.setAutoLinkMask(0);
 757            viewHolder.messageBody.setText(body);
 758            if (body.length() <= 0) viewHolder.messageBody.setVisibility(View.GONE);
 759            BetterLinkMovementMethod method = new BetterLinkMovementMethod() {
 760                @Override
 761                protected void dispatchUrlLongClick(TextView tv, ClickableSpan span) {
 762                    if (span instanceof URLSpan || mOnInlineImageLongClickedListener == null) {
 763                        tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
 764                        super.dispatchUrlLongClick(tv, span);
 765                        return;
 766                    }
 767
 768                    Spannable body = (Spannable) tv.getText();
 769                    ImageSpan[] imageSpans = body.getSpans(body.getSpanStart(span), body.getSpanEnd(span), ImageSpan.class);
 770                    if (imageSpans.length > 0) {
 771                        Uri uri = Uri.parse(imageSpans[0].getSource());
 772                        Cid cid = BobTransfer.cid(uri);
 773                        if (cid == null) return;
 774                        if (mOnInlineImageLongClickedListener.onInlineImageLongClicked(cid)) {
 775                            tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
 776                        }
 777                    }
 778                }
 779            };
 780            method.setOnLinkLongClickListener((tv, url) -> {
 781                tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
 782                ShareUtil.copyLinkToClipboard(activity, url);
 783                return true;
 784            });
 785            viewHolder.messageBody.setMovementMethod(method);
 786        } else {
 787            viewHolder.messageBody.setText("");
 788            viewHolder.messageBody.setTextIsSelectable(false);
 789            toggleWhisperInfo(viewHolder, message, bubbleColor);
 790        }
 791    }
 792
 793    private void displayDownloadableMessage(
 794            ViewHolder viewHolder,
 795            final Message message,
 796            String text,
 797            final BubbleColor bubbleColor, final int type) {
 798        displayTextMessage(viewHolder, message, bubbleColor, type);
 799        viewHolder.image.setVisibility(View.GONE);
 800        List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
 801        if (thumbs != null && !thumbs.isEmpty()) {
 802            for (Element thumb : thumbs) {
 803                Uri uri = Uri.parse(thumb.getAttribute("uri"));
 804                if (uri.getScheme().equals("data")) {
 805                    String[] parts = uri.getSchemeSpecificPart().split(",", 2);
 806                    parts = parts[0].split(";");
 807                    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;
 808                } else if (uri.getScheme().equals("cid")) {
 809                    Cid cid = BobTransfer.cid(uri);
 810                    if (cid == null) continue;
 811                    DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
 812                    if (f == null || !f.canRead()) {
 813                        if (!message.trusted() && !message.getConversation().canInferPresence()) continue;
 814
 815                        try {
 816                            new BobTransfer(BobTransfer.uri(cid), message.getConversation().getAccount(), message.getCounterpart(), activity.xmppConnectionService).start();
 817                        } catch (final NoSuchAlgorithmException | URISyntaxException e) { }
 818                        continue;
 819                    }
 820                } else {
 821                    continue;
 822                }
 823
 824                int width = message.getFileParams().width;
 825                if (width < 1 && thumb.getAttribute("width") != null) width = Integer.parseInt(thumb.getAttribute("width"));
 826                if (width < 1) width = 1920;
 827
 828                int height = message.getFileParams().height;
 829                if (height < 1 && thumb.getAttribute("height") != null) height = Integer.parseInt(thumb.getAttribute("height"));
 830                if (height < 1) height = 1080;
 831
 832                viewHolder.image.setVisibility(View.VISIBLE);
 833                imagePreviewLayout(width, height, viewHolder.image, message.getInReplyTo() != null, true, type, viewHolder);
 834                activity.loadBitmap(message, viewHolder.image);
 835                viewHolder.image.setOnClickListener(v -> ConversationFragment.downloadFile(activity, message));
 836
 837                break;
 838            }
 839        }
 840        viewHolder.audioPlayer.setVisibility(View.GONE);
 841        viewHolder.download_button.setVisibility(View.VISIBLE);
 842        viewHolder.download_button.setText(text);
 843        final var attachment = Attachment.of(message);
 844        final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
 845        viewHolder.download_button.setIconResource(imageResource);
 846        viewHolder.download_button.setOnClickListener(
 847                v -> ConversationFragment.downloadFile(activity, message));
 848    }
 849
 850    private void displayWebxdcMessage(ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
 851        Cid webxdcCid = message.getFileParams().getCids().get(0);
 852        WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
 853        displayTextMessage(viewHolder, message, bubbleColor, type);
 854        viewHolder.image.setVisibility(View.GONE);
 855        viewHolder.audioPlayer.setVisibility(View.GONE);
 856        viewHolder.download_button.setVisibility(View.VISIBLE);
 857        viewHolder.download_button.setIconResource(0);
 858        viewHolder.download_button.setText("Open " + webxdc.getName());
 859        viewHolder.download_button.setOnClickListener(v -> {
 860            Conversation conversation = (Conversation) message.getConversation();
 861            if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
 862                conversation.startWebxdc(webxdc);
 863            }
 864        });
 865        viewHolder.image.setOnClickListener(v -> {
 866            Conversation conversation = (Conversation) message.getConversation();
 867            if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
 868                conversation.startWebxdc(webxdc);
 869            }
 870        });
 871
 872        final WebxdcUpdate lastUpdate;
 873        synchronized(lastWebxdcUpdate) { lastUpdate = lastWebxdcUpdate.get(message.getUuid()); }
 874        if (lastUpdate == null) {
 875            new Thread(() -> {
 876                final WebxdcUpdate update = activity.xmppConnectionService.findLastWebxdcUpdate(message);
 877                if (update != null) {
 878                    synchronized(lastWebxdcUpdate) { lastWebxdcUpdate.put(message.getUuid(), update); }
 879                    activity.xmppConnectionService.updateConversationUi();
 880                }
 881            }).start();
 882        } else {
 883            if (lastUpdate != null && (lastUpdate.getSummary() != null || lastUpdate.getDocument() != null)) {
 884                viewHolder.messageBody.setVisibility(View.VISIBLE);
 885                viewHolder.messageBody.setText(
 886                    (lastUpdate.getDocument() == null ? "" : lastUpdate.getDocument() + "\n") +
 887                    (lastUpdate.getSummary() == null ? "" : lastUpdate.getSummary())
 888                );
 889            }
 890        }
 891
 892        final LruCache<String, Drawable> cache = activity.xmppConnectionService.getDrawableCache();
 893        final Drawable d = cache.get("webxdc:icon:" + webxdcCid);
 894        if (d == null) {
 895            new Thread(() -> {
 896                Drawable icon = webxdc.getIcon();
 897                if (icon != null) {
 898                    cache.put("webxdc:icon:" + webxdcCid, icon);
 899                    activity.xmppConnectionService.updateConversationUi();
 900                }
 901            }).start();
 902        } else {
 903            viewHolder.image.setVisibility(View.VISIBLE);
 904            viewHolder.image.setImageDrawable(d);
 905            imagePreviewLayout(d.getIntrinsicWidth(), d.getIntrinsicHeight(), viewHolder.image, message.getInReplyTo() != null, true, type, viewHolder);
 906        }
 907    }
 908
 909    private void displayOpenableMessage(
 910            ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
 911        displayTextMessage(viewHolder, message, bubbleColor, type);
 912        viewHolder.image.setVisibility(View.GONE);
 913        viewHolder.audioPlayer.setVisibility(View.GONE);
 914        viewHolder.download_button.setVisibility(View.VISIBLE);
 915        viewHolder.download_button.setText(
 916                activity.getString(
 917                        R.string.open_x_file,
 918                        UIHelper.getFileDescriptionString(activity, message)));
 919        final var attachment = Attachment.of(message);
 920        final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
 921        viewHolder.download_button.setIconResource(imageResource);
 922        viewHolder.download_button.setOnClickListener(v -> openDownloadable(message));
 923    }
 924
 925    private void displayLocationMessage(
 926            ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
 927        displayTextMessage(viewHolder, message, bubbleColor, type);
 928        viewHolder.image.setVisibility(View.GONE);
 929        viewHolder.audioPlayer.setVisibility(View.GONE);
 930        viewHolder.download_button.setVisibility(View.VISIBLE);
 931        viewHolder.download_button.setText(R.string.show_location);
 932        final var attachment = Attachment.of(message);
 933        final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
 934        viewHolder.download_button.setIconResource(imageResource);
 935        viewHolder.download_button.setOnClickListener(v -> showLocation(message));
 936    }
 937
 938    private void displayAudioMessage(
 939            ViewHolder viewHolder, Message message, final BubbleColor bubbleColor, final int type) {
 940        displayTextMessage(viewHolder, message, bubbleColor, type);
 941        viewHolder.image.setVisibility(View.GONE);
 942        viewHolder.download_button.setVisibility(View.GONE);
 943        final RelativeLayout audioPlayer = viewHolder.audioPlayer;
 944        audioPlayer.setVisibility(View.VISIBLE);
 945        AudioPlayer.ViewHolder.get(audioPlayer).setBubbleColor(bubbleColor);
 946        this.audioPlayer.init(audioPlayer, message);
 947    }
 948
 949    private void displayMediaPreviewMessage(
 950            ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, final int type) {
 951        displayTextMessage(viewHolder, message, bubbleColor, type);
 952        viewHolder.download_button.setVisibility(View.GONE);
 953        viewHolder.audioPlayer.setVisibility(View.GONE);
 954        viewHolder.image.setVisibility(View.VISIBLE);
 955        final FileParams params = message.getFileParams();
 956        imagePreviewLayout(params.width, params.height, viewHolder.image, message.getInReplyTo() != null, viewHolder.messageBody.getVisibility() != View.GONE, type, viewHolder);
 957        activity.loadBitmap(message, viewHolder.image);
 958        viewHolder.image.setOnClickListener(v -> openDownloadable(message));
 959    }
 960
 961    private void imagePreviewLayout(int w, int h, ShapeableImageView image, boolean otherAbove, boolean otherBelow, int type, ViewHolder viewHolder) {
 962        final float target = activity.getResources().getDimension(R.dimen.image_preview_width);
 963        final int scaledW;
 964        final int scaledH;
 965        if (Math.max(h, w) * metrics.density <= target) {
 966            scaledW = (int) (w * metrics.density);
 967            scaledH = (int) (h * metrics.density);
 968        } else if (Math.max(h, w) <= target) {
 969            scaledW = w;
 970            scaledH = h;
 971        } else if (w <= h) {
 972            scaledW = (int) (w / ((double) h / target));
 973            scaledH = (int) target;
 974        } else {
 975            scaledW = (int) target;
 976            scaledH = (int) (h / ((double) w / target));
 977        }
 978        final var bodyWidth = Math.max(viewHolder.messageBody.getWidth(), viewHolder.download_button.getWidth() + (20 * metrics.density));
 979        var targetImageWidth = 200 * metrics.density;
 980        if (!otherBelow) targetImageWidth = 110 * metrics.density;
 981        if (bodyWidth > 0 && bodyWidth < targetImageWidth) targetImageWidth = bodyWidth;
 982        final var small = scaledW < targetImageWidth;
 983        final LinearLayout.LayoutParams layoutParams =
 984                new LinearLayout.LayoutParams(scaledW, scaledH);
 985        image.setLayoutParams(layoutParams);
 986
 987        final var bubbleRadius = activity.getResources().getDimension(R.dimen.bubble_radius);
 988        var shape = new ShapeAppearanceModel.Builder();
 989        if (!otherAbove) {
 990            shape = shape.setTopRightCorner(CornerFamily.ROUNDED, bubbleRadius);
 991            if (type == SENT) {
 992                shape = shape.setTopLeftCorner(CornerFamily.ROUNDED, bubbleRadius);
 993            }
 994        }
 995        if (small) {
 996            final var imageRadius = activity.getResources().getDimension(R.dimen.image_radius);
 997            shape = shape.setAllCorners(CornerFamily.ROUNDED, imageRadius);
 998            image.setPadding(0, (int)(8 * metrics.density), 0, 0);
 999        } else {
1000            image.setPadding(0, 0, 0, 0);
1001        }
1002        image.setShapeAppearanceModel(shape.build());
1003
1004        if (!small) {
1005            final ViewGroup.LayoutParams blayoutParams = viewHolder.messageBody.getLayoutParams();
1006            blayoutParams.width = (int) (scaledW - (22 * metrics.density));
1007            viewHolder.messageBody.setLayoutParams(blayoutParams);
1008
1009            final ViewGroup.LayoutParams qlayoutParams = viewHolder.inReplyToQuote.getLayoutParams();
1010            qlayoutParams.width = (int) (scaledW - (22 * metrics.density));
1011            viewHolder.messageBody.setLayoutParams(qlayoutParams);
1012        }
1013    }
1014
1015    private void toggleWhisperInfo(
1016            ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor) {
1017        if (message.isPrivateMessage()) {
1018            final String privateMarker;
1019            if (message.getStatus() <= Message.STATUS_RECEIVED) {
1020                privateMarker = activity.getString(R.string.private_message);
1021            } else {
1022                Jid cp = message.getCounterpart();
1023                privateMarker =
1024                        activity.getString(
1025                                R.string.private_message_to,
1026                                Strings.nullToEmpty(cp == null ? null : cp.getResource()));
1027            }
1028            final SpannableString body = new SpannableString(privateMarker);
1029            body.setSpan(
1030                    new ForegroundColorSpan(
1031                            bubbleToOnSurfaceVariant(viewHolder.messageBody, bubbleColor)),
1032                    0,
1033                    privateMarker.length(),
1034                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1035            body.setSpan(
1036                    new StyleSpan(Typeface.BOLD),
1037                    0,
1038                    privateMarker.length(),
1039                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1040            viewHolder.messageBody.setText(body);
1041            viewHolder.messageBody.setVisibility(View.VISIBLE);
1042        } else {
1043            viewHolder.messageBody.setVisibility(View.GONE);
1044        }
1045    }
1046
1047    private void loadMoreMessages(Conversation conversation) {
1048        conversation.setLastClearHistory(0, null);
1049        activity.xmppConnectionService.updateConversation(conversation);
1050        conversation.setHasMessagesLeftOnServer(true);
1051        conversation.setFirstMamReference(null);
1052        long timestamp = conversation.getLastMessageTransmitted().getTimestamp();
1053        if (timestamp == 0) {
1054            timestamp = System.currentTimeMillis();
1055        }
1056        conversation.messagesLoaded.set(true);
1057        MessageArchiveService.Query query =
1058                activity.xmppConnectionService
1059                        .getMessageArchiveService()
1060                        .query(conversation, new MamReference(0), timestamp, false);
1061        if (query != null) {
1062            Toast.makeText(activity, R.string.fetching_history_from_server, Toast.LENGTH_LONG)
1063                    .show();
1064        } else {
1065            Toast.makeText(
1066                            activity,
1067                            R.string.not_fetching_history_retention_period,
1068                            Toast.LENGTH_SHORT)
1069                    .show();
1070        }
1071    }
1072
1073    @Override
1074    public View getView(final int position, View view, final @NonNull ViewGroup parent) {
1075        final Message message = getItem(position);
1076        final boolean omemoEncryption = message.getEncryption() == Message.ENCRYPTION_AXOLOTL;
1077        final boolean isInValidSession =
1078                message.isValidInSession() && (!omemoEncryption || message.isTrusted());
1079        final Conversational conversation = message.getConversation();
1080        final Account account = conversation.getAccount();
1081        final List<Element> commands = message.getCommands();
1082        final int type = getItemViewType(position);
1083        ViewHolder viewHolder;
1084        if (view == null) {
1085            viewHolder = new ViewHolder();
1086            switch (type) {
1087                case DATE_SEPARATOR:
1088                    view =
1089                            activity.getLayoutInflater()
1090                                    .inflate(R.layout.item_message_date_bubble, parent, false);
1091                    viewHolder.status_message = view.findViewById(R.id.message_body);
1092                    viewHolder.message_box = view.findViewById(R.id.message_box);
1093                    break;
1094                case RTP_SESSION:
1095                    view =
1096                            activity.getLayoutInflater()
1097                                    .inflate(R.layout.item_message_rtp_session, parent, false);
1098                    viewHolder.status_message = view.findViewById(R.id.message_body);
1099                    viewHolder.message_box = view.findViewById(R.id.message_box);
1100                    viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
1101                    break;
1102                case SENT:
1103                    view = activity.getLayoutInflater().inflate(R.layout.item_message_sent, parent, false);
1104                    viewHolder.status_line = view.findViewById(R.id.status_line);
1105                    viewHolder.message_box_inner = view.findViewById(R.id.message_box_inner);
1106                    viewHolder.message_box = view.findViewById(R.id.message_box);
1107                    viewHolder.contact_picture = view.findViewById(R.id.message_photo);
1108                    viewHolder.download_button = view.findViewById(R.id.download_button);
1109                    viewHolder.indicator = view.findViewById(R.id.security_indicator);
1110                    viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
1111                    viewHolder.image = view.findViewById(R.id.message_image);
1112                    viewHolder.messageBody = view.findViewById(R.id.message_body);
1113                    viewHolder.time = view.findViewById(R.id.message_time);
1114                    viewHolder.subject = view.findViewById(R.id.message_subject);
1115                    viewHolder.inReplyTo = view.findViewById(R.id.in_reply_to);
1116                    viewHolder.inReplyToBox = view.findViewById(R.id.in_reply_to_box);
1117                    viewHolder.inReplyToQuote = view.findViewById(R.id.in_reply_to_quote);
1118                    viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
1119                    viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
1120                    viewHolder.thread_identicon = view.findViewById(R.id.thread_identicon);
1121                    break;
1122                case RECEIVED:
1123                    view = activity.getLayoutInflater().inflate(R.layout.item_message_received, parent, false);
1124                    viewHolder.status_line = view.findViewById(R.id.status_line);
1125                    viewHolder.message_box_inner = view.findViewById(R.id.message_box_inner);
1126                    viewHolder.message_box = view.findViewById(R.id.message_box);
1127                    viewHolder.contact_picture = view.findViewById(R.id.message_photo);
1128                    viewHolder.download_button = view.findViewById(R.id.download_button);
1129                    viewHolder.indicator = view.findViewById(R.id.security_indicator);
1130                    viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
1131                    viewHolder.image = view.findViewById(R.id.message_image);
1132                    viewHolder.messageBody = view.findViewById(R.id.message_body);
1133                    viewHolder.time = view.findViewById(R.id.message_time);
1134                    viewHolder.subject = view.findViewById(R.id.message_subject);
1135                    viewHolder.inReplyTo = view.findViewById(R.id.in_reply_to);
1136                    viewHolder.inReplyToQuote = view.findViewById(R.id.in_reply_to_quote);
1137                    viewHolder.inReplyToBox = view.findViewById(R.id.in_reply_to_box);
1138                    viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
1139                    viewHolder.encryption = view.findViewById(R.id.message_encryption);
1140                    viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
1141                    viewHolder.commands_list = view.findViewById(R.id.commands_list);
1142                    viewHolder.thread_identicon = view.findViewById(R.id.thread_identicon);
1143                    break;
1144                case STATUS:
1145                    view =
1146                            activity.getLayoutInflater()
1147                                    .inflate(R.layout.item_message_status, parent, false);
1148                    viewHolder.contact_picture = view.findViewById(R.id.message_photo);
1149                    viewHolder.status_message = view.findViewById(R.id.status_message);
1150                    viewHolder.load_more_messages = view.findViewById(R.id.load_more_messages);
1151                    break;
1152                default:
1153                    throw new AssertionError("Unknown view type");
1154            }
1155            view.setTag(viewHolder);
1156        } else {
1157            viewHolder = (ViewHolder) view.getTag();
1158            if (viewHolder == null) {
1159                return view;
1160            }
1161        }
1162
1163        if (viewHolder.messageBody != null) {
1164            viewHolder.messageBody.setCustomSelectionActionModeCallback(new MessageTextActionModeCallback(this, viewHolder.messageBody));
1165        }
1166
1167        if (viewHolder.time != null) {
1168            if (message.isAttention()) {
1169                viewHolder.time.setTypeface(null, Typeface.BOLD);
1170            } else {
1171                viewHolder.time.setTypeface(null, Typeface.NORMAL);
1172            }
1173        }
1174
1175        final var black = MaterialColors.getColor(view, com.google.android.material.R.attr.colorSecondaryContainer) == view.getContext().getColor(android.R.color.black);
1176        final boolean colorfulBackground = this.bubbleDesign.colorfulChatBubbles;
1177        final BubbleColor bubbleColor;
1178        if (type == RECEIVED) {
1179            if (isInValidSession) {
1180                bubbleColor = colorfulBackground  || black ? BubbleColor.SECONDARY : BubbleColor.SURFACE;
1181            } else {
1182                bubbleColor = BubbleColor.WARNING;
1183            }
1184        } else {
1185            if (!colorfulBackground && black) {
1186                bubbleColor = BubbleColor.SECONDARY;
1187            } else {
1188                bubbleColor = colorfulBackground ? BubbleColor.TERTIARY : BubbleColor.SURFACE_HIGH;
1189            }
1190        }
1191
1192        if (viewHolder.thread_identicon != null) {
1193            viewHolder.thread_identicon.setVisibility(View.GONE);
1194            final Element thread = message.getThread();
1195            if (thread != null) {
1196                final String threadId = thread.getContent();
1197                if (threadId != null) {
1198                    final var roles = MaterialColors.getColorRoles(activity, UIHelper.getColorForName(threadId));
1199                    viewHolder.thread_identicon.setVisibility(View.VISIBLE);
1200                    viewHolder.thread_identicon.setColor(roles.getAccent());
1201                    viewHolder.thread_identicon.setHash(UIHelper.identiconHash(threadId));
1202                }
1203            }
1204        }
1205
1206        if (type == DATE_SEPARATOR) {
1207            if (UIHelper.today(message.getTimeSent())) {
1208                viewHolder.status_message.setText(R.string.today);
1209            } else if (UIHelper.yesterday(message.getTimeSent())) {
1210                viewHolder.status_message.setText(R.string.yesterday);
1211            } else {
1212                viewHolder.status_message.setText(
1213                        DateUtils.formatDateTime(
1214                                activity,
1215                                message.getTimeSent(),
1216                                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
1217            }
1218            if (colorfulBackground) {
1219                setBackgroundTint(viewHolder.message_box, BubbleColor.PRIMARY);
1220                setTextColor(viewHolder.status_message, BubbleColor.PRIMARY);
1221            } else {
1222                setBackgroundTint(viewHolder.message_box, BubbleColor.SURFACE_HIGH);
1223                setTextColor(viewHolder.status_message, BubbleColor.SURFACE_HIGH);
1224            }
1225            return view;
1226        } else if (type == RTP_SESSION) {
1227            final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
1228            final RtpSessionStatus rtpSessionStatus = RtpSessionStatus.of(message.getBody());
1229            final long duration = rtpSessionStatus.duration;
1230            final String callTime = UIHelper.readableTimeDifferenceFull(activity, message.getTimeSent());
1231            if (received) {
1232                if (duration > 0) {
1233                    viewHolder.status_message.setText(
1234                            activity.getString(
1235                                    R.string.incoming_call_duration_timestamp,
1236                                    TimeFrameUtils.resolve(activity, duration),
1237                                    UIHelper.readableTimeDifferenceFull(
1238                                            activity, message.getTimeSent())));
1239                } else if (rtpSessionStatus.successful) {
1240                    viewHolder.status_message.setText(activity.getString(R.string.incoming_call_timestamp, callTime));
1241                } else {
1242                    viewHolder.status_message.setText(
1243                            activity.getString(
1244                                    R.string.missed_call_timestamp,
1245                                    UIHelper.readableTimeDifferenceFull(
1246                                            activity, message.getTimeSent())));
1247                }
1248            } else {
1249                if (duration > 0) {
1250                    viewHolder.status_message.setText(
1251                            activity.getString(
1252                                    R.string.outgoing_call_duration_timestamp,
1253                                    TimeFrameUtils.resolve(activity, duration),
1254                                    UIHelper.readableTimeDifferenceFull(
1255                                            activity, message.getTimeSent())));
1256                } else {
1257                    viewHolder.status_message.setText(
1258                            activity.getString(
1259                                    R.string.outgoing_call_timestamp,
1260                                    UIHelper.readableTimeDifferenceFull(
1261                                            activity, message.getTimeSent())));
1262                }
1263            }
1264            if (colorfulBackground) {
1265                setBackgroundTint(viewHolder.message_box, BubbleColor.SECONDARY);
1266                setTextColor(viewHolder.status_message, BubbleColor.SECONDARY);
1267                setImageTint(viewHolder.indicatorReceived, BubbleColor.SECONDARY);
1268            } else {
1269                setBackgroundTint(viewHolder.message_box, BubbleColor.SURFACE_HIGH);
1270                setTextColor(viewHolder.status_message, BubbleColor.SURFACE_HIGH);
1271                setImageTint(viewHolder.indicatorReceived, BubbleColor.SURFACE_HIGH);
1272            }
1273            viewHolder.indicatorReceived.setImageResource(
1274                    RtpSessionStatus.getDrawable(received, rtpSessionStatus.successful));
1275            return view;
1276        } else if (type == STATUS) {
1277            if ("LOAD_MORE".equals(message.getBody())) {
1278                viewHolder.status_message.setVisibility(View.GONE);
1279                viewHolder.contact_picture.setVisibility(View.GONE);
1280                viewHolder.load_more_messages.setVisibility(View.VISIBLE);
1281                viewHolder.load_more_messages.setOnClickListener(
1282                        v -> loadMoreMessages((Conversation) message.getConversation()));
1283            } else {
1284                viewHolder.status_message.setVisibility(View.VISIBLE);
1285                viewHolder.load_more_messages.setVisibility(View.GONE);
1286                viewHolder.status_message.setText(message.getBody());
1287                boolean showAvatar;
1288                if (conversation.getMode() == Conversation.MODE_SINGLE) {
1289                    showAvatar = true;
1290                    AvatarWorkerTask.loadAvatar(
1291                            message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
1292                } else if (message.getCounterpart() != null
1293                        || message.getTrueCounterpart() != null
1294                        || (message.getCounterparts() != null
1295                                && message.getCounterparts().size() > 0)) {
1296                    showAvatar = true;
1297                    AvatarWorkerTask.loadAvatar(
1298                            message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
1299                } else {
1300                    showAvatar = false;
1301                }
1302                if (showAvatar) {
1303                    viewHolder.contact_picture.setAlpha(0.5f);
1304                    viewHolder.contact_picture.setVisibility(View.VISIBLE);
1305                } else {
1306                    viewHolder.contact_picture.setVisibility(View.GONE);
1307                }
1308            }
1309            return view;
1310        } else {
1311            // viewHolder.message_box.setClipToOutline(true); This eats the bubble tails on A14 for some reason
1312            AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar);
1313        }
1314
1315        resetClickListener(viewHolder.message_box, viewHolder.messageBody);
1316
1317        viewHolder.message_box.setOnClickListener(v -> {
1318            if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
1319                MessageAdapter.this.mOnMessageBoxClickedListener
1320                        .onContactPictureClicked(message);
1321            }
1322        });
1323        SwipeDetector swipeDetector = new SwipeDetector((action) -> {
1324            if (action == SwipeDetector.Action.LR && MessageAdapter.this.mOnMessageBoxSwipedListener != null) {
1325                MessageAdapter.this.mOnMessageBoxSwipedListener.onContactPictureClicked(message);
1326            }
1327        });
1328        viewHolder.message_box.setOnTouchListener(swipeDetector);
1329        viewHolder.image.setOnTouchListener(swipeDetector);
1330        viewHolder.time.setOnTouchListener(swipeDetector);
1331
1332        // Treat touch-up as click so we don't have to touch twice
1333        // (touch twice is because it's waiting to see if you double-touch for text selection)
1334        viewHolder.messageBody.setOnTouchListener((v, event) -> {
1335            if (event.getAction() == MotionEvent.ACTION_UP) {
1336                if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
1337                    MessageAdapter.this.mOnMessageBoxClickedListener
1338                        .onContactPictureClicked(message);
1339                }
1340            }
1341
1342            swipeDetector.onTouch(v, event);
1343
1344            return false;
1345        });
1346        viewHolder.messageBody.setOnClickListener(v -> {
1347            if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
1348                MessageAdapter.this.mOnMessageBoxClickedListener
1349                        .onContactPictureClicked(message);
1350            }
1351        });
1352        viewHolder.contact_picture.setOnClickListener(v -> {
1353            if (MessageAdapter.this.mOnContactPictureClickedListener != null) {
1354                MessageAdapter.this.mOnContactPictureClickedListener
1355                        .onContactPictureClicked(message);
1356            }
1357
1358        });
1359        viewHolder.contact_picture.setOnLongClickListener(v -> {
1360            if (MessageAdapter.this.mOnContactPictureLongClickedListener != null) {
1361                MessageAdapter.this.mOnContactPictureLongClickedListener
1362                        .onContactPictureLongClicked(v, message);
1363                return true;
1364            } else {
1365                return false;
1366            }
1367        });
1368        viewHolder.messageBody.setAccessibilityDelegate(null);
1369
1370        boolean footerWrap = false;
1371
1372        final Transferable transferable = message.getTransferable();
1373        final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(message);
1374
1375        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));
1376        if (muted) {
1377            // Muted MUC participant
1378            displayInfoMessage(viewHolder, "Muted", bubbleColor);
1379        } else if (unInitiatedButKnownSize || message.isDeleted() || (transferable != null && transferable.getStatus() != Transferable.STATUS_UPLOADING)) {
1380            if (unInitiatedButKnownSize || (message.isDeleted() && message.getModerated() == null) || transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER) {
1381                displayDownloadableMessage(viewHolder, message, activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, message)), bubbleColor, type);
1382            } else if (transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER_CHECK_FILESIZE) {
1383                displayDownloadableMessage(viewHolder, message, activity.getString(R.string.check_x_filesize, UIHelper.getFileDescriptionString(activity, message)), bubbleColor, type);
1384            } else {
1385                displayInfoMessage(viewHolder, UIHelper.getMessagePreview(activity.xmppConnectionService, message).first, bubbleColor);
1386            }
1387        } else if (message.isFileOrImage()
1388                && message.getEncryption() != Message.ENCRYPTION_PGP
1389                && message.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED) {
1390            if (message.getFileParams().width > 0 && message.getFileParams().height > 0) {
1391                displayMediaPreviewMessage(viewHolder, message, bubbleColor, type);
1392                if (!black && viewHolder.image.getLayoutParams().width > metrics.density * 110) {
1393                    footerWrap = true;
1394                }
1395            } else if (message.getFileParams().runtime > 0) {
1396                displayAudioMessage(viewHolder, message, bubbleColor, type);
1397            } else if ("application/xdc+zip".equals(message.getFileParams().getMediaType()) && message.getConversation() instanceof Conversation && message.getThread() != null && !message.getFileParams().getCids().isEmpty()) {
1398                displayWebxdcMessage(viewHolder, message, bubbleColor, type);
1399            } else {
1400                displayOpenableMessage(viewHolder, message, bubbleColor, type);
1401            }
1402        } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
1403            if (account.isPgpDecryptionServiceConnected()) {
1404                if (conversation instanceof Conversation
1405                        && !account.hasPendingPgpIntent((Conversation) conversation)) {
1406                    displayInfoMessage(
1407                            viewHolder,
1408                            activity.getString(R.string.message_decrypting),
1409                            bubbleColor);
1410                } else {
1411                    displayInfoMessage(
1412                            viewHolder, activity.getString(R.string.pgp_message), bubbleColor);
1413                }
1414            } else {
1415                displayInfoMessage(
1416                        viewHolder, activity.getString(R.string.install_openkeychain), bubbleColor);
1417                viewHolder.message_box.setOnClickListener(this::promptOpenKeychainInstall);
1418                viewHolder.messageBody.setOnClickListener(this::promptOpenKeychainInstall);
1419            }
1420        } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1421            displayInfoMessage(
1422                    viewHolder, activity.getString(R.string.decryption_failed), bubbleColor);
1423        } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
1424            displayInfoMessage(
1425                    viewHolder,
1426                    activity.getString(R.string.not_encrypted_for_this_device),
1427                    bubbleColor);
1428        } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1429            displayInfoMessage(
1430                    viewHolder, activity.getString(R.string.omemo_decryption_failed), bubbleColor);
1431        } else {
1432            if (message.isGeoUri()) {
1433                displayLocationMessage(viewHolder, message, bubbleColor, type);
1434            } else if (message.treatAsDownloadable()) {
1435                try {
1436                    final URI uri = message.getOob();
1437                    displayDownloadableMessage(viewHolder,
1438                            message,
1439                            activity.getString(
1440                                    R.string.check_x_filesize_on_host,
1441                                    UIHelper.getFileDescriptionString(activity, message),
1442                                    uri.getHost()),
1443                            bubbleColor, type);
1444                } catch (Exception e) {
1445                    displayDownloadableMessage(
1446                            viewHolder,
1447                            message,
1448                            activity.getString(
1449                                    R.string.check_x_filesize,
1450                                    UIHelper.getFileDescriptionString(activity, message)),
1451                            bubbleColor, type);
1452                }
1453            } else if (message.bodyIsOnlyEmojis() && message.getType() != Message.TYPE_PRIVATE) {
1454                displayEmojiMessage(viewHolder, message, bubbleColor, type);
1455            } else {
1456                displayTextMessage(viewHolder, message, bubbleColor, message.getType());
1457            }
1458        }
1459
1460        viewHolder.message_box_inner.setMinimumWidth(footerWrap ? (int) (110 * metrics.density) : 0);
1461        LinearLayout.LayoutParams statusParams = (LinearLayout.LayoutParams) viewHolder.status_line.getLayoutParams();
1462        statusParams.width = footerWrap ? ViewGroup.LayoutParams.MATCH_PARENT : ViewGroup.LayoutParams.WRAP_CONTENT;
1463        viewHolder.status_line.setLayoutParams(statusParams);
1464
1465        setBackgroundTint(viewHolder.message_box, bubbleColor);
1466        setTextColor(viewHolder.messageBody, bubbleColor);
1467        viewHolder.messageBody.setLinkTextColor(bubbleToOnSurfaceColor(viewHolder.messageBody, bubbleColor));
1468
1469        if (type == RECEIVED) {
1470            if (!muted && commands != null && conversation instanceof Conversation) {
1471                CommandButtonAdapter adapter = new CommandButtonAdapter(activity);
1472                adapter.addAll(commands);
1473                viewHolder.commands_list.setAdapter(adapter);
1474                viewHolder.commands_list.setVisibility(View.VISIBLE);
1475                viewHolder.commands_list.setOnItemClickListener((p, v, pos, id) -> {
1476                    final Element command = adapter.getItem(pos);
1477                    activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
1478                });
1479            } else {
1480                // It's unclear if we can set this to null...
1481                ListAdapter adapter = viewHolder.commands_list.getAdapter();
1482                if (adapter instanceof ArrayAdapter) {
1483                    ((ArrayAdapter<?>) adapter).clear();
1484                }
1485                viewHolder.commands_list.setVisibility(View.GONE);
1486                viewHolder.commands_list.setOnItemClickListener(null);
1487            }
1488
1489            setTextColor(viewHolder.encryption, bubbleColor);
1490
1491            if (isInValidSession) {
1492                viewHolder.encryption.setVisibility(View.GONE);
1493            } else {
1494                viewHolder.encryption.setVisibility(View.VISIBLE);
1495                if (omemoEncryption && !message.isTrusted()) {
1496                    viewHolder.encryption.setText(R.string.not_trusted);
1497                } else {
1498                    viewHolder.encryption.setText(
1499                            CryptoHelper.encryptionTypeToText(message.getEncryption()));
1500                }
1501            }
1502        }
1503
1504        if (type == RECEIVED || type == SENT) {
1505            String subject = message.getSubject();
1506            if (subject == null && message.getThread() != null) {
1507                final var thread = ((Conversation) message.getConversation()).getThread(message.getThread().getContent());
1508                if (thread != null) subject = thread.getSubject();
1509            }
1510            if (muted || subject == null) {
1511                viewHolder.subject.setVisibility(View.GONE);
1512            } else {
1513                viewHolder.subject.setVisibility(View.VISIBLE);
1514                viewHolder.subject.setText(subject);
1515            }
1516
1517            if (message.getInReplyTo() == null) {
1518                viewHolder.inReplyToBox.setVisibility(View.GONE);
1519            } else {
1520                viewHolder.inReplyToBox.setVisibility(View.VISIBLE);
1521                viewHolder.inReplyTo.setText(UIHelper.getMessageDisplayName(message.getInReplyTo()));
1522                viewHolder.inReplyTo.setOnClickListener((v) -> mConversationFragment.jumpTo(message.getInReplyTo()));
1523                viewHolder.inReplyToQuote.setOnClickListener((v) -> mConversationFragment.jumpTo(message.getInReplyTo()));
1524                setTextColor(viewHolder.inReplyTo, bubbleColor);
1525            }
1526        }
1527
1528        displayStatus(viewHolder, message, type, bubbleColor);
1529
1530        viewHolder.messageBody.setAccessibilityDelegate(new View.AccessibilityDelegate() {
1531            @Override
1532            public void sendAccessibilityEvent(View host, int eventType) {
1533                super.sendAccessibilityEvent(host, eventType);
1534                if (eventType == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
1535                    if (viewHolder.messageBody.hasSelection()) {
1536                        selectionUuid = message.getUuid();
1537                    } else if (message.getUuid() != null && message.getUuid().equals(selectionUuid)) {
1538                        selectionUuid = null;
1539                    }
1540                }
1541            }
1542        });
1543
1544        return view;
1545    }
1546
1547    private void promptOpenKeychainInstall(View view) {
1548        activity.showInstallPgpDialog();
1549    }
1550
1551    public FileBackend getFileBackend() {
1552        return activity.xmppConnectionService.getFileBackend();
1553    }
1554
1555    public void stopAudioPlayer() {
1556        audioPlayer.stop();
1557    }
1558
1559    public void unregisterListenerInAudioPlayer() {
1560        audioPlayer.unregisterListener();
1561    }
1562
1563    public void startStopPending() {
1564        audioPlayer.startStopPending();
1565    }
1566
1567    public void openDownloadable(Message message) {
1568        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
1569                && ContextCompat.checkSelfPermission(
1570                                activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
1571                        != PackageManager.PERMISSION_GRANTED) {
1572            ConversationFragment.registerPendingMessage(activity, message);
1573            ActivityCompat.requestPermissions(
1574                    activity,
1575                    new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
1576                    ConversationsActivity.REQUEST_OPEN_MESSAGE);
1577            return;
1578        }
1579        final DownloadableFile file =
1580                activity.xmppConnectionService.getFileBackend().getFile(message);
1581        ViewUtil.view(activity, file);
1582    }
1583
1584    private void showLocation(Message message) {
1585        for (Intent intent : GeoHelper.createGeoIntentsFromMessage(activity, message)) {
1586            if (intent.resolveActivity(getContext().getPackageManager()) != null) {
1587                getContext().startActivity(intent);
1588                return;
1589            }
1590        }
1591        Toast.makeText(
1592                        activity,
1593                        R.string.no_application_found_to_display_location,
1594                        Toast.LENGTH_SHORT)
1595                .show();
1596    }
1597
1598    public void updatePreferences() {
1599        final AppSettings appSettings = new AppSettings(activity);
1600        this.bubbleDesign =
1601                new BubbleDesign(appSettings.isColorfulChatBubbles(), appSettings.isLargeFont());
1602    }
1603
1604    public void setHighlightedTerm(List<String> terms) {
1605        this.highlightedTerm = terms == null ? null : StylingHelper.filterHighlightedWords(terms);
1606    }
1607
1608    public interface OnContactPictureClicked {
1609        void onContactPictureClicked(Message message);
1610    }
1611
1612    public interface OnContactPictureLongClicked {
1613        void onContactPictureLongClicked(View v, Message message);
1614    }
1615
1616    public interface OnInlineImageLongClicked {
1617        boolean onInlineImageLongClicked(Cid cid);
1618    }
1619
1620    private static void setBackgroundTint(final View view, final BubbleColor bubbleColor) {
1621        view.setBackgroundTintList(bubbleToColorStateList(view, bubbleColor));
1622    }
1623
1624    private static ColorStateList bubbleToColorStateList(
1625            final View view, final BubbleColor bubbleColor) {
1626        final @AttrRes int colorAttributeResId =
1627                switch (bubbleColor) {
1628                    case SURFACE -> Activities.isNightMode(view.getContext())
1629                            ? com.google.android.material.R.attr.colorSurfaceContainerHigh
1630                            : com.google.android.material.R.attr.colorSurfaceContainerLow;
1631                    case SURFACE_HIGH -> Activities.isNightMode(view.getContext())
1632                            ? com.google.android.material.R.attr.colorSurfaceContainerHighest
1633                            : com.google.android.material.R.attr.colorSurfaceContainerHigh;
1634                    case PRIMARY -> com.google.android.material.R.attr.colorPrimaryContainer;
1635                    case SECONDARY -> com.google.android.material.R.attr.colorSecondaryContainer;
1636                    case TERTIARY -> com.google.android.material.R.attr.colorTertiaryContainer;
1637                    case WARNING -> com.google.android.material.R.attr.colorErrorContainer;
1638                };
1639        return ColorStateList.valueOf(MaterialColors.getColor(view, colorAttributeResId));
1640    }
1641
1642    public static void setImageTint(final ImageView imageView, final BubbleColor bubbleColor) {
1643        ImageViewCompat.setImageTintList(
1644                imageView, bubbleToOnSurfaceColorStateList(imageView, bubbleColor));
1645    }
1646
1647    public static void setImageTintError(final ImageView imageView) {
1648        ImageViewCompat.setImageTintList(
1649                imageView,
1650                ColorStateList.valueOf(
1651                        MaterialColors.getColor(
1652                                imageView, com.google.android.material.R.attr.colorError)));
1653    }
1654
1655    public static void setTextColor(final TextView textView, final BubbleColor bubbleColor) {
1656        final var color = bubbleToOnSurfaceColor(textView, bubbleColor);
1657        textView.setTextColor(color);
1658        if (BubbleColor.SURFACES.contains(bubbleColor)) {
1659            textView.setLinkTextColor(
1660                    MaterialColors.getColor(
1661                            textView, com.google.android.material.R.attr.colorPrimary));
1662        } else {
1663            textView.setLinkTextColor(color);
1664        }
1665    }
1666
1667    private static void setTextSize(final TextView textView, final boolean largeFont) {
1668        if (largeFont) {
1669            textView.setTextAppearance(
1670                    com.google.android.material.R.style.TextAppearance_Material3_BodyLarge);
1671            textView.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 18);
1672        } else {
1673            textView.setTextAppearance(
1674                    com.google.android.material.R.style.TextAppearance_Material3_BodyMedium);
1675        }
1676    }
1677
1678    private static @ColorInt int bubbleToOnSurfaceVariant(
1679            final View view, final BubbleColor bubbleColor) {
1680        final @AttrRes int colorAttributeResId;
1681        if (BubbleColor.SURFACES.contains(bubbleColor)) {
1682            colorAttributeResId = com.google.android.material.R.attr.colorOnSurfaceVariant;
1683        } else {
1684            colorAttributeResId = bubbleToOnSurface(bubbleColor);
1685        }
1686        return MaterialColors.getColor(view, colorAttributeResId);
1687    }
1688
1689    private static @ColorInt int bubbleToOnSurfaceColor(
1690            final View view, final BubbleColor bubbleColor) {
1691        return MaterialColors.getColor(view, bubbleToOnSurface(bubbleColor));
1692    }
1693
1694    public static ColorStateList bubbleToOnSurfaceColorStateList(
1695            final View view, final BubbleColor bubbleColor) {
1696        return ColorStateList.valueOf(bubbleToOnSurfaceColor(view, bubbleColor));
1697    }
1698
1699    private static @AttrRes int bubbleToOnSurface(final BubbleColor bubbleColor) {
1700        return switch (bubbleColor) {
1701            case SURFACE, SURFACE_HIGH -> com.google.android.material.R.attr.colorOnSurface;
1702            case PRIMARY -> com.google.android.material.R.attr.colorOnPrimaryContainer;
1703            case SECONDARY -> com.google.android.material.R.attr.colorOnSecondaryContainer;
1704            case TERTIARY -> com.google.android.material.R.attr.colorOnTertiaryContainer;
1705            case WARNING -> com.google.android.material.R.attr.colorOnErrorContainer;
1706        };
1707    }
1708
1709    public enum BubbleColor {
1710        SURFACE,
1711        SURFACE_HIGH,
1712        PRIMARY,
1713        SECONDARY,
1714        TERTIARY,
1715        WARNING;
1716
1717        private static final Collection<BubbleColor> SURFACES =
1718                Arrays.asList(BubbleColor.SURFACE, BubbleColor.SURFACE_HIGH);
1719    }
1720
1721    private static class BubbleDesign {
1722        public final boolean colorfulChatBubbles;
1723        public final boolean largeFont;
1724
1725        private BubbleDesign(final boolean colorfulChatBubbles, final boolean largeFont) {
1726            this.colorfulChatBubbles = colorfulChatBubbles;
1727            this.largeFont = largeFont;
1728        }
1729    }
1730
1731    private static class ViewHolder {
1732
1733        public MaterialButton load_more_messages;
1734        public ImageView edit_indicator;
1735        public RelativeLayout audioPlayer;
1736        protected View status_line;
1737        protected LinearLayout message_box;
1738        protected View message_box_inner;
1739        protected MaterialButton download_button;
1740        protected ShapeableImageView image;
1741        protected ImageView indicator;
1742        protected ImageView indicatorReceived;
1743        protected TextView time;
1744        protected TextView subject;
1745        protected TextView inReplyTo;
1746        protected TextView inReplyToQuote;
1747        protected LinearLayout inReplyToBox;
1748        protected TextView messageBody;
1749        protected ImageView contact_picture;
1750        protected TextView status_message;
1751        protected TextView encryption;
1752        protected ListView commands_list;
1753        protected GithubIdenticonView thread_identicon;
1754    }
1755
1756    class ThumbnailTask extends AsyncTask<DownloadableFile, Void, Drawable[]> {
1757        @Override
1758        protected Drawable[] doInBackground(DownloadableFile... params) {
1759            if (isCancelled()) return null;
1760
1761            Drawable[] d = new Drawable[params.length];
1762            for (int i = 0; i < params.length; i++) {
1763                try {
1764                    d[i] = activity.xmppConnectionService.getFileBackend().getThumbnail(params[i], activity.getResources(), (int) (metrics.density * 288), false);
1765                } catch (final IOException e) {
1766                    d[i] = null;
1767                }
1768            }
1769
1770            return d;
1771        }
1772
1773        @Override
1774        protected void onPostExecute(final Drawable[] d) {
1775            if (isCancelled()) return;
1776            activity.xmppConnectionService.updateConversationUi();
1777        }
1778    }
1779}