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