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