ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
   4import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
   5import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.hideSoftKeyboard;
   6import static eu.siacs.conversations.utils.PermissionUtils.allGranted;
   7import static eu.siacs.conversations.utils.PermissionUtils.audioGranted;
   8import static eu.siacs.conversations.utils.PermissionUtils.cameraGranted;
   9import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
  10import static eu.siacs.conversations.utils.PermissionUtils.writeGranted;
  11
  12import android.Manifest;
  13import android.annotation.SuppressLint;
  14import android.app.Activity;
  15import android.app.DatePickerDialog;
  16import android.app.Fragment;
  17import android.app.FragmentManager;
  18import android.app.PendingIntent;
  19import android.app.ProgressDialog;
  20import android.app.TimePickerDialog;
  21import android.content.ActivityNotFoundException;
  22import android.content.Context;
  23import android.content.DialogInterface;
  24import android.content.Intent;
  25import android.content.IntentSender.SendIntentException;
  26import android.content.SharedPreferences;
  27import android.content.pm.PackageManager;
  28import android.content.res.ColorStateList;
  29import android.graphics.Color;
  30import android.icu.util.Calendar;
  31import android.icu.util.TimeZone;
  32import android.net.Uri;
  33import android.os.Build;
  34import android.os.Bundle;
  35import android.os.Environment;
  36import android.os.Handler;
  37import android.os.Looper;
  38import android.os.storage.StorageManager;
  39import android.os.SystemClock;
  40import android.preference.PreferenceManager;
  41import android.provider.MediaStore;
  42import android.text.Editable;
  43import android.text.TextUtils;
  44import android.text.TextWatcher;
  45import android.text.SpannableStringBuilder;
  46import android.text.style.ImageSpan;
  47import android.util.DisplayMetrics;
  48import android.util.Log;
  49import android.view.ContextMenu;
  50import android.view.ContextMenu.ContextMenuInfo;
  51import android.view.Gravity;
  52import android.view.LayoutInflater;
  53import android.view.Menu;
  54import android.view.MenuInflater;
  55import android.view.MenuItem;
  56import android.view.MotionEvent;
  57import android.view.View;
  58import android.view.View.OnClickListener;
  59import android.view.ViewGroup;
  60import android.view.animation.AlphaAnimation;
  61import android.view.animation.Animation;
  62import android.view.animation.CycleInterpolator;
  63import android.view.inputmethod.EditorInfo;
  64import android.view.inputmethod.InputMethodManager;
  65import android.view.WindowManager;
  66import android.widget.AbsListView;
  67import android.widget.AbsListView.OnScrollListener;
  68import android.widget.AdapterView;
  69import android.widget.AdapterView.AdapterContextMenuInfo;
  70import android.widget.CheckBox;
  71import android.widget.ListView;
  72import android.widget.PopupMenu;
  73import android.widget.PopupWindow;
  74import android.widget.TextView.OnEditorActionListener;
  75import android.widget.Toast;
  76
  77import androidx.activity.OnBackPressedCallback;
  78import androidx.annotation.IdRes;
  79import androidx.annotation.NonNull;
  80import androidx.annotation.Nullable;
  81import androidx.annotation.StringRes;
  82import androidx.appcompat.app.AlertDialog;
  83import androidx.core.content.pm.ShortcutInfoCompat;
  84import androidx.core.content.pm.ShortcutManagerCompat;
  85import androidx.core.graphics.ColorUtils;
  86import androidx.core.view.inputmethod.InputConnectionCompat;
  87import androidx.core.view.inputmethod.InputContentInfoCompat;
  88import androidx.databinding.DataBindingUtil;
  89import androidx.documentfile.provider.DocumentFile;
  90import androidx.recyclerview.widget.RecyclerView.Adapter;
  91import androidx.viewpager.widget.PagerAdapter;
  92import androidx.viewpager.widget.ViewPager;
  93
  94import com.cheogram.android.BobTransfer;
  95import com.cheogram.android.EmojiSearch;
  96import com.cheogram.android.EditMessageSelectionActionModeCallback;
  97import com.cheogram.android.WebxdcPage;
  98import com.cheogram.android.WebxdcStore;
  99
 100import com.google.android.material.color.MaterialColors;
 101import com.google.android.material.dialog.MaterialAlertDialogBuilder;
 102import com.google.common.base.Optional;
 103import com.google.common.collect.Collections2;
 104import com.google.common.collect.ImmutableList;
 105import com.google.common.collect.ImmutableSet;
 106import com.google.common.collect.Lists;
 107import com.google.common.collect.Ordering;
 108import com.google.common.io.Files;
 109import com.google.common.util.concurrent.Futures;
 110import com.google.common.util.concurrent.FutureCallback;
 111import com.google.common.util.concurrent.MoreExecutors;
 112
 113import com.otaliastudios.autocomplete.Autocomplete;
 114import com.otaliastudios.autocomplete.AutocompleteCallback;
 115import com.otaliastudios.autocomplete.AutocompletePresenter;
 116import com.otaliastudios.autocomplete.CharPolicy;
 117import com.otaliastudios.autocomplete.RecyclerViewPresenter;
 118
 119import org.jetbrains.annotations.NotNull;
 120
 121import io.ipfs.cid.Cid;
 122
 123import java.io.File;
 124import java.net.URISyntaxException;
 125import java.util.AbstractMap;
 126import java.util.ArrayList;
 127import java.util.Arrays;
 128import java.util.Collection;
 129import java.util.Collections;
 130import java.util.HashSet;
 131import java.util.Iterator;
 132import java.util.LinkedList;
 133import java.util.List;
 134import java.util.Locale;
 135import java.util.Map;
 136import java.util.Set;
 137import java.util.UUID;
 138import java.util.concurrent.atomic.AtomicBoolean;
 139import java.util.regex.Matcher;
 140import java.util.regex.Pattern;
 141import java.util.stream.Collectors;
 142
 143import com.google.common.collect.Iterables;
 144import de.gultsch.common.Linkify;
 145import de.gultsch.common.Patterns;
 146import eu.siacs.conversations.Config;
 147import eu.siacs.conversations.R;
 148import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 149import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
 150import eu.siacs.conversations.databinding.FragmentConversationBinding;
 151import eu.siacs.conversations.entities.Account;
 152import eu.siacs.conversations.entities.Blockable;
 153import eu.siacs.conversations.entities.Contact;
 154import eu.siacs.conversations.entities.Conversation;
 155import eu.siacs.conversations.entities.Conversational;
 156import eu.siacs.conversations.entities.DownloadableFile;
 157import eu.siacs.conversations.entities.Message;
 158import eu.siacs.conversations.entities.MucOptions;
 159import eu.siacs.conversations.entities.MucOptions.User;
 160import eu.siacs.conversations.entities.Presences;
 161import eu.siacs.conversations.entities.ReadByMarker;
 162import eu.siacs.conversations.entities.Transferable;
 163import eu.siacs.conversations.entities.TransferablePlaceholder;
 164import eu.siacs.conversations.http.HttpDownloadConnection;
 165import eu.siacs.conversations.persistance.FileBackend;
 166import eu.siacs.conversations.services.CallIntegrationConnectionService;
 167import eu.siacs.conversations.services.MessageArchiveService;
 168import eu.siacs.conversations.services.QuickConversationsService;
 169import eu.siacs.conversations.services.XmppConnectionService;
 170import eu.siacs.conversations.ui.adapter.CommandAdapter;
 171import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
 172import eu.siacs.conversations.ui.adapter.MessageAdapter;
 173import eu.siacs.conversations.ui.adapter.UserAdapter;
 174import eu.siacs.conversations.ui.util.ActivityResult;
 175import eu.siacs.conversations.ui.util.Attachment;
 176import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
 177import eu.siacs.conversations.ui.util.DateSeparator;
 178import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
 179import eu.siacs.conversations.ui.util.ListViewUtils;
 180import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 181import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
 182import eu.siacs.conversations.ui.util.PendingItem;
 183import eu.siacs.conversations.ui.util.PresenceSelector;
 184import eu.siacs.conversations.ui.util.ScrollState;
 185import eu.siacs.conversations.ui.util.SendButtonAction;
 186import eu.siacs.conversations.ui.util.SendButtonTool;
 187import eu.siacs.conversations.ui.util.ShareUtil;
 188import eu.siacs.conversations.ui.util.ViewUtil;
 189import eu.siacs.conversations.ui.widget.EditMessage;
 190import eu.siacs.conversations.utils.AccountUtils;
 191import eu.siacs.conversations.utils.Compatibility;
 192import eu.siacs.conversations.utils.Emoticons;
 193import eu.siacs.conversations.utils.GeoHelper;
 194import eu.siacs.conversations.utils.MessageUtils;
 195import eu.siacs.conversations.utils.MimeUtils;
 196import eu.siacs.conversations.utils.NickValidityChecker;
 197import eu.siacs.conversations.utils.PermissionUtils;
 198import eu.siacs.conversations.utils.QuickLoader;
 199import eu.siacs.conversations.utils.StylingHelper;
 200import eu.siacs.conversations.utils.TimeFrameUtils;
 201import eu.siacs.conversations.utils.UIHelper;
 202import eu.siacs.conversations.xml.Element;
 203import eu.siacs.conversations.xml.Namespace;
 204import eu.siacs.conversations.xmpp.Jid;
 205import eu.siacs.conversations.xmpp.XmppConnection;
 206import eu.siacs.conversations.xmpp.chatstate.ChatState;
 207import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 208import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 209import eu.siacs.conversations.xmpp.jingle.JingleFileTransferConnection;
 210import eu.siacs.conversations.xmpp.jingle.Media;
 211import eu.siacs.conversations.xmpp.jingle.OngoingRtpSession;
 212import eu.siacs.conversations.xmpp.jingle.RtpCapability;
 213import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 214import eu.siacs.conversations.xmpp.manager.BookmarkManager;
 215import eu.siacs.conversations.xmpp.manager.DiscoManager;
 216
 217import im.conversations.android.xmpp.Entity;
 218import im.conversations.android.xmpp.model.disco.info.InfoQuery;
 219import im.conversations.android.xmpp.model.disco.items.Item;
 220import im.conversations.android.xmpp.model.muc.Affiliation;
 221import im.conversations.android.xmpp.model.muc.Role;
 222import im.conversations.android.xmpp.model.stanza.Iq;
 223
 224import org.jetbrains.annotations.NotNull;
 225import eu.siacs.conversations.xmpp.manager.HttpUploadManager;
 226import eu.siacs.conversations.xmpp.manager.MultiUserChatManager;
 227import eu.siacs.conversations.xmpp.manager.PresenceManager;
 228import im.conversations.android.xmpp.model.stanza.Presence;
 229import java.util.ArrayList;
 230import java.util.Arrays;
 231import java.util.Collection;
 232import java.util.Collections;
 233import java.util.HashSet;
 234import java.util.Iterator;
 235import java.util.List;
 236import java.util.Objects;
 237import java.util.Set;
 238import java.util.UUID;
 239import java.util.concurrent.atomic.AtomicBoolean;
 240
 241public class ConversationFragment extends XmppFragment
 242        implements EditMessage.KeyboardListener,
 243                MessageAdapter.OnContactPictureLongClicked,
 244                MessageAdapter.OnContactPictureClicked,
 245                MessageAdapter.OnInlineImageLongClicked {
 246
 247    public static final int REQUEST_SEND_MESSAGE = 0x0201;
 248    public static final int REQUEST_DECRYPT_PGP = 0x0202;
 249    public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
 250    public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
 251    public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
 252    public static final int REQUEST_START_DOWNLOAD = 0x0210;
 253    public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
 254    public static final int REQUEST_COMMIT_ATTACHMENTS = 0x0212;
 255    public static final int REQUEST_START_AUDIO_CALL = 0x213;
 256    public static final int REQUEST_START_VIDEO_CALL = 0x214;
 257    public static final int REQUEST_SAVE_STICKER = 0x215;
 258    public static final int REQUEST_WEBXDC_STORE = 0x216;
 259    public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
 260    public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
 261    public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
 262    public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
 263    public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
 264    public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
 265    public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
 266
 267    public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
 268    public static final String STATE_CONVERSATION_UUID =
 269            ConversationFragment.class.getName() + ".uuid";
 270    public static final String STATE_SCROLL_POSITION =
 271            ConversationFragment.class.getName() + ".scroll_position";
 272    public static final String STATE_PHOTO_URI =
 273            ConversationFragment.class.getName() + ".media_previews";
 274    public static final String STATE_MEDIA_PREVIEWS =
 275            ConversationFragment.class.getName() + ".take_photo_uri";
 276    private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
 277
 278    private final List<Message> messageList = new ArrayList<>();
 279    private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
 280    private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
 281    private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
 282    private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
 283    private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
 284    private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
 285    private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
 286    private final PendingItem<Message> pendingMessage = new PendingItem<>();
 287    public Uri mPendingEditorContent = null;
 288    protected ArrayList<WebxdcPage> extensions = new ArrayList<>();
 289    protected MessageAdapter messageListAdapter;
 290    protected CommandAdapter commandAdapter;
 291    private MediaPreviewAdapter mediaPreviewAdapter;
 292    private String lastMessageUuid = null;
 293    private Conversation conversation;
 294    private FragmentConversationBinding binding;
 295    private Toast messageLoaderToast;
 296    private ConversationsActivity activity;
 297    private boolean reInitRequiredOnStart = true;
 298    private int identiconWidth = -1;
 299    private File savingAsSticker = null;
 300    private EmojiSearch emojiSearch = null;
 301
 302    private LinkedList<Message> replyJumps = new LinkedList<>();
 303
 304    private final OnClickListener clickToMuc =
 305            new OnClickListener() {
 306
 307                @Override
 308                public void onClick(View v) {
 309                    ConferenceDetailsActivity.open(getActivity(), conversation);
 310                }
 311            };
 312    private final OnClickListener leaveMuc =
 313            new OnClickListener() {
 314
 315                @Override
 316                public void onClick(View v) {
 317                    activity.xmppConnectionService.archiveConversation(conversation);
 318                }
 319            };
 320    private final OnClickListener joinMuc =
 321            new OnClickListener() {
 322
 323                @Override
 324                public void onClick(View v) {
 325                    activity.xmppConnectionService.joinMuc(conversation);
 326                }
 327            };
 328
 329    private final OnClickListener acceptJoin =
 330            new OnClickListener() {
 331                @Override
 332                public void onClick(View v) {
 333                    conversation.setAttribute("accept_non_anonymous", true);
 334                    activity.xmppConnectionService.updateConversation(conversation);
 335                    activity.xmppConnectionService.joinMuc(conversation);
 336                }
 337            };
 338
 339    private final OnClickListener enterPassword =
 340            new OnClickListener() {
 341
 342                @Override
 343                public void onClick(View v) {
 344                    MucOptions muc = conversation.getMucOptions();
 345                    String password = muc.getPassword();
 346                    if (password == null) {
 347                        password = "";
 348                    }
 349                    activity.quickPasswordEdit(
 350                            password,
 351                            value -> {
 352                                activity.xmppConnectionService.providePasswordForMuc(
 353                                        conversation, value);
 354                                return null;
 355                            });
 356                }
 357            };
 358    private final OnScrollListener mOnScrollListener =
 359            new OnScrollListener() {
 360
 361                @Override
 362                public void onScrollStateChanged(AbsListView view, int scrollState) {
 363                    if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
 364                        fireReadEvent();
 365                    }
 366                }
 367
 368                @Override
 369                public void onScroll(
 370                        final AbsListView view,
 371                        int firstVisibleItem,
 372                        int visibleItemCount,
 373                        int totalItemCount) {
 374                    toggleScrollDownButton(view);
 375                    synchronized (ConversationFragment.this.messageList) {
 376                        boolean paginateBackward = firstVisibleItem < 5;
 377                        boolean paginationForward = conversation.isInHistoryPart() && firstVisibleItem + visibleItemCount + 5 > totalItemCount;
 378                        loadMoreMessages(paginateBackward, paginationForward, view);
 379                    }
 380                }
 381            };
 382
 383    private void loadMoreMessages(boolean paginateBackward, boolean paginationForward, AbsListView view) {
 384        if (paginateBackward && !conversation.messagesLoaded.get()) {
 385            paginateBackward = false;
 386        }
 387
 388        if (
 389                conversation != null &&
 390                        messageList.size() > 0 &&
 391                        ((paginateBackward && conversation.messagesLoaded.compareAndSet(true, false)) ||
 392                                (paginationForward && conversation.historyPartLoadedForward.compareAndSet(true, false)))
 393        ) {
 394            long timestamp;
 395
 396            if (paginateBackward) {
 397                if (messageList.get(0).getType() == Message.TYPE_STATUS
 398                        && messageList.size() >= 2) {
 399                    timestamp = messageList.get(1).getTimeSent();
 400                } else {
 401                    timestamp = messageList.get(0).getTimeSent();
 402                }
 403            } else {
 404                if (messageList.get(messageList.size() - 1).getType() == Message.TYPE_STATUS
 405                        && messageList.size() >= 2) {
 406                    timestamp = messageList.get(messageList.size() - 2).getTimeSent();
 407                } else {
 408                    timestamp = messageList.get(messageList.size() - 1).getTimeSent();
 409                }
 410            }
 411
 412            boolean finalPaginateBackward = paginateBackward;
 413            activity.xmppConnectionService.loadMoreMessages(
 414                    conversation,
 415                    timestamp,
 416                    !paginateBackward,
 417                    new XmppConnectionService.OnMoreMessagesLoaded() {
 418                        @Override
 419                        public void onMoreMessagesLoaded(
 420                                final int c, final Conversation conversation) {
 421                            if (ConversationFragment.this.conversation
 422                                    != conversation) {
 423                                conversation.messagesLoaded.set(true);
 424                                return;
 425                            }
 426                            runOnUiThread(
 427                                    () -> {
 428                                        synchronized (messageList) {
 429                                            final int oldPosition =
 430                                                    binding.messagesView
 431                                                            .getFirstVisiblePosition();
 432                                            Message message = null;
 433                                            int childPos;
 434                                            for (childPos = 0;
 435                                                 childPos + oldPosition
 436                                                         < messageList.size();
 437                                                 ++childPos) {
 438                                                message =
 439                                                        messageList.get(
 440                                                                oldPosition
 441                                                                        + childPos);
 442                                                if (message.getType()
 443                                                        != Message.TYPE_STATUS) {
 444                                                    break;
 445                                                }
 446                                            }
 447                                            final String uuid =
 448                                                    message != null
 449                                                            ? message.getUuid()
 450                                                            : null;
 451                                            View v =
 452                                                    binding.messagesView.getChildAt(
 453                                                            childPos);
 454                                            final int pxOffset =
 455                                                    (v == null) ? 0 : v.getTop();
 456                                            ConversationFragment.this.conversation
 457                                                    .populateWithMessages(
 458                                                            ConversationFragment
 459                                                                    .this
 460                                                                    .messageList,
 461                                                            activity == null ? null : activity.xmppConnectionService);
 462                                            try {
 463                                                updateStatusMessages();
 464                                            } catch (IllegalStateException e) {
 465                                                Log.d(
 466                                                        Config.LOGTAG,
 467                                                        "caught illegal state exception while updating status messages");
 468                                            }
 469                                            messageListAdapter
 470                                                    .notifyDataSetChanged();
 471                                            int pos =
 472                                                    Math.max(
 473                                                            getIndexOf(
 474                                                                    uuid,
 475                                                                    messageList),
 476                                                            0);
 477                                            binding.messagesView
 478                                                    .setSelectionFromTop(
 479                                                            pos, pxOffset);
 480                                            if (messageLoaderToast != null) {
 481                                                messageLoaderToast.cancel();
 482                                            }
 483
 484                                            if (!finalPaginateBackward) {
 485                                                conversation.historyPartLoadedForward.set(true);
 486                                            } else {
 487                                                conversation.messagesLoaded.set(true);
 488                                            }
 489                                        }
 490                                    });
 491                        }
 492
 493                        @Override
 494                        public void informUser(final int resId) {
 495
 496                            runOnUiThread(
 497                                    () -> {
 498                                        if (messageLoaderToast != null) {
 499                                            messageLoaderToast.cancel();
 500                                        }
 501                                        if (ConversationFragment.this.conversation
 502                                                != conversation) {
 503                                            return;
 504                                        }
 505                                        messageLoaderToast =
 506                                                Toast.makeText(
 507                                                        view.getContext(),
 508                                                        resId,
 509                                                        Toast.LENGTH_LONG);
 510                                        messageLoaderToast.show();
 511                                    });
 512                        }
 513                    });
 514        }
 515    }
 516    private final EditMessage.OnCommitContentListener mEditorContentListener =
 517            new EditMessage.OnCommitContentListener() {
 518                @Override
 519                public boolean onCommitContent(
 520                        InputContentInfoCompat inputContentInfo,
 521                        int flags,
 522                        Bundle opts,
 523                        String[] contentMimeTypes) {
 524                    // try to get permission to read the image, if applicable
 525                    if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION)
 526                            != 0) {
 527                        try {
 528                            inputContentInfo.requestPermission();
 529                        } catch (Exception e) {
 530                            Log.e(
 531                                    Config.LOGTAG,
 532                                    "InputContentInfoCompat#requestPermission() failed.",
 533                                    e);
 534                            Toast.makeText(
 535                                            getActivity(),
 536                                            activity.getString(
 537                                                    R.string.no_permission_to_access_x,
 538                                                    inputContentInfo.getDescription()),
 539                                            Toast.LENGTH_LONG)
 540                                    .show();
 541                            return false;
 542                        }
 543                    }
 544                    if (hasPermissions(
 545                            REQUEST_ADD_EDITOR_CONTENT,
 546                            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
 547                        attachEditorContentToConversation(inputContentInfo.getContentUri());
 548                    } else {
 549                        mPendingEditorContent = inputContentInfo.getContentUri();
 550                    }
 551                    return true;
 552                }
 553            };
 554    private Message selectedMessage;
 555    private final OnClickListener mEnableAccountListener =
 556            new OnClickListener() {
 557                @Override
 558                public void onClick(View v) {
 559                    final Account account = conversation == null ? null : conversation.getAccount();
 560                    if (account != null) {
 561                        account.setOption(Account.OPTION_SOFT_DISABLED, false);
 562                        account.setOption(Account.OPTION_DISABLED, false);
 563                        activity.xmppConnectionService.updateAccount(account);
 564                    }
 565                }
 566            };
 567    private final OnClickListener mUnblockClickListener =
 568            new OnClickListener() {
 569                @Override
 570                public void onClick(final View v) {
 571                    v.post(() -> v.setVisibility(View.INVISIBLE));
 572                    if (conversation.isDomainBlocked()) {
 573                        BlockContactDialog.show(activity, conversation);
 574                    } else {
 575                        unblockConversation(conversation);
 576                    }
 577                }
 578            };
 579    private final OnClickListener mBlockClickListener = this::showBlockSubmenu;
 580    private final OnClickListener mAddBackClickListener =
 581            new OnClickListener() {
 582
 583                @Override
 584                public void onClick(View v) {
 585                    final Contact contact = conversation == null ? null : conversation.getContact();
 586                    if (contact != null) {
 587                        activity.xmppConnectionService.createContact(contact);
 588                        activity.switchToContactDetails(contact);
 589                    }
 590                }
 591            };
 592    private final View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
 593    private final OnClickListener mAllowPresenceSubscription =
 594            new OnClickListener() {
 595                @Override
 596                public void onClick(View v) {
 597                    final Contact contact = conversation == null ? null : conversation.getContact();
 598                    if (contact != null) {
 599                        final var connection = contact.getAccount().getXmppConnection();
 600                        connection
 601                                .getManager(PresenceManager.class)
 602                                .subscribed(contact.getJid().asBareJid());
 603                        hideSnackbar();
 604                    }
 605                }
 606            };
 607    protected OnClickListener clickToDecryptListener =
 608            new OnClickListener() {
 609
 610                @Override
 611                public void onClick(View v) {
 612                    PendingIntent pendingIntent =
 613                            conversation.getAccount().getPgpDecryptionService().getPendingIntent();
 614                    if (pendingIntent != null) {
 615                        try {
 616                            getActivity()
 617                                    .startIntentSenderForResult(
 618                                            pendingIntent.getIntentSender(),
 619                                            REQUEST_DECRYPT_PGP,
 620                                            null,
 621                                            0,
 622                                            0,
 623                                            0,
 624                                            Compatibility.pgpStartIntentSenderOptions());
 625                        } catch (SendIntentException e) {
 626                            Toast.makeText(
 627                                            getActivity(),
 628                                            R.string.unable_to_connect_to_keychain,
 629                                            Toast.LENGTH_SHORT)
 630                                    .show();
 631                            conversation
 632                                    .getAccount()
 633                                    .getPgpDecryptionService()
 634                                    .continueDecryption(true);
 635                        }
 636                    }
 637                    updateSnackBar(conversation);
 638                }
 639            };
 640    private final AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
 641    private final OnEditorActionListener mEditorActionListener =
 642            (v, actionId, event) -> {
 643                if (actionId == EditorInfo.IME_ACTION_SEND) {
 644                    InputMethodManager imm =
 645                            (InputMethodManager)
 646                                    activity.getSystemService(Context.INPUT_METHOD_SERVICE);
 647                    if (imm != null && imm.isFullscreenMode()) {
 648                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
 649                    }
 650                    sendMessage();
 651                    return true;
 652                } else {
 653                    return false;
 654                }
 655            };
 656    private final OnClickListener mScrollButtonListener =
 657            new OnClickListener() {
 658
 659                @Override
 660                public void onClick(View v) {
 661                    stopScrolling();
 662
 663                    if (!replyJumps.isEmpty()) {
 664                        int lastVisiblePosition = binding.messagesView.getLastVisiblePosition();
 665                        Message lastVisibleMessage = messageListAdapter.getItem(lastVisiblePosition);
 666                        if (lastVisibleMessage == null) {
 667                            replyJumps.clear();
 668                        } else {
 669                            while (!replyJumps.isEmpty()) {
 670                                Message jump = replyJumps.pop();
 671                                if (jump.getTimeSent() > lastVisibleMessage.getTimeSent()) {
 672                                    Runnable postSelectionRunnable = () -> highlightMessage(jump.getUuid());
 673                                    updateSelection(jump.getUuid(), binding.messagesView.getHeight() / 2, postSelectionRunnable, false, false);
 674                                    return;
 675                                }
 676                            }
 677                        }
 678                    }
 679
 680                    if (conversation.isInHistoryPart()) {
 681                        conversation.jumpToLatest();
 682                        refresh(false);
 683                    }
 684                    setSelection(binding.messagesView.getCount() - 1, true);
 685                }
 686            };
 687    private final OnClickListener mSendButtonListener =
 688            new OnClickListener() {
 689
 690                @Override
 691                public void onClick(View v) {
 692                    Object tag = v.getTag();
 693                    if (tag instanceof SendButtonAction action) {
 694                        switch (action) {
 695                            case TAKE_PHOTO:
 696                            case RECORD_VIDEO:
 697                            case SEND_LOCATION:
 698                            case RECORD_VOICE:
 699                            case CHOOSE_PICTURE:
 700                                attachFile(action.toChoice());
 701                                break;
 702                            case CANCEL:
 703                                if (conversation != null) {
 704                                    conversation.setUserSelectedThread(false);
 705                                    if (conversation.setCorrectingMessage(null)) {
 706                                        binding.textinput.setText("");
 707                                        binding.textinput.append(conversation.getDraftMessage());
 708                                        conversation.setDraftMessage(null);
 709                                    } else if (conversation.getMode() == Conversation.MODE_MULTI) {
 710                                        conversation.setNextCounterpart(null);
 711                                        binding.textinput.setText("");
 712                                    } else {
 713                                        binding.textinput.setText("");
 714                                    }
 715                                    binding.textinputSubject.setText("");
 716                                    binding.textinputSubject.setVisibility(View.GONE);
 717                                    updateChatMsgHint();
 718                                    updateSendButton();
 719                                    updateEditablity();
 720                                }
 721                                break;
 722                            default:
 723                                sendMessage();
 724                        }
 725                    } else {
 726                        sendMessage();
 727                    }
 728                }
 729            };
 730    private OnBackPressedCallback backPressedLeaveSingleThread = new OnBackPressedCallback(false) {
 731        @Override
 732        public void handleOnBackPressed() {
 733            conversation.setLockThread(false);
 734            this.setEnabled(false);
 735            conversation.setUserSelectedThread(false);
 736            setThread(null);
 737            refresh();
 738            updateThreadFromLastMessage();
 739        }
 740    };
 741    private int completionIndex = 0;
 742    private int lastCompletionLength = 0;
 743    private String incomplete;
 744    private int lastCompletionCursor;
 745    private boolean firstWord = false;
 746    private Message mPendingDownloadableMessage;
 747    private ProgressDialog fetchHistoryDialog;
 748
 749    private static ConversationFragment findConversationFragment(Activity activity) {
 750        Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
 751        if (fragment instanceof ConversationFragment) {
 752            return (ConversationFragment) fragment;
 753        }
 754        fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
 755        if (fragment instanceof ConversationFragment) {
 756            return (ConversationFragment) fragment;
 757        }
 758        return null;
 759    }
 760
 761    public static void startStopPending(Activity activity) {
 762        ConversationFragment fragment = findConversationFragment(activity);
 763        if (fragment != null) {
 764            fragment.messageListAdapter.startStopPending();
 765        }
 766    }
 767
 768    public static void downloadFile(Activity activity, Message message) {
 769        ConversationFragment fragment = findConversationFragment(activity);
 770        if (fragment != null) {
 771            fragment.startDownloadable(message);
 772        }
 773    }
 774
 775    public static void registerPendingMessage(Activity activity, Message message) {
 776        ConversationFragment fragment = findConversationFragment(activity);
 777        if (fragment != null) {
 778            fragment.pendingMessage.push(message);
 779        }
 780    }
 781
 782    public static void openPendingMessage(Activity activity) {
 783        ConversationFragment fragment = findConversationFragment(activity);
 784        if (fragment != null) {
 785            Message message = fragment.pendingMessage.pop();
 786            if (message != null) {
 787                fragment.messageListAdapter.openDownloadable(message);
 788            }
 789        }
 790    }
 791
 792    public static Conversation getConversation(Activity activity) {
 793        return getConversation(activity, R.id.secondary_fragment);
 794    }
 795
 796    private static Conversation getConversation(Activity activity, @IdRes int res) {
 797        final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
 798        if (fragment instanceof ConversationFragment) {
 799            return ((ConversationFragment) fragment).getConversation();
 800        } else {
 801            return null;
 802        }
 803    }
 804
 805    public static ConversationFragment get(Activity activity) {
 806        FragmentManager fragmentManager = activity.getFragmentManager();
 807        Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment);
 808        if (fragment instanceof ConversationFragment) {
 809            return (ConversationFragment) fragment;
 810        } else {
 811            fragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
 812            return fragment instanceof ConversationFragment
 813                    ? (ConversationFragment) fragment
 814                    : null;
 815        }
 816    }
 817
 818    public static Conversation getConversationReliable(Activity activity) {
 819        final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
 820        if (conversation != null) {
 821            return conversation;
 822        }
 823        return getConversation(activity, R.id.main_fragment);
 824    }
 825
 826    private static boolean scrolledToBottom(AbsListView listView) {
 827        final int count = listView.getCount();
 828        if (count == 0) {
 829            return true;
 830        } else if (listView.getLastVisiblePosition() == count - 1) {
 831            final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
 832            return lastChild != null && lastChild.getBottom() <= listView.getHeight();
 833        } else {
 834            return false;
 835        }
 836    }
 837
 838    private void toggleScrollDownButton() {
 839        toggleScrollDownButton(binding.messagesView);
 840    }
 841
 842    private void toggleScrollDownButton(AbsListView listView) {
 843        if (conversation == null) {
 844            return;
 845        }
 846        if (scrolledToBottom(listView) && !conversation.isInHistoryPart()) {
 847            lastMessageUuid = null;
 848            hideUnreadMessagesCount();
 849        } else {
 850            binding.scrollToBottomButton.setEnabled(true);
 851            binding.scrollToBottomButton.show();
 852            if (lastMessageUuid == null) {
 853                lastMessageUuid = conversation.getLatestMessage().getUuid();
 854            }
 855            if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) {
 856                binding.unreadCountCustomView.setVisibility(View.VISIBLE);
 857            }
 858        }
 859    }
 860
 861    private int getIndexOf(String uuid, List<Message> messages) {
 862        if (uuid == null) {
 863            return messages.size() - 1;
 864        }
 865        for (int i = 0; i < messages.size(); ++i) {
 866            if (uuid.equals(messages.get(i).getUuid())) {
 867                return i;
 868            }
 869        }
 870        return -1;
 871    }
 872
 873    private int getIndexOfExtended(String uuid, List<Message> messages) {
 874        if (uuid == null) {
 875            return messages.size() - 1;
 876        }
 877        for (int i = 0; i < messages.size(); ++i) {
 878            if (uuid.equals(messages.get(i).getServerMsgId())) {
 879                return i;
 880            }
 881
 882            if (uuid.equals(messages.get(i).getRemoteMsgId())) {
 883                return i;
 884            }
 885
 886            if (uuid.equals(messages.get(i).getUuid())) {
 887                return i;
 888            }
 889        }
 890        return -1;
 891    }
 892
 893    private ScrollState getScrollPosition() {
 894        final ListView listView = this.binding == null ? null : this.binding.messagesView;
 895        if (listView == null
 896                || listView.getCount() == 0
 897                || listView.getLastVisiblePosition() == listView.getCount() - 1) {
 898            return null;
 899        } else {
 900            final int pos = listView.getFirstVisiblePosition();
 901            final View view = listView.getChildAt(0);
 902            if (view == null) {
 903                return null;
 904            } else {
 905                return new ScrollState(pos, view.getTop());
 906            }
 907        }
 908    }
 909
 910    private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) {
 911        if (scrollPosition != null) {
 912
 913            this.lastMessageUuid = lastMessageUuid;
 914            if (lastMessageUuid != null) {
 915                binding.unreadCountCustomView.setUnreadCount(
 916                        conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
 917            }
 918            // TODO maybe this needs a 'post'
 919            this.binding.messagesView.setSelectionFromTop(
 920                    scrollPosition.position, scrollPosition.offset);
 921            toggleScrollDownButton();
 922        }
 923    }
 924
 925    private void attachLocationToConversation(Conversation conversation, Uri uri) {
 926        if (conversation == null) {
 927            return;
 928        }
 929        final String subject = binding.textinputSubject.getText().toString();
 930        activity.xmppConnectionService.attachLocationToConversation(
 931                conversation,
 932                uri,
 933                subject,
 934                new UiCallback<Message>() {
 935
 936                    @Override
 937                    public void success(Message message) {
 938                        messageSent();
 939                    }
 940
 941                    @Override
 942                    public void error(int errorCode, Message object) {
 943                        // TODO show possible pgp error
 944                    }
 945
 946                    @Override
 947                    public void userInputRequired(PendingIntent pi, Message object) {}
 948                });
 949    }
 950
 951    private void attachFileToConversation(Conversation conversation, Uri uri, String type, Runnable next) {
 952        if (conversation == null) {
 953            return;
 954        }
 955        final String subject = binding.textinputSubject.getText().toString();
 956        if ("application/webxdc+zip".equals(type)) newSubThread();
 957        final Toast prepareFileToast =
 958                Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
 959        prepareFileToast.show();
 960        activity.delegateUriPermissionsToService(uri);
 961        activity.xmppConnectionService.attachFileToConversation(
 962                conversation,
 963                uri,
 964                type,
 965                subject,
 966                new UiInformableCallback<Message>() {
 967                    @Override
 968                    public void inform(final String text) {
 969                        hidePrepareFileToast(prepareFileToast);
 970                        runOnUiThread(() -> activity.replaceToast(text));
 971                    }
 972
 973                    @Override
 974                    public void success(Message message) {
 975                        if (next == null) {
 976                            runOnUiThread(() -> {
 977                                activity.hideToast();
 978                                messageSent();
 979                            });
 980                        } else {
 981                            runOnUiThread(next);
 982                        }
 983                        hidePrepareFileToast(prepareFileToast);
 984                    }
 985
 986                    @Override
 987                    public void error(final int errorCode, Message message) {
 988                        hidePrepareFileToast(prepareFileToast);
 989                        runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
 990                    }
 991
 992                    @Override
 993                    public void userInputRequired(PendingIntent pi, Message message) {
 994                        hidePrepareFileToast(prepareFileToast);
 995                    }
 996                });
 997    }
 998
 999    public void attachEditorContentToConversation(Uri uri) {
1000        mediaPreviewAdapter.addMediaPreviews(
1001                Attachment.of(getActivity(), uri, Attachment.Type.FILE));
1002        toggleInputMethod();
1003    }
1004
1005    private void attachImageToConversation(Conversation conversation, Uri uri, String type, Runnable next) {
1006        if (conversation == null) {
1007            return;
1008        }
1009        final String subject = binding.textinputSubject.getText().toString();
1010        final Toast prepareFileToast =
1011                Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
1012        prepareFileToast.show();
1013        activity.delegateUriPermissionsToService(uri);
1014        activity.xmppConnectionService.attachImageToConversation(
1015                conversation,
1016                uri,
1017                type,
1018                subject,
1019                new UiCallback<Message>() {
1020
1021                    @Override
1022                    public void userInputRequired(PendingIntent pi, Message object) {
1023                        hidePrepareFileToast(prepareFileToast);
1024                    }
1025
1026                    @Override
1027                    public void success(Message message) {
1028                        hidePrepareFileToast(prepareFileToast);
1029                        if (next == null) {
1030                            runOnUiThread(() -> messageSent());
1031                        } else {
1032                            runOnUiThread(next);
1033                        }
1034                    }
1035
1036                    @Override
1037                    public void error(final int error, final Message message) {
1038                        hidePrepareFileToast(prepareFileToast);
1039                        final ConversationsActivity activity = ConversationFragment.this.activity;
1040                        if (activity == null) {
1041                            return;
1042                        }
1043                        activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
1044                    }
1045                });
1046    }
1047
1048    private void hidePrepareFileToast(final Toast prepareFileToast) {
1049        if (prepareFileToast != null && activity != null) {
1050            activity.runOnUiThread(prepareFileToast::cancel);
1051        }
1052    }
1053
1054    private void sendMessage() {
1055        sendMessage((Long) null);
1056    }
1057
1058    private void sendMessage(Long sendAt) {
1059        if (sendAt != null && sendAt < System.currentTimeMillis()) sendAt = null; // No sending in past plz
1060        if (mediaPreviewAdapter.hasAttachments()) {
1061            commitAttachments();
1062            return;
1063        }
1064        Editable body = this.binding.textinput.getText();
1065        if (body == null) body = new SpannableStringBuilder("");
1066        if (body.length() > Config.MAX_DISPLAY_MESSAGE_CHARS) {
1067            Toast.makeText(activity, "Message is too long", Toast.LENGTH_SHORT).show();
1068            return;
1069        }
1070        final Conversation conversation = this.conversation;
1071        final boolean hasSubject = binding.textinputSubject.getText().length() > 0;
1072        if (conversation == null || (body.length() == 0 && (conversation.getThread() == null || !hasSubject))) {
1073            if (Build.VERSION.SDK_INT >= 24) {
1074                binding.textSendButton.showContextMenu(0, 0);
1075            } else {
1076                binding.textSendButton.showContextMenu();
1077            }
1078            return;
1079        }
1080        if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_TEXT)) {
1081            return;
1082        }
1083        final Message message;
1084        if (conversation.getCorrectingMessage() == null) {
1085            boolean attention = false;
1086            if (Pattern.compile("\\A@here\\s.*").matcher(body).find()) {
1087                attention = true;
1088                body.delete(0, 6);
1089                while (body.length() > 0 && Character.isWhitespace(body.charAt(0))) body.delete(0, 1);
1090            }
1091            if (conversation.getReplyTo() != null) {
1092                if (Emoticons.isEmoji(body.toString().replaceAll("\\s", "")) && conversation.getNextCounterpart() == null && !conversation.getReplyTo().isPrivateMessage()) {
1093                    final var aggregated = conversation.getReplyTo().getAggregatedReactions();
1094                    final ImmutableSet.Builder<String> reactionBuilder = new ImmutableSet.Builder<>();
1095                    reactionBuilder.addAll(aggregated.ourReactions);
1096                    reactionBuilder.add(body.toString().replaceAll("\\s", ""));
1097                    activity.xmppConnectionService.sendReactions(conversation.getReplyTo(), reactionBuilder.build());
1098                    messageSent();
1099                    return;
1100                } else {
1101                    message = conversation.getReplyTo().reply();
1102                    message.appendBody(body);
1103                }
1104                message.setEncryption(conversation.getNextEncryption());
1105            } else {
1106                message = new Message(conversation, body.toString(), conversation.getNextEncryption());
1107                message.setBody(hasSubject && body.length() == 0 ? null : body);
1108                if (message.bodyIsOnlyEmojis()) {
1109                    var spannable = message.getSpannableBody(null, null);
1110                    ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1111                    for (ImageSpan span : imageSpans) {
1112                        final int start = spannable.getSpanStart(span);
1113                        final int end = spannable.getSpanEnd(span);
1114                        spannable.delete(start, end);
1115                    }
1116                    if (imageSpans.length == 1 && spannable.toString().replaceAll("\\s", "").length() < 1) {
1117                        // Only one inline image, so it's a sticker
1118                        String source = imageSpans[0].getSource();
1119                        if (source != null && source.length() > 0 && source.substring(0, 4).equals("cid:")) {
1120                            try {
1121                                final Cid cid = BobTransfer.cid(Uri.parse(source));
1122                                final String url = activity.xmppConnectionService.getUrlForCid(cid);
1123                                final File f = activity.xmppConnectionService.getFileForCid(cid);
1124                                if (url != null) {
1125                                    message.setBody("");
1126                                    message.setRelativeFilePath(f.getAbsolutePath());
1127                                    activity.xmppConnectionService.getFileBackend().updateFileParams(message);
1128                                }
1129                            } catch (final Exception e) { }
1130                        }
1131                    }
1132                }
1133            }
1134            if (hasSubject) message.setSubject(binding.textinputSubject.getText().toString());
1135            message.setThread(conversation.getThread());
1136            if (attention) {
1137                message.addPayload(new Element("attention", "urn:xmpp:attention:0"));
1138            }
1139            Message.configurePrivateMessage(message);
1140        } else {
1141            message = conversation.getCorrectingMessage();
1142            if (hasSubject) message.setSubject(binding.textinputSubject.getText().toString());
1143            message.setThread(conversation.getThread());
1144            if (conversation.getReplyTo() != null) {
1145                if (Emoticons.isEmoji(body.toString().replaceAll("\\s", ""))) {
1146                    message.updateReaction(conversation.getReplyTo(), body.toString().replaceAll("\\s", ""));
1147                } else {
1148                    message.updateReplyTo(conversation.getReplyTo(), body);
1149                }
1150            } else {
1151                message.clearReplyReact();
1152                message.setBody(hasSubject && body.length() == 0 ? null : body);
1153            }
1154            if (message.getStatus() == Message.STATUS_WAITING) {
1155                if (sendAt != null) message.setTime(sendAt);
1156                activity.xmppConnectionService.updateMessage(message);
1157                messageSent();
1158                return;
1159            } else {
1160                message.putEdited(message.getUuid(), message.getServerMsgId());
1161                message.setServerMsgId(null);
1162                message.setUuid(UUID.randomUUID().toString());
1163            }
1164        }
1165        if (sendAt != null) message.setTime(sendAt);
1166        switch (conversation.getNextEncryption()) {
1167            case Message.ENCRYPTION_PGP:
1168                sendPgpMessage(message);
1169                break;
1170            default:
1171                sendMessage(message);
1172        }
1173        setupReply(null);
1174    }
1175
1176    private boolean trustKeysIfNeeded(final Conversation conversation, final int requestCode) {
1177        return conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL
1178                && trustKeysIfNeeded(requestCode);
1179    }
1180
1181    protected boolean trustKeysIfNeeded(int requestCode) {
1182        AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
1183        if (axolotlService == null) return false;
1184        final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
1185        boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
1186        boolean hasUndecidedOwn =
1187                !axolotlService
1188                        .getKeysWithTrust(FingerprintStatus.createActiveUndecided())
1189                        .isEmpty();
1190        boolean hasUndecidedContacts =
1191                !axolotlService
1192                        .getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets)
1193                        .isEmpty();
1194        boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
1195        boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1196        boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets);
1197        if (hasUndecidedOwn
1198                || hasUndecidedContacts
1199                || hasPendingKeys
1200                || hasNoTrustedKeys
1201                || hasUnaccepted
1202                || downloadInProgress) {
1203            axolotlService.createSessionsIfNeeded(conversation);
1204            Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
1205            String[] contacts = new String[targets.size()];
1206            for (int i = 0; i < contacts.length; ++i) {
1207                contacts[i] = targets.get(i).toString();
1208            }
1209            intent.putExtra("contacts", contacts);
1210            intent.putExtra(
1211                    EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
1212            intent.putExtra("conversation", conversation.getUuid());
1213            startActivityForResult(intent, requestCode);
1214            return true;
1215        } else {
1216            return false;
1217        }
1218    }
1219
1220    public void updateChatMsgHint() {
1221        final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
1222        if (conversation.getCorrectingMessage() != null) {
1223            this.binding.textInputHint.setVisibility(View.GONE);
1224            this.binding.textinput.setHint(R.string.send_corrected_message);
1225            binding.conversationViewPager.setCurrentItem(0);
1226        } else if (multi && conversation.getNextCounterpart() != null) {
1227            this.binding.textinput.setHint(R.string.send_message);
1228            this.binding.textInputHint.setVisibility(View.VISIBLE);
1229            final MucOptions.User user = conversation.getMucOptions().findUserByName(conversation.getNextCounterpart().getResource());
1230            String nick = user == null ? null : user.getNick();
1231            if (nick == null) nick = conversation.getNextCounterpart().getResource();
1232            this.binding.textInputHint.setText(
1233                    getString(
1234                            R.string.send_private_message_to,
1235                            nick));
1236            binding.conversationViewPager.setCurrentItem(0);
1237        } else if (multi && !conversation.getMucOptions().participating()) {
1238            this.binding.textInputHint.setVisibility(View.GONE);
1239            this.binding.textinput.setHint(R.string.you_are_not_participating);
1240            this.binding.inputLayout.setBackgroundColor(android.R.color.transparent);
1241        } else {
1242            this.binding.textInputHint.setVisibility(View.GONE);
1243            if (activity == null) return;
1244            this.binding.textinput.setHint(UIHelper.getMessageHint(activity, conversation));
1245            this.binding.inputLayout.setBackground(activity.getDrawable(R.drawable.background_message_bubble));
1246            activity.invalidateOptionsMenu();
1247        }
1248
1249        binding.messagesView.post(this::updateThreadFromLastMessage);
1250    }
1251
1252    public void setupIme() {
1253        this.binding.textinput.refreshIme();
1254    }
1255
1256    private void handleActivityResult(ActivityResult activityResult) {
1257        if (activityResult.resultCode == Activity.RESULT_OK) {
1258            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
1259        } else {
1260            handleNegativeActivityResult(activityResult.requestCode);
1261        }
1262    }
1263
1264    private void handlePositiveActivityResult(int requestCode, final Intent data) {
1265        switch (requestCode) {
1266            case REQUEST_WEBXDC_STORE:
1267                mediaPreviewAdapter.addMediaPreviews(Attachment.of(activity, data.getData(), Attachment.Type.FILE));
1268                toggleInputMethod();
1269                break;
1270            case REQUEST_SAVE_STICKER:
1271                final DocumentFile df = DocumentFile.fromSingleUri(activity, data.getData());
1272                final File f = savingAsSticker;
1273                savingAsSticker = null;
1274                try {
1275                    activity.xmppConnectionService.getFileBackend().copyFileToDocumentFile(activity, f, df);
1276                    Toast.makeText(activity, "Sticker saved", Toast.LENGTH_SHORT).show();
1277                } catch (final FileBackend.FileCopyException e) {
1278                    Toast.makeText(activity, e.getResId(), Toast.LENGTH_SHORT).show();
1279                }
1280                break;
1281            case REQUEST_TRUST_KEYS_TEXT:
1282                sendMessage();
1283                break;
1284            case REQUEST_TRUST_KEYS_ATTACHMENTS:
1285                commitAttachments();
1286                break;
1287            case REQUEST_START_AUDIO_CALL:
1288                triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1289                break;
1290            case REQUEST_START_VIDEO_CALL:
1291                triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1292                break;
1293            case ATTACHMENT_CHOICE_CHOOSE_IMAGE: {
1294                final Uri takePhotoUri = pendingTakePhotoUri.pop();
1295                if (takePhotoUri != null && (data == null || (data.getData() == null && data.getClipData() == null))) {
1296                    mediaPreviewAdapter.addMediaPreviews(
1297                            Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
1298                }
1299                final List<Attachment> imageUris =
1300                        Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
1301                mediaPreviewAdapter.addMediaPreviews(imageUris);
1302                toggleInputMethod();
1303                break;
1304            }
1305            case ATTACHMENT_CHOICE_TAKE_PHOTO: {
1306                final Uri takePhotoUri = pendingTakePhotoUri.pop();
1307                if (takePhotoUri != null) {
1308                    mediaPreviewAdapter.addMediaPreviews(
1309                            Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
1310                    toggleInputMethod();
1311                } else {
1312                    Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
1313                }
1314                break;
1315            }
1316            case ATTACHMENT_CHOICE_CHOOSE_FILE:
1317            case ATTACHMENT_CHOICE_RECORD_VIDEO:
1318            case ATTACHMENT_CHOICE_RECORD_VOICE:
1319                final Attachment.Type type =
1320                        requestCode == ATTACHMENT_CHOICE_RECORD_VOICE
1321                                ? Attachment.Type.RECORDING
1322                                : Attachment.Type.FILE;
1323                final List<Attachment> fileUris =
1324                        Attachment.extractAttachments(getActivity(), data, type);
1325                mediaPreviewAdapter.addMediaPreviews(fileUris);
1326                toggleInputMethod();
1327                break;
1328            case ATTACHMENT_CHOICE_LOCATION:
1329                final double latitude = data.getDoubleExtra("latitude", 0);
1330                final double longitude = data.getDoubleExtra("longitude", 0);
1331                final int accuracy = data.getIntExtra("accuracy", 0);
1332                final Uri geo;
1333                if (accuracy > 0) {
1334                    geo = Uri.parse(String.format("geo:%s,%s;u=%s", latitude, longitude, accuracy));
1335                } else {
1336                    geo = Uri.parse(String.format("geo:%s,%s", latitude, longitude));
1337                }
1338                mediaPreviewAdapter.addMediaPreviews(
1339                        Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
1340                toggleInputMethod();
1341                break;
1342            case REQUEST_INVITE_TO_CONVERSATION:
1343                XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
1344                if (invite != null) {
1345                    if (invite.execute(activity)) {
1346                        activity.mToast =
1347                                Toast.makeText(
1348                                        activity, R.string.creating_conference, Toast.LENGTH_LONG);
1349                        activity.mToast.show();
1350                    }
1351                }
1352                break;
1353        }
1354    }
1355
1356    private void commitAttachments() {
1357        final List<Attachment> attachments = mediaPreviewAdapter.getAttachments();
1358        if (anyNeedsExternalStoragePermission(attachments)
1359                && !hasPermissions(
1360                        REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1361            return;
1362        }
1363        if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_ATTACHMENTS)) {
1364            return;
1365        }
1366        final PresenceSelector.OnPresenceSelected callback =
1367                () -> {
1368                    final Iterator<Attachment> i = attachments.iterator();
1369                    final Runnable next = new Runnable() {
1370                        @Override
1371                        public void run() {
1372                            try {
1373                                if (!i.hasNext()) return;
1374                                final Attachment attachment = i.next();
1375                                if (attachment.getType() == Attachment.Type.LOCATION) {
1376                                        attachLocationToConversation(conversation, attachment.getUri());
1377                                    if (i.hasNext()) runOnUiThread(this);
1378                                } else if (attachment.getType() == Attachment.Type.IMAGE) {
1379                                    Log.d(
1380                                          Config.LOGTAG,
1381                                          "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
1382                                    attachImageToConversation(conversation, attachment.getUri(), attachment.getMime(), this);
1383                                } else {
1384                                    Log.d(
1385                                          Config.LOGTAG,
1386                                          "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1387                                    attachFileToConversation(conversation, attachment.getUri(), attachment.getMime(), this);
1388                                }
1389                                i.remove();
1390                                if (!i.hasNext()) messageSent();
1391                            } catch (final java.util.ConcurrentModificationException e) {
1392                                // Abort, leave any unsent attachments alone for the user to try again
1393                                Toast.makeText(activity, "Sometimes went wrong with some attachments. Try again?", Toast.LENGTH_SHORT).show();
1394                            }
1395                            mediaPreviewAdapter.notifyDataSetChanged();
1396                            toggleInputMethod();
1397                        }
1398                    };
1399                    next.run();
1400                };
1401        if (conversation == null
1402                || conversation.getMode() == Conversation.MODE_MULTI
1403                || Attachment.canBeSendInBand(attachments)
1404                || (conversation.getAccount().httpUploadAvailable()
1405                        && FileBackend.allFilesUnderSize(
1406                                getActivity(), attachments, getMaxHttpUploadSize(conversation)))) {
1407            callback.onPresenceSelected();
1408        } else {
1409            activity.selectPresence(conversation, callback);
1410        }
1411    }
1412
1413    private static boolean anyNeedsExternalStoragePermission(
1414            final Collection<Attachment> attachments) {
1415        for (final Attachment attachment : attachments) {
1416            if (attachment.getType() != Attachment.Type.LOCATION) {
1417                return true;
1418            }
1419        }
1420        return false;
1421    }
1422
1423    public void toggleInputMethod() {
1424        boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
1425        binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
1426        binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
1427        updateSendButton();
1428    }
1429
1430    private void handleNegativeActivityResult(int requestCode) {
1431        switch (requestCode) {
1432            case ATTACHMENT_CHOICE_TAKE_PHOTO:
1433                if (pendingTakePhotoUri.clear()) {
1434                    Log.d(
1435                            Config.LOGTAG,
1436                            "cleared pending photo uri after negative activity result");
1437                }
1438                break;
1439        }
1440    }
1441
1442    @Override
1443    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
1444        super.onActivityResult(requestCode, resultCode, data);
1445        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
1446        if (activity != null && activity.xmppConnectionService != null) {
1447            handleActivityResult(activityResult);
1448        } else {
1449            this.postponedActivityResult.push(activityResult);
1450        }
1451    }
1452
1453    public void unblockConversation(final Blockable conversation) {
1454        activity.xmppConnectionService.sendUnblockRequest(conversation);
1455    }
1456
1457    @Override
1458    public void onAttach(Activity activity) {
1459        super.onAttach(activity);
1460        Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
1461        if (activity instanceof ConversationsActivity) {
1462            this.activity = (ConversationsActivity) activity;
1463        } else {
1464            throw new IllegalStateException(
1465                    "Trying to attach fragment to activity that is not the ConversationsActivity");
1466        }
1467    }
1468
1469    @Override
1470    public void onDetach() {
1471        super.onDetach();
1472        this.activity = null; // TODO maybe not a good idea since some callbacks really need it
1473    }
1474
1475    @Override
1476    public void onCreate(Bundle savedInstanceState) {
1477        super.onCreate(savedInstanceState);
1478        setHasOptionsMenu(true);
1479        activity.getOnBackPressedDispatcher().addCallback(this, backPressedLeaveSingleThread);
1480        // On wide-screen devices, `secondary_fragment` is initialized to an empty `ConversationFragment`
1481        final var conversation = this.conversation;
1482        if (savedInstanceState == null && conversation != null) {
1483            conversation.jumpToLatest();
1484        }
1485    }
1486
1487    @Override
1488    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
1489        if (activity != null && activity.xmppConnectionService != null && activity.xmppConnectionService.isOnboarding()) return;
1490
1491        menuInflater.inflate(R.menu.fragment_conversation, menu);
1492        final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
1493        final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
1494        final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
1495        final MenuItem menuMute = menu.findItem(R.id.action_mute);
1496        final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
1497        final MenuItem menuCall = menu.findItem(R.id.action_call);
1498        final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
1499        final MenuItem menuVideoCall = menu.findItem(R.id.action_video_call);
1500        final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
1501        final MenuItem menuArchiveChat = menu.findItem(R.id.action_archive);
1502
1503        if (conversation != null) {
1504            if (conversation.getMode() == Conversation.MODE_MULTI) {
1505                menuContactDetails.setVisible(false);
1506                menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
1507                menuMucDetails.setTitle(
1508                        conversation.getMucOptions().isPrivateAndNonAnonymous()
1509                                ? R.string.action_muc_details
1510                                : R.string.channel_details);
1511                menuCall.setVisible(false);
1512                menuOngoingCall.setVisible(false);
1513                menuArchiveChat.setTitle("Leave " + (conversation.getMucOptions().isPrivateAndNonAnonymous() ? "group chat" : "Channel"));
1514            } else {
1515                final XmppConnectionService service =
1516                        activity == null ? null : activity.xmppConnectionService;
1517                final Optional<OngoingRtpSession> ongoingRtpSession =
1518                        service == null
1519                                ? Optional.absent()
1520                                : service.getJingleConnectionManager()
1521                                        .getOngoingRtpConnection(conversation.getContact());
1522                if (ongoingRtpSession.isPresent()) {
1523                    menuOngoingCall.setVisible(true);
1524                    menuCall.setVisible(false);
1525                } else {
1526                    menuOngoingCall.setVisible(false);
1527                    final RtpCapability.Capability rtpCapability =
1528                            RtpCapability.check(conversation.getContact());
1529                    final boolean cameraAvailable =
1530                            activity != null && activity.isCameraFeatureAvailable();
1531                    menuCall.setVisible(true);
1532                    menuVideoCall.setVisible(rtpCapability != RtpCapability.Capability.AUDIO && cameraAvailable);
1533                }
1534                menuContactDetails.setVisible(!this.conversation.withSelf());
1535                menuMucDetails.setVisible(false);
1536                final var connection = this.conversation.getAccount().getXmppConnection();
1537                menuInviteContact.setVisible(
1538                        !connection.getManager(MultiUserChatManager.class).getServices().isEmpty());
1539            }
1540            if (conversation.isMuted()) {
1541                menuMute.setVisible(false);
1542            } else {
1543                menuUnmute.setVisible(false);
1544            }
1545            ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1546            ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
1547            if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
1548                menuTogglePinned.setTitle(R.string.remove_from_favorites);
1549            } else {
1550                menuTogglePinned.setTitle(R.string.add_to_favorites);
1551            }
1552        }
1553        super.onCreateOptionsMenu(menu, menuInflater);
1554    }
1555
1556    @Override
1557    public View onCreateView(
1558            final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
1559        this.binding =
1560                DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
1561        binding.getRoot().setOnClickListener(null); // TODO why the fuck did we do this?
1562
1563        binding.textinput.setOnEditorActionListener(mEditorActionListener);
1564        binding.textinput.setRichContentListener(new String[] {"image/*"}, mEditorContentListener);
1565        DisplayMetrics displayMetrics = new DisplayMetrics();
1566        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
1567        if (displayMetrics.heightPixels > 0) binding.textinput.setMaxHeight(displayMetrics.heightPixels / 4);
1568
1569        binding.textSendButton.setOnClickListener(this.mSendButtonListener);
1570        binding.contextPreviewCancel.setOnClickListener((v) -> {
1571            setThread(null);
1572            conversation.setUserSelectedThread(false);
1573            setupReply(null);
1574        });
1575        binding.requestVoice.setOnClickListener((v) -> {
1576            activity.xmppConnectionService.requestVoice(conversation.getAccount(), conversation.getJid());
1577            binding.requestVoice.setVisibility(View.GONE);
1578            Toast.makeText(activity, "Your request has been sent to the moderators", Toast.LENGTH_SHORT).show();
1579        });
1580
1581        binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1582        binding.messagesView.setOnScrollListener(mOnScrollListener);
1583        binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1584        mediaPreviewAdapter = new MediaPreviewAdapter(this);
1585        binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1586        messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1587        messageListAdapter.setOnContactPictureClicked(this);
1588        messageListAdapter.setOnContactPictureLongClicked(this);
1589        messageListAdapter.setOnInlineImageLongClicked(this);
1590        messageListAdapter.setConversationFragment(this);
1591        binding.messagesView.setAdapter(messageListAdapter);
1592
1593        binding.textinput.addTextChangedListener(
1594                new StylingHelper.MessageEditorStyler(binding.textinput, messageListAdapter));
1595
1596        registerForContextMenu(binding.messagesView);
1597        registerForContextMenu(binding.textSendButton);
1598
1599        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1600            this.binding.textinput.setCustomInsertionActionModeCallback(
1601                    new EditMessageActionModeCallback(this.binding.textinput));
1602            this.binding.textinput.setCustomSelectionActionModeCallback(
1603                    new EditMessageSelectionActionModeCallback(this.binding.textinput));
1604        }
1605
1606        messageListAdapter.setOnMessageBoxClicked(message -> {
1607            if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1608            setThread(message.getThread());
1609            conversation.setUserSelectedThread(true);
1610        });
1611
1612        messageListAdapter.setOnMessageBoxSwiped(message -> {
1613            quoteMessage(message);
1614        });
1615
1616        binding.threadIdenticonLayout.setOnClickListener(v -> {
1617            boolean wasLocked = conversation.getLockThread();
1618            conversation.setLockThread(false);
1619            backPressedLeaveSingleThread.setEnabled(false);
1620            if (wasLocked) {
1621                setThread(null);
1622                conversation.setUserSelectedThread(false);
1623                refresh();
1624                updateThreadFromLastMessage();
1625            } else {
1626                newThread();
1627                conversation.setUserSelectedThread(true);
1628                newThreadTutorialToast("Switched to new thread");
1629            }
1630        });
1631
1632        binding.threadIdenticonLayout.setOnLongClickListener(v -> {
1633            boolean wasLocked = conversation.getLockThread();
1634            conversation.setLockThread(false);
1635            backPressedLeaveSingleThread.setEnabled(false);
1636            setThread(null);
1637            conversation.setUserSelectedThread(true);
1638            if (wasLocked) refresh();
1639            newThreadTutorialToast("Cleared thread");
1640            return true;
1641        });
1642
1643        Autocomplete.<MucOptions.User>on(binding.textinput)
1644            .with(activity.getDrawable(R.drawable.background_message_bubble))
1645            .with(new CharPolicy('@'))
1646            .with(new RecyclerViewPresenter<MucOptions.User>(activity) {
1647                protected UserAdapter adapter;
1648
1649                @Override
1650                protected Adapter instantiateAdapter() {
1651                    adapter = new UserAdapter(false) {
1652                        @Override
1653                        public void onBindViewHolder(UserAdapter.ViewHolder viewHolder, int position) {
1654                            super.onBindViewHolder(viewHolder, position);
1655                            final var item = getItem(position);
1656                            viewHolder.binding.getRoot().setOnClickListener(v -> {
1657                                dispatchClick(item);
1658                            });
1659                        }
1660                    };
1661                    return adapter;
1662                }
1663
1664                @Override
1665                protected void onQuery(@Nullable CharSequence query) {
1666                    if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1667
1668                    final var allUsers = conversation.getMucOptions().getUsers();
1669                    if (!conversation.getMucOptions().getUsersByRole(Role.MODERATOR).isEmpty()) {
1670                        final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0role:moderator", "Notify active moderators", new HashSet<>());
1671                        u.setRole(Role.PARTICIPANT);
1672                        allUsers.add(u);
1673                    }
1674                    if (!allUsers.isEmpty() && conversation.getMucOptions().getSelf() != null && conversation.getMucOptions().getSelf().ranks(Affiliation.MEMBER)) {
1675                        final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0attention", "Notify active participants", new HashSet<>());
1676                        u.setRole(Role.PARTICIPANT);
1677                        allUsers.add(u);
1678                    }
1679                    final String needle = query.toString().toLowerCase(Locale.getDefault());
1680                    if (getRecyclerView() != null) getRecyclerView().setItemAnimator(null);
1681                    adapter.submitList(
1682                        Ordering.natural().immutableSortedCopy(Collections2.filter(
1683                            allUsers,
1684                            user -> {
1685                                if ("mods".contains(needle) && "\0role:moderator".equals(user.getOccupantId())) return true;
1686                                if ("here".contains(needle) && "\0attention".equals(user.getOccupantId())) return true;
1687                                final String name = user.getNick();
1688                                if (name == null) return false;
1689                                for (final var hat : user.getHats()) {
1690                                    if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1691                                }
1692                                for (final var hat : user.getPseudoHats(activity)) {
1693                                    if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1694                                }
1695                                final Contact contact = user.getContact();
1696                                return name.toLowerCase(Locale.getDefault()).contains(needle)
1697                                    || contact != null
1698                                    && contact.getDisplayName().toLowerCase(Locale.getDefault()).contains(needle);
1699                            })));
1700                }
1701
1702                @Override
1703                protected AutocompletePresenter.PopupDimensions getPopupDimensions() {
1704                    final var dim = new AutocompletePresenter.PopupDimensions();
1705                    dim.width = displayMetrics.widthPixels * 4/5;
1706                    return dim;
1707                }
1708            })
1709            .with(new AutocompleteCallback<MucOptions.User>() {
1710                @Override
1711                public boolean onPopupItemClicked(Editable editable, MucOptions.User user) {
1712                    int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1713                    if (range == null) return false;
1714                    range[0] -= 1;
1715                    if ("\0attention".equals(user.getOccupantId())) {
1716                        editable.delete(Math.max(0, range[0]), Math.min(editable.length(), range[1]));
1717                        editable.insert(0, "@here ");
1718                        return true;
1719                    }
1720                    int colon = editable.toString().indexOf(':');
1721                    final var beforeColon = range[0] < colon;
1722                    String prefix = "";
1723                    String suffix = " ";
1724                    if (beforeColon) suffix = ", ";
1725                    if (colon < 0 && range[0] == 0) suffix = ": ";
1726                    if (colon > 0 && colon == range[0] - 2) {
1727                        prefix = ", ";
1728                        suffix = ": ";
1729                        range[0] -= 2;
1730                    }
1731                    var insert = user.getNick();
1732                    if ("\0role:moderator".equals(user.getOccupantId())) {
1733                        insert = conversation.getMucOptions().getUsersByRole(Role.MODERATOR).stream().map(MucOptions.User::getNick).collect(Collectors.joining(", "));
1734                    }
1735                    editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), prefix + insert + suffix);
1736                    return true;
1737                }
1738
1739                @Override
1740                public void onPopupVisibilityChanged(boolean shown) {}
1741            }).build();
1742
1743        Handler emojiDebounce = new Handler(Looper.getMainLooper());
1744        setupEmojiSearch();
1745        Autocomplete.<EmojiSearch.Emoji>on(binding.textinput)
1746            .with(activity.getDrawable(R.drawable.background_message_bubble))
1747            .with(new CharPolicy(':'))
1748            .with(new RecyclerViewPresenter<EmojiSearch.Emoji>(activity) {
1749                protected EmojiSearch.EmojiSearchAdapter adapter;
1750
1751                @Override
1752                protected Adapter instantiateAdapter() {
1753                    setupEmojiSearch();
1754                    adapter = emojiSearch.makeAdapter(item -> dispatchClick(item));
1755                    return adapter;
1756                }
1757
1758                @Override
1759                protected void onViewHidden() {
1760                    if (getRecyclerView() == null) return;
1761                    super.onViewHidden();
1762                }
1763
1764                @Override
1765                protected void onQuery(@Nullable CharSequence query) {
1766                    if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1767
1768                    emojiDebounce.removeCallbacksAndMessages(null);
1769                    emojiDebounce.postDelayed(() -> {
1770                        if (getRecyclerView() == null) return;
1771                        getRecyclerView().setItemAnimator(null);
1772                        adapter.search(activity, getRecyclerView(), query.toString());
1773                    }, 100L);
1774                }
1775            })
1776            .with(new AutocompleteCallback<EmojiSearch.Emoji>() {
1777                @Override
1778                public boolean onPopupItemClicked(Editable editable, EmojiSearch.Emoji emoji) {
1779                    int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1780                    if (range == null) return false;
1781                    range[0] -= 1;
1782                    final var toInsert = emoji.toInsert();
1783                    toInsert.append(" ");
1784                    editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), toInsert);
1785                    return true;
1786                }
1787
1788                @Override
1789                public void onPopupVisibilityChanged(boolean shown) {}
1790            }).build();
1791
1792        return binding.getRoot();
1793    }
1794
1795    protected void setupEmojiSearch() {
1796        if (activity != null && activity.xmppConnectionService != null) {
1797            if (emojiSearch == null) {
1798                emojiSearch = activity.xmppConnectionService.emojiSearch();
1799            }
1800        }
1801    }
1802
1803    protected void newThreadTutorialToast(String s) {
1804        if (activity == null) return;
1805        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1806        final int tutorialCount = p.getInt("thread_tutorial", 0);
1807        if (tutorialCount < 5) {
1808            Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1809            p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1810        }
1811    }
1812
1813    @Override
1814    public void onDestroyView() {
1815        super.onDestroyView();
1816        Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1817        messageListAdapter.setOnContactPictureClicked(null);
1818        messageListAdapter.setOnContactPictureLongClicked(null);
1819        messageListAdapter.setOnInlineImageLongClicked(null);
1820        messageListAdapter.setConversationFragment(null);
1821        messageListAdapter.setOnMessageBoxClicked(null);
1822        messageListAdapter.setOnMessageBoxSwiped(null);
1823        binding.conversationViewPager.setAdapter(null);
1824        if (conversation != null) conversation.setupViewPager(null, null, false, null);
1825    }
1826
1827    public void quoteText(String text) {
1828        if (binding.textinput.isEnabled()) {
1829            binding.textinput.insertAsQuote(text);
1830            binding.textinput.requestFocus();
1831            InputMethodManager inputMethodManager =
1832                    (InputMethodManager)
1833                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1834            if (inputMethodManager != null) {
1835                inputMethodManager.showSoftInput(
1836                        binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1837            }
1838        }
1839    }
1840
1841    private void quoteMessage(Message message) {
1842        if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1843        setThread(message.getThread());
1844        conversation.setUserSelectedThread(true);
1845        if (!forkNullThread(message)) newThread();
1846        setupReply(message);
1847    }
1848
1849    private boolean forkNullThread(Message message) {
1850        if (message.getThread() != null || conversation.getMode() != Conversation.MODE_MULTI) return true;
1851        for (final Message m : conversation.findReplies(message.getServerMsgId())) {
1852            final Element thread = m.getThread();
1853            if (thread != null) {
1854                setThread(thread);
1855                return true;
1856            }
1857        }
1858
1859        return false;
1860    }
1861
1862    private void setupReply(Message message) {
1863        if (message != null) {
1864            final var correcting = conversation.getCorrectingMessage();
1865            if (correcting != null && correcting.getUuid().equals(message.getUuid())) return;
1866        }
1867        conversation.setReplyTo(message);
1868        if (message == null) {
1869            binding.contextPreview.setVisibility(View.GONE);
1870            binding.textsend.setBackgroundResource(R.drawable.textsend);
1871            return;
1872        }
1873
1874        var body = message.getSpannableBody(null, null);
1875        if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1876        messageListAdapter.handleTextQuotes(binding.contextPreviewText, body);
1877        binding.contextPreviewText.setText(body);
1878        binding.contextPreview.setVisibility(View.VISIBLE);
1879    }
1880
1881    private void setThread(Element thread) {
1882        this.conversation.setThread(thread);
1883        binding.threadIdenticon.setAlpha(0f);
1884        binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1885        if (thread != null) {
1886            final String threadId = thread.getContent();
1887            if (threadId != null) {
1888                binding.threadIdenticon.setAlpha(1f);
1889                binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1890                binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1891            }
1892        }
1893        updateSendButton();
1894    }
1895
1896
1897    private void highlightMessage(String uuid) {
1898        binding.messagesView.postDelayed(() -> {
1899            int actualIndex = getIndexOfExtended(uuid, messageList);
1900
1901            if (actualIndex == -1) {
1902                return;
1903            }
1904
1905            View view = ListViewUtils.getViewByPosition(actualIndex, binding.messagesView);
1906            View messageBox = view.findViewById(R.id.message_box);
1907            if (messageBox != null) {
1908                messageBox.animate()
1909                        .scaleX(1.14f)
1910                        .scaleY(1.14f)
1911                        .setInterpolator(new CycleInterpolator(0.5f))
1912                        .setDuration(400L)
1913                        .start();
1914            }
1915        }, 300L);
1916    }
1917
1918    private void updateSelection(String uuid, Integer offsetFormTop, Runnable selectionUpdatedRunnable, boolean populateFromMam, boolean recursiveFetch) {
1919        if (recursiveFetch && (fetchHistoryDialog == null || !fetchHistoryDialog.isShowing())) return;
1920
1921        int pos = getIndexOfExtended(uuid, messageList);
1922
1923        Runnable updateSelectionRunnable = () -> {
1924            FragmentConversationBinding binding = ConversationFragment.this.binding;
1925
1926            Runnable performRunnable = () -> {
1927                if (offsetFormTop != null) {
1928                    binding.messagesView.setSelectionFromTop(pos, offsetFormTop);
1929                    return;
1930                }
1931
1932                binding.messagesView.setSelection(pos);
1933            };
1934
1935            performRunnable.run();
1936            binding.messagesView.post(performRunnable);
1937
1938            if (selectionUpdatedRunnable != null) {
1939                selectionUpdatedRunnable.run();
1940            }
1941        };
1942
1943        if (pos != -1) {
1944            hideFetchHistoryDialog();
1945            updateSelectionRunnable.run();
1946        } else {
1947            activity.xmppConnectionService.jumpToMessage(conversation, uuid, new XmppConnectionService.JumpToMessageListener() {
1948                @Override
1949                public void onSuccess() {
1950                    activity.runOnUiThread(() -> {
1951                        refresh(false);
1952                        conversation.messagesLoaded.set(true);
1953                        conversation.historyPartLoadedForward.set(true);
1954                        toggleScrollDownButton();
1955                        updateSelection(uuid, binding.messagesView.getHeight() / 2, selectionUpdatedRunnable, populateFromMam, false);
1956                    });
1957                }
1958
1959                @Override
1960                public void onNotFound() {
1961                    activity.runOnUiThread(() -> {
1962                        if (populateFromMam && conversation.hasMessagesLeftOnServer()) {
1963                            showFetchHistoryDialog();
1964                            loadMoreMessages(true, false, binding.messagesView);
1965                            binding.messagesView.postDelayed(() -> updateSelection(uuid, binding.messagesView.getHeight() / 2, selectionUpdatedRunnable, populateFromMam, true), 500L);
1966                        } else {
1967                            hideFetchHistoryDialog();
1968                        }
1969                    });
1970                }
1971            });
1972        }
1973    }
1974
1975    private void showFetchHistoryDialog() {
1976        if (fetchHistoryDialog != null && fetchHistoryDialog.isShowing()) return;
1977
1978        fetchHistoryDialog = new ProgressDialog(getActivity());
1979        fetchHistoryDialog.setIndeterminate(true);
1980        fetchHistoryDialog.setMessage(getString(R.string.please_wait));
1981        fetchHistoryDialog.setCancelable(true);
1982        fetchHistoryDialog.show();
1983    }
1984
1985    private void hideFetchHistoryDialog() {
1986        if (fetchHistoryDialog != null && fetchHistoryDialog.isShowing()) {
1987            fetchHistoryDialog.hide();
1988        }
1989    }
1990
1991    @Override
1992    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1993        // This should cancel any remaining click events that would otherwise trigger links
1994        v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1995
1996        if (v == binding.textSendButton) {
1997            super.onCreateContextMenu(menu, v, menuInfo);
1998            try {
1999                java.lang.reflect.Method m = menu.getClass().getSuperclass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
2000                m.setAccessible(true);
2001                m.invoke(menu, true);
2002            } catch (Exception e) {
2003                e.printStackTrace();
2004            }
2005            Menu tmpMenu = new PopupMenu(activity, null).getMenu();
2006            activity.getMenuInflater().inflate(R.menu.fragment_conversation, tmpMenu);
2007            MenuItem attachMenu = tmpMenu.findItem(R.id.action_attach_file);
2008            for (int i = 0; i < attachMenu.getSubMenu().size(); i++) {
2009                MenuItem item = attachMenu.getSubMenu().getItem(i);
2010                MenuItem newItem = menu.add(item.getGroupId(), item.getItemId(), item.getOrder(), item.getTitle());
2011                newItem.setIcon(item.getIcon());
2012            }
2013
2014            extensions.clear();
2015            final var xmppConnectionService = activity.xmppConnectionService;
2016            final var dir = new File(xmppConnectionService.getExternalFilesDir(null), "extensions");
2017            for (File file : Files.fileTraverser().breadthFirst(dir)) {
2018                if (file.isFile() && file.canRead()) {
2019                    final var dummy = new Message(conversation, null, conversation.getNextEncryption());
2020                    dummy.setStatus(Message.STATUS_DUMMY);
2021                    dummy.setThread(conversation.getThread());
2022                    dummy.setUuid(file.getName());
2023                    final var xdc = new WebxdcPage(activity, file, dummy);
2024                    extensions.add(xdc);
2025                    final var item = menu.add(0x1, extensions.size() - 1, 0, xdc.getName());
2026                    item.setIcon(xdc.getIcon(24));
2027                }
2028            }
2029            ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
2030            return;
2031        }
2032
2033        synchronized (this.messageList) {
2034            super.onCreateContextMenu(menu, v, menuInfo);
2035            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
2036            this.selectedMessage = this.messageList.get(acmi.position);
2037            populateContextMenu(menu);
2038        }
2039    }
2040
2041    private void populateContextMenu(final ContextMenu menu) {
2042        final Message m = this.selectedMessage;
2043        final Transferable t = m.getTransferable();
2044        if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
2045
2046            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
2047                    || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
2048                return;
2049            }
2050
2051            if (m.getStatus() == Message.STATUS_RECEIVED
2052                    && t != null
2053                    && (t.getStatus() == Transferable.STATUS_CANCELLED
2054                            || t.getStatus() == Transferable.STATUS_FAILED)) {
2055                return;
2056            }
2057
2058            final boolean deleted = m.isDeleted();
2059            final boolean encrypted =
2060                    m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
2061                            || m.getEncryption() == Message.ENCRYPTION_PGP;
2062            final boolean receiving =
2063                    m.getStatus() == Message.STATUS_RECEIVED
2064                            && (t instanceof JingleFileTransferConnection
2065                                    || t instanceof HttpDownloadConnection);
2066            activity.getMenuInflater().inflate(R.menu.message_context, menu);
2067            final MenuItem reportAndBlock = menu.findItem(R.id.action_report_and_block);
2068            final MenuItem addReaction = menu.findItem(R.id.action_add_reaction);
2069            final MenuItem openWith = menu.findItem(R.id.open_with);
2070            final MenuItem copyMessage = menu.findItem(R.id.copy_message);
2071            final MenuItem quoteMessage = menu.findItem(R.id.quote_message);
2072            final MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
2073            final MenuItem correctMessage = menu.findItem(R.id.correct_message);
2074            final MenuItem retractMessage = menu.findItem(R.id.retract_message);
2075            final MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
2076            final MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
2077            final MenuItem shareWith = menu.findItem(R.id.share_with);
2078            final MenuItem sendAgain = menu.findItem(R.id.send_again);
2079            final MenuItem retryAsP2P = menu.findItem(R.id.send_again_as_p2p);
2080            final MenuItem copyUrl = menu.findItem(R.id.copy_url);
2081            final MenuItem copyLink = menu.findItem(R.id.copy_link);
2082            final MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
2083            final MenuItem downloadFile = menu.findItem(R.id.download_file);
2084            final MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
2085            final MenuItem blockMedia = menu.findItem(R.id.block_media);
2086            final MenuItem deleteFile = menu.findItem(R.id.delete_file);
2087            final MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
2088            onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
2089            final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
2090            final boolean showError =
2091                    m.getStatus() == Message.STATUS_SEND_FAILED
2092                            && m.getErrorMessage() != null
2093                            && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
2094            final Conversational conversational = m.getConversation();
2095            final var connection = conversational.getAccount().getXmppConnection();
2096            if (m.getStatus() == Message.STATUS_RECEIVED
2097                    && conversational instanceof Conversation c) {
2098                if (c.isWithStranger()
2099                        && m.getServerMsgId() != null
2100                        && !c.isBlocked()
2101                        && connection != null
2102                        && connection.getFeatures().spamReporting()) {
2103                    reportAndBlock.setVisible(true);
2104                }
2105            }
2106            if (conversational instanceof Conversation c) {
2107                addReaction.setVisible(
2108                        m.getStatus() != Message.STATUS_SEND_FAILED
2109                                && !m.isDeleted()
2110                                && !m.isPrivateMessage()
2111                                && (c.getMode() == Conversational.MODE_SINGLE
2112                                        || (c.getMucOptions().occupantId()
2113                                                && c.getMucOptions().participating())));
2114            } else {
2115                addReaction.setVisible(false);
2116            }
2117            if (!m.isFileOrImage()
2118                    && !encrypted
2119                    && !m.isGeoUri()
2120                    && !m.treatAsDownloadable()
2121                    && !unInitiatedButKnownSize
2122                    && t == null) {
2123                copyMessage.setVisible(true);
2124                quoteMessage.setVisible(!showError && !MessageUtils.prepareQuote(m).isEmpty());
2125                final var firstUri = Iterables.getFirst(Linkify.getLinks(m.getBody()), null);
2126                if (firstUri != null) {
2127                    final var scheme = firstUri.getScheme();
2128                    final @StringRes int resForScheme =
2129                            switch (scheme) {
2130                                case "xmpp" -> R.string.copy_jabber_id;
2131                                case "http", "https", "gemini" -> R.string.copy_link;
2132                                case "geo" -> R.string.copy_geo_uri;
2133                                case "tel" -> R.string.copy_telephone_number;
2134                                case "mailto" -> R.string.copy_email_address;
2135                                default -> R.string.copy_URI;
2136                            };
2137                    copyLink.setTitle(resForScheme);
2138                    copyLink.setVisible(true);
2139                } else {
2140                    copyLink.setVisible(false);
2141                }
2142            }
2143            quoteMessage.setVisible(!encrypted && !showError);
2144            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
2145                retryDecryption.setVisible(true);
2146            }
2147            if (!showError
2148                    && m.getType() == Message.TYPE_TEXT
2149                    && m.isEditable()
2150                    && !m.isGeoUri()
2151                    && m.getConversation() instanceof Conversation) {
2152                correctMessage.setVisible(true);
2153                if (!m.getBody().equals("") && !m.getBody().equals(" ")) retractMessage.setVisible(true);
2154            }
2155            if (m.getStatus() == Message.STATUS_WAITING) {
2156                correctMessage.setVisible(true);
2157                retractMessage.setVisible(true);
2158            }
2159            if (conversation.getMode() == Conversation.MODE_MULTI && m.getServerMsgId() != null && m.getModerated() == null && conversation.getMucOptions().getSelf().ranks(Role.MODERATOR) && conversation.getMucOptions().hasFeature("urn:xmpp:message-moderate:0")) {
2160                moderateMessage.setVisible(true);
2161            }
2162            if ((m.isFileOrImage() && !deleted && !receiving)
2163                    || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
2164                            && !unInitiatedButKnownSize
2165                            && t == null) {
2166                shareWith.setVisible(true);
2167            }
2168            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
2169                sendAgain.setVisible(true);
2170                final var httpUploadAvailable =
2171                        connection != null
2172                                && Objects.nonNull(
2173                                        connection
2174                                                .getManager(HttpUploadManager.class)
2175                                                .getService());
2176                final var fileNotUploaded = m.isFileOrImage() && !m.hasFileOnRemoteHost();
2177                final var isPeerOnline =
2178                        conversational.getMode() == Conversation.MODE_SINGLE
2179                                && (conversational instanceof Conversation c)
2180                                && !c.getContact().getPresences().isEmpty();
2181                retryAsP2P.setVisible(fileNotUploaded && isPeerOnline && httpUploadAvailable);
2182            }
2183            if (m.hasFileOnRemoteHost()
2184                    || m.isGeoUri()
2185                    || m.treatAsDownloadable()
2186                    || unInitiatedButKnownSize
2187                    || t instanceof HttpDownloadConnection) {
2188                copyUrl.setVisible(true);
2189            }
2190            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
2191                downloadFile.setVisible(true);
2192                downloadFile.setTitle(
2193                        activity.getString(
2194                                R.string.download_x_file,
2195                                UIHelper.getFileDescriptionString(activity, m)));
2196            }
2197            final boolean waitingOfferedSending =
2198                    m.getStatus() == Message.STATUS_WAITING
2199                            || m.getStatus() == Message.STATUS_UNSEND
2200                            || m.getStatus() == Message.STATUS_OFFERED;
2201            final boolean cancelable =
2202                    (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
2203            if (cancelable) {
2204                cancelTransmission.setVisible(true);
2205            }
2206            if (m.isFileOrImage() && !deleted && !cancelable) {
2207                final String path = m.getRelativeFilePath();
2208                if (path != null) {
2209                    final var file = new File(path);
2210                    if (file.canRead()) saveAsSticker.setVisible(true);
2211                    blockMedia.setVisible(true);
2212                    if (file.canWrite()) deleteFile.setVisible(true);
2213                    deleteFile.setTitle(
2214                            activity.getString(
2215                                    R.string.delete_x_file,
2216                                    UIHelper.getFileDescriptionString(activity, m)));
2217                }
2218            }
2219
2220            if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
2221                // We might be showing a thumbnail worth blocking
2222                blockMedia.setVisible(true);
2223            }
2224            if (showError) {
2225                showErrorMessage.setVisible(true);
2226            }
2227            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
2228            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
2229                    || (mime != null && mime.startsWith("audio/"))) {
2230                openWith.setVisible(true);
2231            }
2232        }
2233    }
2234
2235    @Override
2236    public boolean onContextItemSelected(MenuItem item) {
2237        switch (item.getItemId()) {
2238            case R.id.share_with:
2239                ShareUtil.share(activity, selectedMessage);
2240                return true;
2241            case R.id.correct_message:
2242                correctMessage(selectedMessage);
2243                return true;
2244            case R.id.retract_message:
2245                new AlertDialog.Builder(activity)
2246                    .setTitle(R.string.retract_message)
2247                    .setMessage("Do you really want to retract this message?")
2248                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2249                        final var message = selectedMessage;
2250                        if (message.getStatus() == Message.STATUS_WAITING || message.getStatus() == Message.STATUS_OFFERED) {
2251                            activity.xmppConnectionService.deleteMessage(message);
2252                            return;
2253                        }
2254                        Element reactions = message.getReactionsEl();
2255                        if (reactions != null) {
2256                            final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
2257                            if (previousReaction != null) reactions = previousReaction.getReactionsEl();
2258                            for (Element el : reactions.getChildren()) {
2259                                if (message.getRawBody().endsWith(el.getContent())) {
2260                                    reactions.removeChild(el);
2261                                }
2262                            }
2263                            message.setReactions(reactions);
2264                            if (previousReaction != null) {
2265                                previousReaction.setReactions(reactions);
2266                                activity.xmppConnectionService.updateMessage(previousReaction);
2267                            }
2268                        } else {
2269                            message.setInReplyTo(null);
2270                            message.clearPayloads();
2271                        }
2272                        message.setBody(" ");
2273                        message.setSubject(null);
2274                        message.putEdited(message.getUuid(), message.getServerMsgId());
2275                        message.setServerMsgId(null);
2276                        message.setUuid(UUID.randomUUID().toString());
2277                        sendMessage(message);
2278                    })
2279                    .setNegativeButton(R.string.no, null).show();
2280                return true;
2281            case R.id.moderate_message:
2282                activity.quickEdit("Spam", (reason) -> {
2283                    activity.xmppConnectionService.moderateMessage(conversation.getAccount(), selectedMessage, reason);
2284                    return null;
2285                }, R.string.moderate_reason, false, false, true, true);
2286                return true;
2287            case R.id.copy_message:
2288                ShareUtil.copyToClipboard(activity, selectedMessage);
2289                return true;
2290            case R.id.quote_message:
2291                quoteMessage(selectedMessage);
2292                return true;
2293            case R.id.send_again:
2294                resendMessage(selectedMessage, false);
2295                return true;
2296            case R.id.send_again_as_p2p:
2297                resendMessage(selectedMessage, true);
2298                return true;
2299            case R.id.copy_url:
2300                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
2301                return true;
2302            case R.id.save_as_sticker:
2303                saveAsSticker(selectedMessage);
2304                return true;
2305            case R.id.download_file:
2306                startDownloadable(selectedMessage);
2307                return true;
2308            case R.id.cancel_transmission:
2309                cancelTransmission(selectedMessage);
2310                return true;
2311            case R.id.retry_decryption:
2312                retryDecryption(selectedMessage);
2313                return true;
2314            case R.id.block_media:
2315                new AlertDialog.Builder(activity)
2316                    .setTitle(R.string.block_media)
2317                    .setMessage("Do you really want to block this media in all messages?")
2318                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2319                        List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2320                        if (thumbs != null && !thumbs.isEmpty()) {
2321                            for (Element thumb : thumbs) {
2322                                Uri uri = Uri.parse(thumb.getAttribute("uri"));
2323                                if (uri.getScheme().equals("cid")) {
2324                                    Cid cid = BobTransfer.cid(uri);
2325                                    if (cid == null) continue;
2326                                    DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2327                                    activity.xmppConnectionService.blockMedia(f);
2328                                    activity.xmppConnectionService.evictPreview(f);
2329                                    f.delete();
2330                                }
2331                            }
2332                        }
2333                        File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
2334                        activity.xmppConnectionService.blockMedia(f);
2335                        activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
2336                        activity.xmppConnectionService.evictPreview(f);
2337                        activity.xmppConnectionService.updateMessage(selectedMessage, false);
2338                        activity.onConversationsListItemUpdated();
2339                        refresh();
2340                    })
2341                    .setNegativeButton(R.string.no, null).show();
2342                return true;
2343            case R.id.delete_file:
2344                deleteFile(selectedMessage);
2345                return true;
2346            case R.id.show_error_message:
2347                showErrorMessage(selectedMessage);
2348                return true;
2349            case R.id.open_with:
2350                openWith(selectedMessage);
2351                return true;
2352            case R.id.only_this_thread:
2353                conversation.setLockThread(true);
2354                backPressedLeaveSingleThread.setEnabled(true);
2355                setThread(selectedMessage.getThread());
2356                refresh();
2357                return true;
2358            case R.id.action_report_and_block:
2359                reportMessage(selectedMessage);
2360                return true;
2361            case R.id.action_add_reaction:
2362                addReaction(selectedMessage);
2363                return true;
2364            default:
2365                return onOptionsItemSelected(item);
2366        }
2367    }
2368
2369    @Override
2370    public boolean onOptionsItemSelected(final MenuItem item) {
2371        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
2372            return false;
2373        } else if (conversation == null) {
2374            return super.onOptionsItemSelected(item);
2375        }
2376        if (item.getGroupId() == 0x1) {
2377            conversation.startWebxdc(extensions.get(item.getItemId()));
2378            return true;
2379        }
2380        switch (item.getItemId()) {
2381            case R.id.encryption_choice_axolotl:
2382            case R.id.encryption_choice_pgp:
2383            case R.id.encryption_choice_none:
2384                handleEncryptionSelection(item);
2385                return true;
2386            case R.id.attach_choose_picture:
2387            //case R.id.attach_take_picture:
2388            //case R.id.attach_record_video:
2389            case R.id.attach_choose_file:
2390            case R.id.attach_record_voice:
2391            case R.id.attach_location:
2392                handleAttachmentSelection(item);
2393                return true;
2394            case R.id.attach_webxdc:
2395                final Intent intent = new Intent(getActivity(), WebxdcStore.class);
2396                startActivityForResult(intent, REQUEST_WEBXDC_STORE);
2397                return true;
2398            case R.id.attach_subject:
2399                binding.textinputSubject.setVisibility(binding.textinputSubject.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
2400                return true;
2401            case R.id.attach_schedule:
2402                scheduleMessage();
2403                return true;
2404            case R.id.action_search:
2405                startSearch();
2406                return true;
2407            case R.id.action_archive:
2408                activity.xmppConnectionService.archiveConversation(conversation);
2409                return true;
2410            case R.id.action_contact_details:
2411                activity.switchToContactDetails(conversation.getContact());
2412                return true;
2413            case R.id.action_muc_details:
2414                ConferenceDetailsActivity.open(activity, conversation);
2415                return true;
2416            case R.id.action_invite:
2417                startActivityForResult(
2418                        ChooseContactActivity.create(activity, conversation),
2419                        REQUEST_INVITE_TO_CONVERSATION);
2420                return true;
2421            case R.id.action_clear_history:
2422                clearHistoryDialog(conversation);
2423                return true;
2424            case R.id.action_mute:
2425                muteConversationDialog(conversation);
2426                return true;
2427            case R.id.action_unmute:
2428                unMuteConversation(conversation);
2429                return true;
2430            case R.id.action_block:
2431            case R.id.action_unblock:
2432                BlockContactDialog.show(activity, conversation);
2433                return true;
2434            case R.id.action_audio_call:
2435                checkPermissionAndTriggerAudioCall();
2436                return true;
2437            case R.id.action_video_call:
2438                checkPermissionAndTriggerVideoCall();
2439                return true;
2440            case R.id.action_ongoing_call:
2441                returnToOngoingCall();
2442                return true;
2443            case R.id.action_toggle_pinned:
2444                togglePinned();
2445                return true;
2446            case R.id.action_add_shortcut:
2447                addShortcut();
2448                return true;
2449            case R.id.action_block_avatar:
2450                new AlertDialog.Builder(activity)
2451                    .setTitle(R.string.block_media)
2452                    .setMessage("Do you really want to block this avatar?")
2453                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2454                            activity.xmppConnectionService.blockMedia(activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatar()));
2455                            activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatar()).delete();
2456                            activity.avatarService().clear(conversation);
2457                            conversation.getContact().setAvatar(null);
2458                            activity.xmppConnectionService.updateConversationUi();
2459                    })
2460                    .setNegativeButton(R.string.no, null).show();
2461                return true;
2462            case R.id.action_refresh_feature_discovery:
2463                refreshFeatureDiscovery();
2464                return true;
2465            default:
2466                break;
2467        }
2468        return super.onOptionsItemSelected(item);
2469    }
2470
2471    public boolean onBackPressed() {
2472        boolean wasLocked = conversation.getLockThread();
2473        conversation.setLockThread(false);
2474        backPressedLeaveSingleThread.setEnabled(false);
2475        if (wasLocked) {
2476            setThread(null);
2477            conversation.setUserSelectedThread(false);
2478            refresh();
2479            updateThreadFromLastMessage();
2480            return true;
2481        }
2482        return false;
2483    }
2484
2485    private void startSearch() {
2486        final Intent intent = new Intent(getActivity(), SearchActivity.class);
2487        intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
2488        startActivity(intent);
2489    }
2490
2491    private void scheduleMessage() {
2492        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
2493            final var datePicker = com.google.android.material.datepicker.MaterialDatePicker.Builder.datePicker()
2494                .setTitleText("Schedule Message")
2495                .setSelection(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2496                .setCalendarConstraints(
2497                    new com.google.android.material.datepicker.CalendarConstraints.Builder()
2498                        .setStart(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2499                        .build()
2500                 )
2501                .build();
2502            datePicker.addOnPositiveButtonClickListener((date) -> {
2503                final Calendar now = Calendar.getInstance();
2504                final var timePicker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
2505                    .setTitleText("Schedule Message")
2506                    .setHour(now.get(Calendar.HOUR_OF_DAY))
2507                    .setMinute(now.get(Calendar.MINUTE))
2508                    .setTimeFormat(android.text.format.DateFormat.is24HourFormat(activity) ? com.google.android.material.timepicker.TimeFormat.CLOCK_24H : com.google.android.material.timepicker.TimeFormat.CLOCK_12H)
2509                    .build();
2510                timePicker.addOnPositiveButtonClickListener((v2) -> {
2511                        final var dateCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
2512                        dateCal.setTimeInMillis(date);
2513                        final var time = Calendar.getInstance();
2514                        time.set(dateCal.get(Calendar.YEAR), dateCal.get(Calendar.MONTH), dateCal.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0);
2515                        final long timestamp = time.getTimeInMillis();
2516                        sendMessage(timestamp);
2517                        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": scheduled message for " + timestamp);
2518                    });
2519                timePicker.show(activity.getSupportFragmentManager(), "schedulMessageTime");
2520            });
2521            datePicker.show(activity.getSupportFragmentManager(), "schedulMessageDate");
2522        }
2523    }
2524
2525    private void returnToOngoingCall() {
2526        final Optional<OngoingRtpSession> ongoingRtpSession =
2527                activity.xmppConnectionService
2528                        .getJingleConnectionManager()
2529                        .getOngoingRtpConnection(conversation.getContact());
2530        if (ongoingRtpSession.isPresent()) {
2531            final OngoingRtpSession id = ongoingRtpSession.get();
2532            final Intent intent = new Intent(activity, RtpSessionActivity.class);
2533            intent.setAction(Intent.ACTION_VIEW);
2534            intent.putExtra(
2535                    RtpSessionActivity.EXTRA_ACCOUNT,
2536                    id.getAccount().getJid().asBareJid().toString());
2537            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toString());
2538            if (id instanceof AbstractJingleConnection) {
2539                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2540                activity.startActivity(intent);
2541            } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
2542                if (Media.audioOnly(proposal.media)) {
2543                    intent.putExtra(
2544                            RtpSessionActivity.EXTRA_LAST_ACTION,
2545                            RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2546                } else {
2547                    intent.putExtra(
2548                            RtpSessionActivity.EXTRA_LAST_ACTION,
2549                            RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2550                }
2551                intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
2552                activity.startActivity(intent);
2553            }
2554        }
2555    }
2556
2557    private void refreshFeatureDiscovery() {
2558        final var connection = conversation.getContact().getAccount().getXmppConnection();
2559        if (connection == null) return;
2560
2561        var jids = conversation.getContact().getPresences().getFullJids();
2562        if (jids.isEmpty()) {
2563            jids = new HashSet<>();
2564            jids.add(conversation.getContact().getJid());
2565        }
2566        for (final var jid : jids) {
2567            Futures.addCallback(
2568                connection.getManager(DiscoManager.class).info(Entity.presence(jid), null, null),
2569                new FutureCallback<>() {
2570                    @Override
2571                    public void onSuccess(InfoQuery disco) {
2572                        if (activity == null) return;
2573                        activity.runOnUiThread(() -> {
2574                            refresh();
2575                            refreshCommands(true);
2576                        });
2577                    }
2578
2579                    @Override
2580                    public void onFailure(@NonNull Throwable throwable) {}
2581                },
2582                MoreExecutors.directExecutor()
2583            );
2584        }
2585    }
2586
2587    private void addShortcut() {
2588        ShortcutInfoCompat info;
2589        if (conversation.getMode() == Conversation.MODE_MULTI) {
2590            info = activity.xmppConnectionService.getShortcutService().getShortcutInfo(conversation.getMucOptions());
2591        } else {
2592            info = activity.xmppConnectionService.getShortcutService().getShortcutInfo(conversation.getContact());
2593        }
2594        ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2595    }
2596
2597    private void togglePinned() {
2598        final boolean pinned =
2599                conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2600        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2601        activity.xmppConnectionService.updateConversation(conversation);
2602        activity.invalidateOptionsMenu();
2603    }
2604
2605    private void checkPermissionAndTriggerAudioCall() {
2606        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2607            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2608            return;
2609        }
2610        final List<String> permissions;
2611        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2612            permissions =
2613                    Arrays.asList(
2614                            Manifest.permission.RECORD_AUDIO,
2615                            Manifest.permission.BLUETOOTH_CONNECT);
2616        } else {
2617            permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2618        }
2619        if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2620            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2621        }
2622    }
2623
2624    private void checkPermissionAndTriggerVideoCall() {
2625        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2626            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2627            return;
2628        }
2629        final List<String> permissions;
2630        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2631            permissions =
2632                    Arrays.asList(
2633                            Manifest.permission.RECORD_AUDIO,
2634                            Manifest.permission.CAMERA,
2635                            Manifest.permission.BLUETOOTH_CONNECT);
2636        } else {
2637            permissions =
2638                    Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2639        }
2640        if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2641            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2642        }
2643    }
2644
2645    private void triggerRtpSession(final String action) {
2646        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
2647            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2648                    .show();
2649            return;
2650        }
2651        final Account account = conversation.getAccount();
2652        if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2653            activity.xmppConnectionService.updateAccount(account);
2654        }
2655        final Contact contact = conversation.getContact();
2656        if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
2657            triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2658        } else {
2659            final RtpCapability.Capability capability;
2660            if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2661                capability = RtpCapability.Capability.VIDEO;
2662            } else {
2663                capability = RtpCapability.Capability.AUDIO;
2664            }
2665            PresenceSelector.selectFullJidForDirectRtpConnection(
2666                    activity,
2667                    contact,
2668                    capability,
2669                    fullJid -> {
2670                        triggerRtpSession(contact.getAccount(), fullJid, action);
2671                    });
2672        }
2673    }
2674
2675    private void triggerRtpSession(final Account account, final Jid with, final String action) {
2676        CallIntegrationConnectionService.placeCall(
2677                activity.xmppConnectionService,
2678                account,
2679                with,
2680                RtpSessionActivity.actionToMedia(action));
2681    }
2682
2683    private void handleAttachmentSelection(MenuItem item) {
2684        switch (item.getItemId()) {
2685            case R.id.attach_choose_picture:
2686                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2687                break;
2688            /*case R.id.attach_take_picture:
2689                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2690                break;
2691            case R.id.attach_record_video:
2692                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2693                break;*/
2694            case R.id.attach_choose_file:
2695                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2696                break;
2697            case R.id.attach_record_voice:
2698                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2699                break;
2700            case R.id.attach_location:
2701                attachFile(ATTACHMENT_CHOICE_LOCATION);
2702                break;
2703        }
2704    }
2705
2706    private void handleEncryptionSelection(MenuItem item) {
2707        if (conversation == null) {
2708            return;
2709        }
2710        final boolean updated;
2711        switch (item.getItemId()) {
2712            case R.id.encryption_choice_none:
2713                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2714                item.setChecked(true);
2715                break;
2716            case R.id.encryption_choice_pgp:
2717                if (activity.hasPgp()) {
2718                    if (conversation.getAccount().getPgpSignature() != null) {
2719                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2720                        item.setChecked(true);
2721                    } else {
2722                        updated = false;
2723                        activity.announcePgp(
2724                                conversation.getAccount(),
2725                                conversation,
2726                                null,
2727                                activity.onOpenPGPKeyPublished);
2728                    }
2729                } else {
2730                    activity.showInstallPgpDialog();
2731                    updated = false;
2732                }
2733                break;
2734            case R.id.encryption_choice_axolotl:
2735                Log.d(
2736                        Config.LOGTAG,
2737                        AxolotlService.getLogprefix(conversation.getAccount())
2738                                + "Enabled axolotl for Contact "
2739                                + conversation.getContact().getJid());
2740                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2741                item.setChecked(true);
2742                break;
2743            default:
2744                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2745                break;
2746        }
2747        if (updated) {
2748            activity.xmppConnectionService.updateConversation(conversation);
2749        }
2750        updateChatMsgHint();
2751        getActivity().invalidateOptionsMenu();
2752        activity.refreshUi();
2753    }
2754
2755    public void attachFile(final int attachmentChoice) {
2756        attachFile(attachmentChoice, true, false);
2757    }
2758
2759    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2760        attachFile(attachmentChoice, updateRecentlyUsed, false);
2761    }
2762
2763    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed, final boolean fromPermissions) {
2764        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2765            if (!hasPermissions(
2766                    attachmentChoice,
2767                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2768                    Manifest.permission.RECORD_AUDIO)) {
2769                return;
2770            }
2771        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2772                || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO
2773                || (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE && !fromPermissions)) {
2774            if (!hasPermissions(
2775                    attachmentChoice,
2776                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2777                    Manifest.permission.CAMERA)) {
2778                return;
2779            }
2780        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2781            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2782                return;
2783            }
2784        }
2785        if (updateRecentlyUsed) {
2786            storeRecentlyUsedQuickAction(attachmentChoice);
2787        }
2788        final int encryption = conversation.getNextEncryption();
2789        final int mode = conversation.getMode();
2790        if (encryption == Message.ENCRYPTION_PGP) {
2791            if (activity.hasPgp()) {
2792                if (mode == Conversation.MODE_SINGLE
2793                        && conversation.getContact().getPgpKeyId() != 0) {
2794                    activity.xmppConnectionService
2795                            .getPgpEngine()
2796                            .hasKey(
2797                                    conversation.getContact(),
2798                                    new UiCallback<Contact>() {
2799
2800                                        @Override
2801                                        public void userInputRequired(
2802                                                PendingIntent pi, Contact contact) {
2803                                            startPendingIntent(pi, attachmentChoice);
2804                                        }
2805
2806                                        @Override
2807                                        public void success(Contact contact) {
2808                                            invokeAttachFileIntent(attachmentChoice);
2809                                        }
2810
2811                                        @Override
2812                                        public void error(int error, Contact contact) {
2813                                            activity.replaceToast(getString(error));
2814                                        }
2815                                    });
2816                } else if (mode == Conversation.MODE_MULTI
2817                        && conversation.getMucOptions().pgpKeysInUse()) {
2818                    if (!conversation.getMucOptions().everybodyHasKeys()) {
2819                        Toast warning =
2820                                Toast.makeText(
2821                                        getActivity(),
2822                                        R.string.missing_public_keys,
2823                                        Toast.LENGTH_LONG);
2824                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2825                        warning.show();
2826                    }
2827                    invokeAttachFileIntent(attachmentChoice);
2828                } else {
2829                    showNoPGPKeyDialog(
2830                            false,
2831                            (dialog, which) -> {
2832                                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2833                                activity.xmppConnectionService.updateConversation(conversation);
2834                                invokeAttachFileIntent(attachmentChoice);
2835                            });
2836                }
2837            } else {
2838                activity.showInstallPgpDialog();
2839            }
2840        } else {
2841            invokeAttachFileIntent(attachmentChoice);
2842        }
2843    }
2844
2845    private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2846        try {
2847            activity.getPreferences()
2848                    .edit()
2849                    .putString(
2850                            RECENTLY_USED_QUICK_ACTION,
2851                            SendButtonAction.of(attachmentChoice).toString())
2852                    .apply();
2853        } catch (IllegalArgumentException e) {
2854            // just do not save
2855        }
2856    }
2857
2858    @Override
2859    public void onRequestPermissionsResult(
2860            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2861        final PermissionUtils.PermissionResult permissionResult =
2862                PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2863        if (grantResults.length > 0) {
2864            if (allGranted(permissionResult.grantResults) || requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
2865                switch (requestCode) {
2866                    case REQUEST_START_DOWNLOAD:
2867                        if (this.mPendingDownloadableMessage != null) {
2868                            startDownloadable(this.mPendingDownloadableMessage);
2869                        }
2870                        break;
2871                    case REQUEST_ADD_EDITOR_CONTENT:
2872                        if (this.mPendingEditorContent != null) {
2873                            attachEditorContentToConversation(this.mPendingEditorContent);
2874                        }
2875                        break;
2876                    case REQUEST_COMMIT_ATTACHMENTS:
2877                        commitAttachments();
2878                        break;
2879                    case REQUEST_START_AUDIO_CALL:
2880                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2881                        break;
2882                    case REQUEST_START_VIDEO_CALL:
2883                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2884                        break;
2885                    default:
2886                        attachFile(requestCode, true, true);
2887                        break;
2888                }
2889            } else {
2890                @StringRes int res;
2891                String firstDenied =
2892                        getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2893                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2894                    res = R.string.no_microphone_permission;
2895                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2896                    res = R.string.no_camera_permission;
2897                } else {
2898                    res = R.string.no_storage_permission;
2899                }
2900                Toast.makeText(
2901                                getActivity(),
2902                                getString(res, getString(R.string.app_name)),
2903                                Toast.LENGTH_SHORT)
2904                        .show();
2905            }
2906        }
2907        if (writeGranted(grantResults, permissions)) {
2908            if (activity != null && activity.xmppConnectionService != null) {
2909                activity.xmppConnectionService.getDrawableCache().evictAll();
2910                activity.xmppConnectionService.restartFileObserver();
2911            }
2912            refresh();
2913        }
2914        if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2915            XmppConnectionService.toggleForegroundService(activity);
2916        }
2917    }
2918
2919    public void startDownloadable(Message message) {
2920        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2921            this.mPendingDownloadableMessage = message;
2922            return;
2923        }
2924        Transferable transferable = message.getTransferable();
2925        if (transferable != null) {
2926            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2927                createNewConnection(message);
2928                return;
2929            }
2930            if (!transferable.start()) {
2931                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2932                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2933                        .show();
2934            }
2935        } else if (message.treatAsDownloadable()
2936                || message.hasFileOnRemoteHost()
2937                || MessageUtils.unInitiatedButKnownSize(message)) {
2938            createNewConnection(message);
2939        } else {
2940            Log.d(
2941                    Config.LOGTAG,
2942                    message.getConversation().getAccount() + ": unable to start downloadable");
2943        }
2944    }
2945
2946    private void createNewConnection(final Message message) {
2947        if (!activity.xmppConnectionService.hasInternetConnection()) {
2948            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2949                    .show();
2950            return;
2951        }
2952        if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2953            try {
2954                BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2955                message.setTransferable(transfer);
2956                transfer.start();
2957            } catch (URISyntaxException e) {
2958                Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2959            }
2960        } else {
2961            activity.xmppConnectionService
2962                    .getHttpConnectionManager()
2963                    .createNewDownloadConnection(message, true);
2964        }
2965    }
2966
2967    @SuppressLint("InflateParams")
2968    protected void clearHistoryDialog(final Conversation conversation) {
2969        final MaterialAlertDialogBuilder builder =
2970                new MaterialAlertDialogBuilder(requireActivity());
2971        builder.setTitle(R.string.clear_conversation_history);
2972        final View dialogView =
2973                requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2974        final CheckBox endConversationCheckBox =
2975                dialogView.findViewById(R.id.end_conversation_checkbox);
2976        builder.setView(dialogView);
2977        builder.setNegativeButton(getString(R.string.cancel), null);
2978        builder.setPositiveButton(
2979                getString(R.string.confirm),
2980                (dialog, which) -> {
2981                    this.activity.xmppConnectionService.clearConversationHistory(conversation);
2982                    if (endConversationCheckBox.isChecked()) {
2983                        this.activity.xmppConnectionService.archiveConversation(conversation);
2984                        this.activity.onConversationArchived(conversation);
2985                    } else {
2986                        activity.onConversationsListItemUpdated();
2987                        refresh();
2988                    }
2989                });
2990        builder.create().show();
2991    }
2992
2993    protected void muteConversationDialog(final Conversation conversation) {
2994        final MaterialAlertDialogBuilder builder =
2995                new MaterialAlertDialogBuilder(requireActivity());
2996        builder.setTitle(R.string.disable_notifications);
2997        final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2998        final CharSequence[] labels = new CharSequence[durations.length];
2999        for (int i = 0; i < durations.length; ++i) {
3000            if (durations[i] == -1) {
3001                labels[i] = activity.getString(R.string.until_further_notice);
3002            } else {
3003                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
3004            }
3005        }
3006        builder.setItems(
3007                labels,
3008                (dialog, which) -> {
3009                    final long till;
3010                    if (durations[which] == -1) {
3011                        till = Long.MAX_VALUE;
3012                    } else {
3013                        till = System.currentTimeMillis() + (durations[which] * 1000L);
3014                    }
3015                    conversation.setMutedTill(till);
3016                    activity.xmppConnectionService.updateConversation(conversation);
3017                    activity.onConversationsListItemUpdated();
3018                    refresh();
3019                    activity.invalidateOptionsMenu();
3020                });
3021        builder.create().show();
3022    }
3023
3024    private boolean hasPermissions(int requestCode, List<String> permissions) {
3025        final List<String> missingPermissions = new ArrayList<>();
3026        for (String permission : permissions) {
3027            if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
3028                            || Config.ONLY_INTERNAL_STORAGE)
3029                    && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
3030                continue;
3031            }
3032            if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
3033                missingPermissions.add(permission);
3034            }
3035        }
3036        if (missingPermissions.size() == 0) {
3037            return true;
3038        } else {
3039            requestPermissions(missingPermissions.toArray(new String[0]), requestCode);
3040            return false;
3041        }
3042    }
3043
3044    private boolean hasPermissions(int requestCode, String... permissions) {
3045        return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
3046    }
3047
3048    public void unMuteConversation(final Conversation conversation) {
3049        conversation.setMutedTill(0);
3050        this.activity.xmppConnectionService.updateConversation(conversation);
3051        this.activity.onConversationsListItemUpdated();
3052        refresh();
3053        this.activity.invalidateOptionsMenu();
3054    }
3055
3056    protected void invokeAttachFileIntent(final int attachmentChoice) {
3057        Intent intent = new Intent();
3058
3059        final var takePhotoIntent = new Intent();
3060        final Uri takePhotoUri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
3061        pendingTakePhotoUri.push(takePhotoUri);
3062        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoUri);
3063        takePhotoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
3064        takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
3065        takePhotoIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
3066
3067        final var takeVideoIntent = new Intent();
3068        takeVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
3069
3070        switch (attachmentChoice) {
3071            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
3072                intent.setAction(Intent.ACTION_GET_CONTENT);
3073                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
3074                intent.setType("*/*");
3075                intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});
3076                intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
3077                if (activity.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
3078                    intent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent, takeVideoIntent });
3079                }
3080                break;
3081            case ATTACHMENT_CHOICE_RECORD_VIDEO:
3082                intent = takeVideoIntent;
3083                break;
3084            case ATTACHMENT_CHOICE_TAKE_PHOTO:
3085                intent = takePhotoIntent;
3086                break;
3087            case ATTACHMENT_CHOICE_CHOOSE_FILE:
3088                intent.setAction(Intent.ACTION_GET_CONTENT);
3089                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
3090                intent.setType("*/*");
3091                intent.addCategory(Intent.CATEGORY_OPENABLE);
3092                intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
3093                break;
3094            case ATTACHMENT_CHOICE_RECORD_VOICE:
3095                intent = new Intent(getActivity(), RecordingActivity.class);
3096                break;
3097            case ATTACHMENT_CHOICE_LOCATION:
3098                intent = GeoHelper.getFetchIntent(activity);
3099                break;
3100        }
3101        final Context context = getActivity();
3102        if (context == null) {
3103            return;
3104        }
3105        try {
3106            startActivityForResult(intent, attachmentChoice);
3107        } catch (final ActivityNotFoundException e) {
3108            Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
3109        }
3110    }
3111
3112    @Override
3113    public void onResume() {
3114        super.onResume();
3115        binding.messagesView.post(this::fireReadEvent);
3116    }
3117
3118    private void fireReadEvent() {
3119        if (activity != null && this.conversation != null) {
3120            String uuid = getLastVisibleMessageUuid();
3121            if (uuid != null) {
3122                activity.onConversationRead(this.conversation, uuid);
3123            }
3124        }
3125    }
3126
3127    private void newSubThread() {
3128        Element oldThread = conversation.getThread();
3129        Element thread = new Element("thread", "jabber:client");
3130        thread.setContent(UUID.randomUUID().toString());
3131        if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
3132        setThread(thread);
3133    }
3134
3135    private void newThread() {
3136        Element thread = new Element("thread", "jabber:client");
3137        thread.setContent(UUID.randomUUID().toString());
3138        setThread(thread);
3139    }
3140
3141    private void updateThreadFromLastMessage() {
3142        if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
3143            Message message = getLastVisibleMessage();
3144            if (message == null) {
3145                newThread();
3146            } else {
3147                if (conversation.getMode() == Conversation.MODE_MULTI) {
3148                    if (activity == null || activity.xmppConnectionService == null) return;
3149                    if (message.getStatus() < Message.STATUS_SEND) {
3150                        if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
3151                    }
3152                }
3153
3154                setThread(message.getThread());
3155            }
3156        }
3157    }
3158
3159    private String getLastVisibleMessageUuid() {
3160        Message message =  getLastVisibleMessage();
3161        return message == null ? null : message.getUuid();
3162    }
3163
3164    private Message getLastVisibleMessage() {
3165        if (binding == null) {
3166            return null;
3167        }
3168        synchronized (this.messageList) {
3169            int pos = binding.messagesView.getLastVisiblePosition();
3170            if (pos >= 0) {
3171                Message message = null;
3172                for (int i = pos; i >= 0; --i) {
3173                    try {
3174                        message = (Message) binding.messagesView.getItemAtPosition(i);
3175                    } catch (IndexOutOfBoundsException e) {
3176                        // should not happen if we synchronize properly. however if that fails we
3177                        // just gonna try item -1
3178                        continue;
3179                    }
3180                    if (message.getType() != Message.TYPE_STATUS) {
3181                        break;
3182                    }
3183                }
3184                if (message != null) {
3185                    return message;
3186                }
3187            }
3188        }
3189        return null;
3190    }
3191
3192    private void openWith(final Message message) {
3193        if (message.isGeoUri()) {
3194            GeoHelper.view(getActivity(), message);
3195        } else {
3196            final DownloadableFile file =
3197                    activity.xmppConnectionService.getFileBackend().getFile(message);
3198            final var fp = message.getFileParams();
3199            final var name = fp == null ? null : fp.getName();
3200            final var displayName = name == null ? file.getName() : name;
3201            ViewUtil.view(activity, file, displayName);
3202        }
3203    }
3204
3205    public void addReaction(final Message message) {
3206        activity.addReaction(emoji -> {
3207            setupReply(message);
3208            binding.textinput.setText(emoji.toInsert());
3209            sendMessage();
3210        });
3211    }
3212
3213    private void reportMessage(final Message message) {
3214        BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
3215    }
3216
3217    private void showErrorMessage(final Message message) {
3218        final MaterialAlertDialogBuilder builder =
3219                new MaterialAlertDialogBuilder(requireActivity());
3220        builder.setTitle(R.string.error_message);
3221        final String errorMessage = message.getErrorMessage();
3222        final String[] errorMessageParts =
3223                errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
3224        final String displayError;
3225        if (errorMessageParts.length == 2) {
3226            displayError = errorMessageParts[1];
3227        } else {
3228            displayError = errorMessage;
3229        }
3230        builder.setMessage(displayError);
3231        builder.setNegativeButton(
3232                R.string.copy_to_clipboard,
3233                (dialog, which) -> {
3234                    if (activity.copyTextToClipboard(displayError, R.string.error_message)
3235                            && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
3236                        Toast.makeText(
3237                                        activity,
3238                                        R.string.error_message_copied_to_clipboard,
3239                                        Toast.LENGTH_SHORT)
3240                                .show();
3241                    }
3242                });
3243        builder.setPositiveButton(R.string.confirm, null);
3244        builder.create().show();
3245    }
3246
3247    public boolean onInlineImageLongClicked(Cid cid) {
3248        DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3249        if (f == null) return false;
3250
3251        saveAsSticker(f, null);
3252        return true;
3253    }
3254
3255    private void saveAsSticker(final Message m) {
3256        String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
3257        existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
3258        saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
3259    }
3260
3261    private void saveAsSticker(final File file, final String name) {
3262        savingAsSticker = file;
3263
3264        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
3265        intent.addCategory(Intent.CATEGORY_OPENABLE);
3266        intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file, file.getName())));
3267        intent.putExtra(Intent.EXTRA_TITLE, name);
3268
3269        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3270        final String dir = p.getString("sticker_directory", "Stickers");
3271        if (dir.startsWith("content://")) {
3272            intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
3273        } else {
3274            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
3275            Uri uri;
3276            if (Build.VERSION.SDK_INT >= 29) {
3277                Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
3278                uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
3279                uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
3280            } else {
3281                uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
3282            }
3283            intent.putExtra("android.provider.extra.INITIAL_URI", uri);
3284            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
3285        }
3286
3287        Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
3288        startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
3289    }
3290
3291    private void deleteFile(final Message message) {
3292        final MaterialAlertDialogBuilder builder =
3293                new MaterialAlertDialogBuilder(requireActivity());
3294        builder.setNegativeButton(R.string.cancel, null);
3295        builder.setTitle(R.string.delete_file_dialog);
3296        builder.setMessage(R.string.delete_file_dialog_msg);
3297        builder.setPositiveButton(
3298                R.string.confirm,
3299                (dialog, which) -> {
3300                    List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
3301                    if (thumbs != null && !thumbs.isEmpty()) {
3302                        for (Element thumb : thumbs) {
3303                            Uri uri = Uri.parse(thumb.getAttribute("uri"));
3304                            if (uri.getScheme().equals("cid")) {
3305                                Cid cid = BobTransfer.cid(uri);
3306                                if (cid == null) continue;
3307                                DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3308                                activity.xmppConnectionService.evictPreview(f);
3309                                f.delete();
3310                            }
3311                        }
3312                    }
3313                    if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
3314                        activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
3315                        activity.xmppConnectionService.updateMessage(message, false);
3316                        activity.onConversationsListItemUpdated();
3317                        refresh();
3318                    }
3319                });
3320        builder.create().show();
3321    }
3322
3323    private void resendMessage(final Message message, final boolean forceP2P) {
3324        if (message.isFileOrImage()) {
3325            if (!(message.getConversation() instanceof Conversation conversation)) {
3326                return;
3327            }
3328            final DownloadableFile file =
3329                    activity.xmppConnectionService.getFileBackend().getFile(message);
3330            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
3331                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
3332                if (!message.hasFileOnRemoteHost()
3333                        && xmppConnection != null
3334                        && conversation.getMode() == Conversational.MODE_SINGLE
3335                        && (!xmppConnection
3336                                        .getManager(HttpUploadManager.class)
3337                                        .isAvailableForSize(message.getFileParams().getSize())
3338                                || forceP2P)) {
3339                    activity.selectPresence(
3340                            conversation,
3341                            () -> {
3342                                message.setCounterpart(conversation.getNextCounterpart());
3343                                activity.xmppConnectionService.resendFailedMessages(
3344                                        message, forceP2P);
3345                                new Handler()
3346                                        .post(
3347                                                () -> {
3348                                                    int size = messageList.size();
3349                                                    this.binding.messagesView.setSelection(
3350                                                            size - 1);
3351                                                });
3352                            });
3353                    return;
3354                }
3355            } else if (!Compatibility.hasStoragePermission(getActivity())) {
3356                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
3357                return;
3358            } else {
3359                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
3360                message.setDeleted(true);
3361                activity.xmppConnectionService.updateMessage(message, false);
3362                activity.onConversationsListItemUpdated();
3363                refresh();
3364                return;
3365            }
3366        }
3367        activity.xmppConnectionService.resendFailedMessages(message, false);
3368        new Handler()
3369                .post(
3370                        () -> {
3371                            int size = messageList.size();
3372                            this.binding.messagesView.setSelection(size - 1);
3373                        });
3374    }
3375
3376    private void cancelTransmission(Message message) {
3377        Transferable transferable = message.getTransferable();
3378        if (transferable != null) {
3379            transferable.cancel();
3380        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
3381            activity.xmppConnectionService.markMessage(
3382                    message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
3383        }
3384    }
3385
3386    private void retryDecryption(Message message) {
3387        message.setEncryption(Message.ENCRYPTION_PGP);
3388        activity.onConversationsListItemUpdated();
3389        refresh();
3390        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
3391    }
3392
3393    public void privateMessageWith(final Jid counterpart) {
3394        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3395            activity.xmppConnectionService.sendChatState(conversation);
3396        }
3397        this.binding.textinput.setText("");
3398        this.conversation.setNextCounterpart(counterpart);
3399        updateChatMsgHint();
3400        updateSendButton();
3401        updateEditablity();
3402    }
3403
3404    private void correctMessage(final Message message) {
3405        setThread(message.getThread());
3406        conversation.setUserSelectedThread(true);
3407        this.conversation.setCorrectingMessage(message);
3408        final Editable editable = binding.textinput.getText();
3409        this.conversation.setDraftMessage(editable.toString());
3410        this.binding.textinput.setText("");
3411        this.binding.textinput.append(message.getBody(true));
3412        if (message.getSubject() != null && message.getSubject().length() > 0) {
3413            this.binding.textinputSubject.setText(message.getSubject());
3414            this.binding.textinputSubject.setVisibility(View.VISIBLE);
3415        }
3416        setupReply(message.getInReplyTo());
3417    }
3418
3419    private void highlightInConference(String nick) {
3420        final Editable editable = this.binding.textinput.getText();
3421        String oldString = editable.toString().trim();
3422        final int pos = this.binding.textinput.getSelectionStart();
3423        if (oldString.isEmpty() || pos == 0) {
3424            editable.insert(0, nick + ": ");
3425        } else {
3426            final char before = editable.charAt(pos - 1);
3427            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
3428            if (before == '\n') {
3429                editable.insert(pos, nick + ": ");
3430            } else {
3431                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
3432                    if (NickValidityChecker.check(
3433                            conversation,
3434                            Arrays.asList(
3435                                    editable.subSequence(0, pos - 2).toString().split(", ")))) {
3436                        editable.insert(pos - 2, ", " + nick);
3437                        return;
3438                    }
3439                }
3440                editable.insert(
3441                        pos,
3442                        (Character.isWhitespace(before) ? "" : " ")
3443                                + nick
3444                                + (Character.isWhitespace(after) ? "" : " "));
3445                if (Character.isWhitespace(after)) {
3446                    this.binding.textinput.setSelection(
3447                            this.binding.textinput.getSelectionStart() + 1);
3448                }
3449            }
3450        }
3451    }
3452
3453    @Override
3454    public void startActivityForResult(Intent intent, int requestCode) {
3455        final Activity activity = getActivity();
3456        if (activity instanceof ConversationsActivity) {
3457            ((ConversationsActivity) activity).clearPendingViewIntent();
3458        }
3459        super.startActivityForResult(intent, requestCode);
3460    }
3461
3462    @Override
3463    public void onSaveInstanceState(@NonNull Bundle outState) {
3464        super.onSaveInstanceState(outState);
3465        if (conversation != null) {
3466            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
3467            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
3468            final Uri uri = pendingTakePhotoUri.peek();
3469            if (uri != null) {
3470                outState.putString(STATE_PHOTO_URI, uri.toString());
3471            }
3472            final ScrollState scrollState = getScrollPosition();
3473            if (scrollState != null) {
3474                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
3475            }
3476            final ArrayList<Attachment> attachments =
3477                    mediaPreviewAdapter == null
3478                            ? new ArrayList<>()
3479                            : mediaPreviewAdapter.getAttachments();
3480            if (attachments.size() > 0) {
3481                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public void onActivityCreated(Bundle savedInstanceState) {
3488        super.onActivityCreated(savedInstanceState);
3489        if (savedInstanceState == null) {
3490            return;
3491        }
3492        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
3493        ArrayList<Attachment> attachments =
3494                savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
3495        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
3496        if (uuid != null) {
3497            QuickLoader.set(uuid);
3498            this.pendingConversationsUuid.push(uuid);
3499            if (attachments != null && attachments.size() > 0) {
3500                this.pendingMediaPreviews.push(attachments);
3501            }
3502            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
3503            if (takePhotoUri != null) {
3504                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
3505            }
3506            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
3507        }
3508    }
3509
3510    @Override
3511    public void onStart() {
3512        super.onStart();
3513        if (this.reInitRequiredOnStart && this.conversation != null) {
3514            final Bundle extras = pendingExtras.pop();
3515            reInit(this.conversation, extras != null, extras != null && extras.getString(ConversationsActivity.EXTRA_MESSAGE_UUID) != null);
3516            if (extras != null) {
3517                processExtras(extras);
3518            }
3519        } else if (conversation == null
3520                && activity != null
3521                && activity.xmppConnectionService != null) {
3522            final String uuid = pendingConversationsUuid.pop();
3523            Log.d(
3524                    Config.LOGTAG,
3525                    "ConversationFragment.onStart() - activity was bound but no conversation"
3526                            + " loaded. uuid="
3527                            + uuid);
3528            if (uuid != null) {
3529                findAndReInitByUuidOrArchive(uuid);
3530            }
3531        }
3532    }
3533
3534    @Override
3535    public void onStop() {
3536        super.onStop();
3537        final Activity activity = getActivity();
3538        messageListAdapter.unregisterListenerInAudioPlayer();
3539        if (activity == null || !activity.isChangingConfigurations()) {
3540            hideSoftKeyboard(activity);
3541            messageListAdapter.stopAudioPlayer();
3542        }
3543        if (this.conversation != null) {
3544            final String msg = this.binding.textinput.getText().toString();
3545            storeNextMessage(msg);
3546            updateChatState(this.conversation, msg);
3547            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
3548        }
3549        this.reInitRequiredOnStart = true;
3550    }
3551
3552    private void updateChatState(final Conversation conversation, final String msg) {
3553        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
3554        Account.State status = conversation.getAccount().getStatus();
3555        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
3556            activity.xmppConnectionService.sendChatState(conversation);
3557        }
3558    }
3559
3560    private void saveMessageDraftStopAudioPlayer() {
3561        final Conversation previousConversation = this.conversation;
3562        if (this.activity == null || this.binding == null || previousConversation == null) {
3563            return;
3564        }
3565        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
3566        final String msg = this.binding.textinput.getText().toString();
3567        storeNextMessage(msg);
3568        updateChatState(this.conversation, msg);
3569        messageListAdapter.stopAudioPlayer();
3570        mediaPreviewAdapter.clearPreviews();
3571        toggleInputMethod();
3572    }
3573
3574    public void reInit(final Conversation conversation, final Bundle extras) {
3575        QuickLoader.set(conversation.getUuid());
3576        final boolean changedConversation = this.conversation != conversation;
3577        if (changedConversation) {
3578            this.saveMessageDraftStopAudioPlayer();
3579        }
3580        this.clearPending();
3581        if (this.reInit(conversation, extras != null, extras != null && extras.getString(ConversationsActivity.EXTRA_MESSAGE_UUID) != null)) {
3582            if (extras != null) {
3583                processExtras(extras);
3584            }
3585            this.reInitRequiredOnStart = false;
3586        } else {
3587            this.reInitRequiredOnStart = true;
3588            pendingExtras.push(extras);
3589        }
3590        resetUnreadMessagesCount();
3591    }
3592
3593    private void reInit(Conversation conversation) {
3594        reInit(conversation, false, false);
3595        if (activity != null) {
3596            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
3597        }
3598    }
3599
3600    private boolean reInit(final Conversation conversation, final boolean hasExtras, final boolean hasMessageUUID) {
3601        if (conversation == null) {
3602            return false;
3603        }
3604        final Conversation originalConversation = this.conversation;
3605        this.conversation = conversation;
3606        // once we set the conversation all is good and it will automatically do the right thing in
3607        // onStart()
3608        if (this.activity == null || this.binding == null) {
3609            return false;
3610        }
3611
3612        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3613            activity.onConversationArchived(this.conversation);
3614            return false;
3615        }
3616
3617        final var cursord = activity.getDrawable(R.drawable.cursor_on_tertiary_container);
3618        if (activity.xmppConnectionService != null && activity.xmppConnectionService.getAccounts().size() > 1) {
3619            final var bg = MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorSurface);
3620            final var accountColor = conversation.getAccount().getColor(activity.isDark());
3621            final var colors = MaterialColors.getColorRoles(activity, accountColor);
3622            final var accent = activity.isDark() ? ColorUtils.blendARGB(colors.getAccentContainer(), bg, 1.0f - Math.max(0.25f, Color.alpha(accountColor) / 255.0f)) : colors.getAccentContainer();
3623            cursord.setTintList(ColorStateList.valueOf(colors.getOnAccentContainer()));
3624            binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(accent));
3625            binding.textinputSubject.setTextColor(colors.getOnAccentContainer());
3626            binding.textinput.setTextColor(colors.getOnAccentContainer());
3627            binding.textinputSubject.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3628            binding.textinput.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3629            binding.textInputHint.setTextColor(colors.getOnAccentContainer());
3630        } else {
3631            cursord.setTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer)));
3632            binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.inputLayout, com.google.android.material.R.attr.colorTertiaryContainer)));
3633            binding.textinputSubject.setTextColor(MaterialColors.getColor(binding.textinputSubject, com.google.android.material.R.attr.colorOnTertiaryContainer));
3634            binding.textinput.setTextColor(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer));
3635            binding.textinputSubject.setHintTextColor(R.color.hint_on_tertiary_container);
3636            binding.textinput.setHintTextColor(R.color.hint_on_tertiary_container);
3637            binding.textInputHint.setTextColor(MaterialColors.getColor(binding.textInputHint, com.google.android.material.R.attr.colorOnTertiaryContainer));
3638        }
3639        if (Build.VERSION.SDK_INT >= 29) {
3640            binding.textinputSubject.setTextCursorDrawable(cursord);
3641            binding.textinput.setTextCursorDrawable(cursord);
3642        }
3643
3644        setThread(conversation.getThread());
3645        setupReply(conversation.getReplyTo());
3646
3647        stopScrolling();
3648        Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3649
3650        if (this.conversation.isRead(activity == null ? null : activity.xmppConnectionService) && hasExtras) {
3651            Log.d(Config.LOGTAG, "trimming conversation");
3652            this.conversation.trim();
3653        }
3654
3655        setupIme();
3656
3657        final boolean scrolledToBottomAndNoPending =
3658                this.scrolledToBottom() && pendingScrollState.peek() == null;
3659
3660        this.binding.textSendButton.setContentDescription(
3661                activity.getString(R.string.send_message_to_x, conversation.getName()));
3662        this.binding.textinput.setKeyboardListener(null);
3663        this.binding.textinputSubject.setKeyboardListener(null);
3664        final boolean participating =
3665                conversation.getMode() == Conversational.MODE_SINGLE
3666                        || conversation.getMucOptions().participating();
3667        if (participating) {
3668            this.binding.textinput.setText(this.conversation.getNextMessage());
3669            this.binding.textinput.setSelection(this.binding.textinput.length());
3670        } else {
3671            this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3672        }
3673        this.binding.textinput.setKeyboardListener(this);
3674        this.binding.textinputSubject.setKeyboardListener(this);
3675        messageListAdapter.updatePreferences();
3676        refresh(false);
3677        activity.invalidateOptionsMenu();
3678        this.conversation.messagesLoaded.set(true);
3679        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3680
3681        if (!hasMessageUUID && (hasExtras || scrolledToBottomAndNoPending)) {
3682            resetUnreadMessagesCount();
3683            synchronized (this.messageList) {
3684                Log.d(Config.LOGTAG, "jump to first unread message");
3685                final Message first = conversation.getFirstUnreadMessage();
3686                final int bottom = Math.max(0, this.messageList.size() - 1);
3687                final int pos;
3688                final boolean jumpToBottom;
3689                if (first == null) {
3690                    pos = bottom;
3691                    jumpToBottom = true;
3692                } else {
3693                    int i = getIndexOf(first.getUuid(), this.messageList);
3694                    pos = i < 0 ? bottom : i;
3695                    jumpToBottom = false;
3696                }
3697                setSelection(pos, jumpToBottom);
3698            }
3699        }
3700
3701        this.binding.messagesView.post(this::fireReadEvent);
3702        // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3703        // layout which might be unnecessary since we can *see* it
3704        activity.xmppConnectionService
3705                .getNotificationService()
3706                .setOpenConversation(this.conversation);
3707
3708        if (commandAdapter != null && conversation != originalConversation) {
3709            commandAdapter.clear();
3710            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3711            refreshCommands(false);
3712        }
3713        if (commandAdapter == null && conversation != null) {
3714            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3715            commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3716            binding.commandsView.setAdapter(commandAdapter);
3717            binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3718                if (activity == null) return;
3719
3720                commandAdapter.getItem(position).start(activity, ConversationFragment.this.conversation);
3721            });
3722            refreshCommands(false);
3723        }
3724        binding.commandsNote.setVisibility(activity.xmppConnectionService.isOnboarding() ? View.VISIBLE : View.GONE);
3725        replyJumps.clear();
3726        return true;
3727    }
3728
3729    @Override
3730    public void refreshForNewCaps(final Set<Jid> newCapsJids) {
3731        if (newCapsJids.isEmpty() || (conversation != null && newCapsJids.contains(conversation.getJid().asBareJid()))) {
3732            refreshCommands(true);
3733        }
3734    }
3735
3736    protected void refreshCommands(boolean delayShow) {
3737        if (commandAdapter == null) return;
3738
3739        final CommandAdapter.MucConfig mucConfig =
3740            conversation.getMucOptions().getSelf().ranks(Affiliation.OWNER) ?
3741            new CommandAdapter.MucConfig() :
3742            null;
3743
3744        Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3745        if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3746            commandJid = conversation.getJid().asBareJid();
3747        }
3748        if (commandJid == null && conversation.getJid().isDomainJid()) {
3749            commandJid = conversation.getJid();
3750        }
3751        if (commandJid == null) {
3752            binding.commandsViewProgressbar.setVisibility(View.GONE);
3753            if (mucConfig == null) {
3754                conversation.hideViewPager();
3755            } else {
3756                commandAdapter.clear();
3757                commandAdapter.add(mucConfig);
3758                conversation.showViewPager();
3759            }
3760        } else {
3761            if (!delayShow) conversation.showViewPager();
3762            binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3763            final var discoManager = conversation.getAccount().getXmppConnection().getManager(DiscoManager.class);
3764            final var future = discoManager.items(Entity.discoItem(commandJid), Namespace.COMMANDS);
3765            Futures.addCallback(
3766                    future,
3767                    new FutureCallback<>() {
3768                        @Override
3769                        public void onSuccess(Collection<Item> result) {
3770                            if (activity == null) return;
3771
3772                            activity.runOnUiThread(() -> {
3773                                binding.commandsViewProgressbar.setVisibility(View.GONE);
3774                                commandAdapter.clear();
3775                                for (final var command : result) {
3776                                    commandAdapter.add(new CommandAdapter.Command0050(command));
3777                                }
3778
3779                                if (mucConfig != null) commandAdapter.add(mucConfig);
3780
3781                                if (commandAdapter.getCount() < 1) {
3782                                    conversation.hideViewPager();
3783                                } else if (delayShow) {
3784                                    conversation.showViewPager();
3785                                }
3786                            });
3787
3788                        }
3789
3790                        @Override
3791                        public void onFailure(@NonNull Throwable throwable) {
3792                            Log.d(Config.LOGTAG, "Failed to get commands: " + throwable);
3793
3794                            if (activity == null) return;
3795
3796                            activity.runOnUiThread(() -> {
3797                                binding.commandsViewProgressbar.setVisibility(View.GONE);
3798                                commandAdapter.clear();
3799
3800                                if (mucConfig != null) commandAdapter.add(mucConfig);
3801
3802                                if (commandAdapter.getCount() < 1) {
3803                                    conversation.hideViewPager();
3804                                } else if (delayShow) {
3805                                    conversation.showViewPager();
3806                                }
3807                            });
3808                        }
3809                    },
3810                    MoreExecutors.directExecutor()
3811            );
3812        }
3813    }
3814
3815    private void resetUnreadMessagesCount() {
3816        lastMessageUuid = null;
3817        hideUnreadMessagesCount();
3818    }
3819
3820    private void hideUnreadMessagesCount() {
3821        if (this.binding == null) {
3822            return;
3823        }
3824        this.binding.scrollToBottomButton.setEnabled(false);
3825        this.binding.scrollToBottomButton.hide();
3826        replyJumps.clear();
3827        this.binding.unreadCountCustomView.setVisibility(View.GONE);
3828    }
3829
3830    private void setSelection(int pos, boolean jumpToBottom) {
3831        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3832        this.binding.messagesView.post(
3833                () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3834        this.binding.messagesView.post(this::fireReadEvent);
3835    }
3836
3837    private boolean scrolledToBottom() {
3838        return !conversation.isInHistoryPart() && this.binding != null && scrolledToBottom(this.binding.messagesView);
3839    }
3840
3841    private void processExtras(final Bundle extras) {
3842        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3843        final String text = extras.getString(Intent.EXTRA_TEXT);
3844        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3845        final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3846        final String postInitAction =
3847                extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3848        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3849        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3850        final boolean doNotAppend =
3851                extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3852        final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3853
3854        final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3855        if (thread != null) {
3856            conversation.setLockThread(true);
3857            backPressedLeaveSingleThread.setEnabled(true);
3858            setThread(new Element("thread").setContent(thread));
3859            refresh();
3860        }
3861
3862        final List<Uri> uris = extractUris(extras);
3863        if (uris != null && uris.size() > 0) {
3864            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3865                mediaPreviewAdapter.addMediaPreviews(
3866                        Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3867            } else {
3868                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3869                mediaPreviewAdapter.addMediaPreviews(
3870                        Attachment.of(getActivity(), cleanedUris, type));
3871            }
3872            toggleInputMethod();
3873            return;
3874        }
3875        if (nick != null) {
3876            if (pm) {
3877                Jid jid = conversation.getJid();
3878                try {
3879                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3880                    privateMessageWith(next);
3881                } catch (final IllegalArgumentException ignored) {
3882                    // do nothing
3883                }
3884            } else {
3885                final MucOptions mucOptions = conversation.getMucOptions();
3886                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3887                    highlightInConference(nick);
3888                }
3889            }
3890        } else {
3891            if (text != null && Patterns.URI_GEO.matcher(text).matches()) {
3892                mediaPreviewAdapter.addMediaPreviews(
3893                        Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3894                toggleInputMethod();
3895                return;
3896            } else if (text != null && asQuote) {
3897                quoteText(text);
3898            } else {
3899                appendText(text, doNotAppend);
3900            }
3901        }
3902        if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3903            attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3904            return;
3905        }
3906        if ("call".equals(postInitAction)) {
3907            checkPermissionAndTriggerAudioCall();
3908        }
3909        if ("message".equals(postInitAction)) {
3910            binding.conversationViewPager.post(() -> {
3911                binding.conversationViewPager.setCurrentItem(0);
3912            });
3913        }
3914        if ("command".equals(postInitAction)) {
3915            binding.conversationViewPager.post(() -> {
3916                PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3917                if (adapter != null && adapter.getCount() > 1) {
3918                    binding.conversationViewPager.setCurrentItem(1);
3919                }
3920                final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3921                Jid commandJid = null;
3922                if (jid != null) {
3923                    try {
3924                        commandJid = Jid.of(jid);
3925                    } catch (final IllegalArgumentException e) { }
3926                }
3927                if (commandJid == null || !commandJid.isFullJid()) {
3928                    final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3929                    if (discoJid != null) commandJid = discoJid;
3930                }
3931                if (node != null && commandJid != null && activity != null) {
3932                    conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3933                }
3934            });
3935            return;
3936        }
3937        Message message =
3938                downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3939        if ("webxdc".equals(postInitAction)) {
3940            if (message == null) {
3941                message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3942            }
3943            if (message == null) return;
3944
3945            Cid webxdcCid = message.getFileParams().getCids().get(0);
3946            WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message);
3947            Conversation conversation = (Conversation) message.getConversation();
3948            if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3949                conversation.startWebxdc(webxdc);
3950            }
3951        }
3952        if (message != null) {
3953            startDownloadable(message);
3954        }
3955        if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3956            if (!conversation.switchToSession("jabber:iq:register")) {
3957                conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3958            }
3959        }
3960        String messageUuid = extras.getString(ConversationsActivity.EXTRA_MESSAGE_UUID);
3961        if (messageUuid != null) {
3962            Runnable postSelectionRunnable = () -> highlightMessage(messageUuid);
3963            updateSelection(messageUuid, binding.messagesView.getHeight() / 2, postSelectionRunnable, false, false);
3964        }
3965    }
3966
3967    private Element commandFor(final Jid jid, final String node) {
3968        if (commandAdapter != null) {
3969            for (int i = 0; i < commandAdapter.getCount(); i++) {
3970                final CommandAdapter.Command c = commandAdapter.getItem(i);
3971                if (!(c instanceof CommandAdapter.Command0050)) continue;
3972
3973                final Element command = ((CommandAdapter.Command0050) c).el;
3974                final String commandNode = command.getAttribute("node");
3975                if (commandNode == null || !commandNode.equals(node)) continue;
3976
3977                final Jid commandJid = command.getAttributeAsJid("jid");
3978                if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3979
3980                return command;
3981            }
3982        }
3983
3984        return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3985    }
3986
3987    private List<Uri> extractUris(final Bundle extras) {
3988        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3989        if (uris != null) {
3990            return uris;
3991        }
3992        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3993        if (uri != null) {
3994            return Collections.singletonList(uri);
3995        } else {
3996            return null;
3997        }
3998    }
3999
4000    private List<Uri> cleanUris(final List<Uri> uris) {
4001        final Iterator<Uri> iterator = uris.iterator();
4002        while (iterator.hasNext()) {
4003            final Uri uri = iterator.next();
4004            if (FileBackend.dangerousFile(uri)) {
4005                iterator.remove();
4006                Toast.makeText(
4007                                requireActivity(),
4008                                R.string.security_violation_not_attaching_file,
4009                                Toast.LENGTH_SHORT)
4010                        .show();
4011            }
4012        }
4013        return uris;
4014    }
4015
4016    private boolean showBlockSubmenu(View view) {
4017        final Jid jid = conversation.getJid();
4018        final int mode = conversation.getMode();
4019        final var contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
4020        final boolean showReject = contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
4021        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
4022        popupMenu.inflate(R.menu.block);
4023        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
4024        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
4025        popupMenu.getMenu().findItem(R.id.add_contact).setVisible(!contact.showInRoster());
4026        popupMenu.setOnMenuItemClickListener(
4027                menuItem -> {
4028                    Blockable blockable;
4029                    switch (menuItem.getItemId()) {
4030                        case R.id.reject:
4031                            activity.xmppConnectionService.stopPresenceUpdatesTo(
4032                                    conversation.getContact());
4033                            updateSnackBar(conversation);
4034                            return true;
4035                        case R.id.add_contact:
4036                            mAddBackClickListener.onClick(view);
4037                            return true;
4038                        // case R.id.block_domain:
4039                        //     blockable =
4040                        //             conversation
4041                        //                     .getAccount()
4042                        //                     .getRoster()
4043                        //                     .getContact(jid.getDomain());
4044                        //     break;
4045                        default:
4046                            blockable = conversation;
4047                    }
4048                    BlockContactDialog.show(activity, blockable);
4049                    return true;
4050                });
4051        popupMenu.show();
4052        return true;
4053    }
4054
4055    private boolean showBlockMucSubmenu(View view) {
4056        final var jid = conversation.getJid();
4057        final var popupMenu = new PopupMenu(getActivity(), view);
4058        popupMenu.inflate(R.menu.block_muc);
4059        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
4060        popupMenu.setOnMenuItemClickListener(
4061                menuItem -> {
4062                    Blockable blockable;
4063                    switch (menuItem.getItemId()) {
4064                        case R.id.reject:
4065                            activity.xmppConnectionService.clearConversationHistory(conversation);
4066                            activity.xmppConnectionService.archiveConversation(conversation);
4067                            return true;
4068                        case R.id.add_bookmark:
4069                            conversation.getAccount().getXmppConnection().getManager(BookmarkManager.class).save(conversation, "");
4070                            updateSnackBar(conversation);
4071                            return true;
4072                        case R.id.block_contact:
4073                            blockable =
4074                                    conversation
4075                                            .getAccount()
4076                                            .getRoster()
4077                                            .getContact(Jid.of(conversation.getAttribute("inviter")));
4078                            break;
4079                        default:
4080                            blockable = conversation;
4081                    }
4082                    BlockContactDialog.show(activity, blockable);
4083                    activity.xmppConnectionService.archiveConversation(conversation);
4084                    return true;
4085                });
4086        popupMenu.show();
4087        return true;
4088    }
4089
4090    private void updateSnackBar(final Conversation conversation) {
4091        final Account account = conversation.getAccount();
4092        final XmppConnection connection = account.getXmppConnection();
4093        final int mode = conversation.getMode();
4094        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
4095        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
4096            return;
4097        }
4098        if (account.getStatus() == Account.State.DISABLED) {
4099            showSnackbar(
4100                    R.string.this_account_is_disabled,
4101                    R.string.enable,
4102                    this.mEnableAccountListener);
4103        } else if (account.getStatus() == Account.State.LOGGED_OUT) {
4104            showSnackbar(
4105                    R.string.this_account_is_logged_out,
4106                    R.string.log_in,
4107                    this.mEnableAccountListener);
4108        } else if (conversation.isBlocked()) {
4109            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
4110        } else if (account.getStatus() == Account.State.CONNECTING) {
4111            showSnackbar(R.string.this_account_is_connecting, 0, null);
4112        } else if (account.getStatus() != Account.State.ONLINE) {
4113            showSnackbar(R.string.this_account_is_offline, 0, null);
4114        } else if (contact != null
4115                && !contact.showInRoster()
4116                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
4117            showSnackbar(
4118                    R.string.contact_added_you,
4119                    R.string.options,
4120                    this.mBlockClickListener,
4121                    this.mLongPressBlockListener);
4122        } else if (contact != null
4123                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
4124            showSnackbar(
4125                    R.string.contact_asks_for_presence_subscription,
4126                    R.string.allow,
4127                    this.mAllowPresenceSubscription,
4128                    this.mLongPressBlockListener);
4129        } else if (mode == Conversation.MODE_MULTI
4130                && !conversation.getMucOptions().online()
4131                && account.getStatus() == Account.State.ONLINE) {
4132            switch (conversation.getMucOptions().getError()) {
4133                case NICK_IN_USE:
4134                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
4135                    break;
4136                case NO_RESPONSE:
4137                    showSnackbar(R.string.joining_conference, 0, null);
4138                    break;
4139                case SERVER_NOT_FOUND:
4140                    if (conversation.receivedMessagesCount() > 0) {
4141                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
4142                    } else {
4143                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
4144                    }
4145                    break;
4146                case REMOTE_SERVER_TIMEOUT:
4147                    if (conversation.receivedMessagesCount() > 0) {
4148                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
4149                    } else {
4150                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
4151                    }
4152                    break;
4153                case PASSWORD_REQUIRED:
4154                    showSnackbar(
4155                            R.string.conference_requires_password,
4156                            R.string.enter_password,
4157                            enterPassword);
4158                    break;
4159                case BANNED:
4160                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
4161                    break;
4162                case MEMBERS_ONLY:
4163                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
4164                    break;
4165                case RESOURCE_CONSTRAINT:
4166                    showSnackbar(
4167                            R.string.conference_resource_constraint, R.string.try_again, joinMuc);
4168                    break;
4169                case KICKED:
4170                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
4171                    break;
4172                case TECHNICAL_PROBLEMS:
4173                    showSnackbar(
4174                            R.string.conference_technical_problems, R.string.try_again, joinMuc);
4175                    break;
4176                case UNKNOWN:
4177                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
4178                    break;
4179                case INVALID_NICK:
4180                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
4181                case SHUTDOWN:
4182                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
4183                    break;
4184                case DESTROYED:
4185                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
4186                    break;
4187                case NON_ANONYMOUS:
4188                    showSnackbar(
4189                            R.string.group_chat_will_make_your_jabber_id_public,
4190                            R.string.join,
4191                            acceptJoin);
4192                    break;
4193                default:
4194                    hideSnackbar();
4195                    break;
4196            }
4197        } else if (account.hasPendingPgpIntent(conversation)) {
4198            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
4199        } else if (connection != null
4200                && connection.getFeatures().blocking()
4201                && conversation.strangerInvited()) {
4202            showSnackbar(
4203                    R.string.received_invite_from_stranger,
4204                    R.string.options,
4205                    (v) -> showBlockMucSubmenu(v),
4206                    (v) -> showBlockMucSubmenu(v));
4207        } else if (connection != null
4208                && connection.getFeatures().blocking()
4209                && conversation.countMessages() != 0
4210                && !conversation.isBlocked()
4211                && conversation.isWithStranger()) {
4212            showSnackbar(
4213                    R.string.received_message_from_stranger,
4214                    R.string.options,
4215                    this.mBlockClickListener,
4216                    this.mLongPressBlockListener);
4217        } else {
4218            hideSnackbar();
4219        }
4220    }
4221
4222    @Override
4223    public void refresh() {
4224        if (this.binding == null) {
4225            Log.d(
4226                    Config.LOGTAG,
4227                    "ConversationFragment.refresh() skipped updated because view binding was null");
4228            return;
4229        }
4230        if (this.conversation != null
4231                && this.activity != null
4232                && this.activity.xmppConnectionService != null) {
4233            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
4234                activity.onConversationArchived(this.conversation);
4235                return;
4236            }
4237        }
4238        this.refresh(true);
4239    }
4240
4241    private void refresh(boolean notifyConversationRead) {
4242        synchronized (this.messageList) {
4243            if (this.conversation != null) {
4244                if (messageListAdapter.hasSelection()) {
4245                    if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
4246                } else {
4247                    conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
4248                    try {
4249                        updateStatusMessages();
4250                    } catch (IllegalStateException e) {
4251                        Log.e(Config.LOGTAG, "Problem updating status messages on refresh: " + e);
4252                    }
4253                    this.messageListAdapter.notifyDataSetChanged();
4254                }
4255                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
4256                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
4257                    binding.unreadCountCustomView.setUnreadCount(
4258                            conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
4259                }
4260                updateSnackBar(conversation);
4261                if (activity != null) updateChatMsgHint();
4262                if (notifyConversationRead && activity != null) {
4263                    binding.messagesView.post(this::fireReadEvent);
4264                }
4265                updateSendButton();
4266                updateEditablity();
4267                conversation.refreshSessions();
4268            }
4269        }
4270    }
4271
4272    protected void messageSent() {
4273        binding.textinputSubject.setText("");
4274        binding.textinputSubject.setVisibility(View.GONE);
4275        setThread(null);
4276        setupReply(null);
4277        conversation.setUserSelectedThread(false);
4278        mSendingPgpMessage.set(false);
4279        this.binding.textinput.setText("");
4280        if (conversation.setCorrectingMessage(null)) {
4281            this.binding.textinput.append(conversation.getDraftMessage());
4282            conversation.setDraftMessage(null);
4283        }
4284        storeNextMessage();
4285        updateChatMsgHint();
4286        if (activity == null) return;
4287        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
4288        final boolean prefScrollToBottom =
4289                p.getBoolean(
4290                        "scroll_to_bottom",
4291                        activity.getResources().getBoolean(R.bool.scroll_to_bottom));
4292        if (prefScrollToBottom || scrolledToBottom()) {
4293            new Handler()
4294                    .post(
4295                            () -> {
4296                                int size = messageList.size();
4297                                this.binding.messagesView.setSelection(size - 1);
4298                            });
4299        }
4300    }
4301
4302    private boolean storeNextMessage() {
4303        return storeNextMessage(this.binding.textinput.getText().toString());
4304    }
4305
4306    private boolean storeNextMessage(String msg) {
4307        final boolean participating =
4308                conversation.getMode() == Conversational.MODE_SINGLE
4309                        || conversation.getMucOptions().participating();
4310        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
4311                && participating
4312                && this.conversation.setNextMessage(msg) && activity != null) {
4313            activity.xmppConnectionService.updateConversation(this.conversation);
4314            return true;
4315        }
4316        return false;
4317    }
4318
4319    public void doneSendingPgpMessage() {
4320        mSendingPgpMessage.set(false);
4321    }
4322
4323    public Long getMaxHttpUploadSize(final Conversation conversation) {
4324
4325        final var connection = conversation.getAccount().getXmppConnection();
4326        final var httpUploadService = connection.getManager(HttpUploadManager.class).getService();
4327        if (httpUploadService == null) {
4328            return -1L;
4329        }
4330        return httpUploadService.getMaxFileSize();
4331    }
4332
4333    private boolean canWrite() {
4334        return
4335                this.conversation.getMode() == Conversation.MODE_SINGLE
4336                        || this.conversation.getMucOptions().participating()
4337                        || this.conversation.getNextCounterpart() != null;
4338    }
4339
4340    private void updateEditablity() {
4341        boolean canWrite = canWrite();
4342        this.binding.textinput.setFocusable(canWrite);
4343        this.binding.textinput.setFocusableInTouchMode(canWrite);
4344        this.binding.textSendButton.setEnabled(canWrite);
4345        this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
4346        this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
4347        this.binding.textinput.setCursorVisible(canWrite);
4348        this.binding.textinput.setEnabled(canWrite);
4349    }
4350
4351    public void updateSendButton() {
4352        boolean hasAttachments =
4353                mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
4354        final Conversation c = this.conversation;
4355        final Presence.Availability status;
4356        final String text =
4357                this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
4358        final SendButtonAction action;
4359        if (hasAttachments) {
4360            action = SendButtonAction.TEXT;
4361        } else {
4362            action = SendButtonTool.getAction(getActivity(), c, text, binding.textinputSubject.getText().toString());
4363        }
4364        if (c.getAccount().getStatus() == Account.State.ONLINE) {
4365            if (activity != null
4366                    && activity.xmppConnectionService != null
4367                    && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
4368                status = Presence.Availability.OFFLINE;
4369            } else if (c.getMode() == Conversation.MODE_SINGLE) {
4370                status = c.getContact().getShownStatus();
4371            } else {
4372                status =
4373                        c.getMucOptions().online()
4374                                ? Presence.Availability.ONLINE
4375                                : Presence.Availability.OFFLINE;
4376            }
4377        } else {
4378            status = Presence.Availability.OFFLINE;
4379        }
4380        this.binding.textSendButton.setTag(action);
4381        this.binding.textSendButton.setIconTint(ColorStateList.valueOf(SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
4382        // TODO send button color
4383        final Activity activity = getActivity();
4384        if (activity != null) {
4385            this.binding.textSendButton.setIconResource(
4386                    SendButtonTool.getSendButtonImageResource(action, text.length() > 0 || hasAttachments || (c.getThread() != null && binding.textinputSubject.getText().length() > 0)));
4387        }
4388
4389        ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
4390        if (identiconWidth < 0) identiconWidth = params.width;
4391        if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
4392            binding.conversationViewPager.setCurrentItem(0);
4393            params.width = conversation.getThread() == null ? 0 : identiconWidth;
4394        } else {
4395            params.width = identiconWidth;
4396        }
4397        if (!canWrite()) params.width = 0;
4398        binding.threadIdenticonLayout.setLayoutParams(params);
4399    }
4400
4401    protected void updateStatusMessages() {
4402        DateSeparator.addAll(this.messageList);
4403        if (showLoadMoreMessages(conversation)) {
4404            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
4405        }
4406        if (conversation.getMode() == Conversation.MODE_SINGLE) {
4407            ChatState state = conversation.getIncomingChatState();
4408            if (state == ChatState.COMPOSING) {
4409                this.messageList.add(
4410                        Message.createStatusMessage(
4411                                conversation,
4412                                getString(R.string.contact_is_typing, conversation.getName())));
4413            } else if (state == ChatState.PAUSED) {
4414                this.messageList.add(
4415                        Message.createStatusMessage(
4416                                conversation,
4417                                getString(
4418                                        R.string.contact_has_stopped_typing,
4419                                        conversation.getName())));
4420            } else {
4421                for (int i = this.messageList.size() - 1; i >= 0; --i) {
4422                    final Message message = this.messageList.get(i);
4423                    if (message.getType() != Message.TYPE_STATUS) {
4424                        if (message.getStatus() == Message.STATUS_RECEIVED) {
4425                            return;
4426                        } else {
4427                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
4428                                this.messageList.add(
4429                                        i + 1,
4430                                        Message.createStatusMessage(
4431                                                conversation,
4432                                                getString(
4433                                                        R.string.contact_has_read_up_to_this_point,
4434                                                        conversation.getName())));
4435                                return;
4436                            }
4437                        }
4438                    }
4439                }
4440            }
4441        } else {
4442            final MucOptions mucOptions = conversation.getMucOptions();
4443            final List<MucOptions.User> allUsers = mucOptions.getUsers();
4444            final Set<ReadByMarker> addedMarkers = new HashSet<>();
4445            ChatState state = ChatState.COMPOSING;
4446            List<MucOptions.User> users =
4447                    conversation.getMucOptions().getUsersWithChatState(state, 5);
4448            if (users.size() == 0) {
4449                state = ChatState.PAUSED;
4450                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
4451            }
4452            if (mucOptions.isPrivateAndNonAnonymous()) {
4453                for (int i = this.messageList.size() - 1; i >= 0; --i) {
4454                    final Set<ReadByMarker> markersForMessage =
4455                            messageList.get(i).getReadByMarkers();
4456                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
4457                    for (ReadByMarker marker : markersForMessage) {
4458                        if (!ReadByMarker.contains(marker, addedMarkers)) {
4459                            addedMarkers.add(
4460                                    marker); // may be put outside this condition. set should do
4461                            // dedup anyway
4462                            MucOptions.User user = mucOptions.findUser(marker);
4463                            if (user != null && !users.contains(user)) {
4464                                shownMarkers.add(user);
4465                            }
4466                        }
4467                    }
4468                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
4469                    final Message statusMessage;
4470                    final int size = shownMarkers.size();
4471                    if (size > 1) {
4472                        final String body;
4473                        if (size <= 4) {
4474                            body =
4475                                    getString(
4476                                            R.string.contacts_have_read_up_to_this_point,
4477                                            UIHelper.concatNames(shownMarkers));
4478                        } else if (ReadByMarker.allUsersRepresented(
4479                                allUsers, markersForMessage, markerForSender)) {
4480                            body = getString(R.string.everyone_has_read_up_to_this_point);
4481                        } else {
4482                            body =
4483                                    getString(
4484                                            R.string.contacts_and_n_more_have_read_up_to_this_point,
4485                                            UIHelper.concatNames(shownMarkers, 3),
4486                                            size - 3);
4487                        }
4488                        statusMessage = Message.createStatusMessage(conversation, body);
4489                        statusMessage.setCounterparts(shownMarkers);
4490                    } else if (size == 1) {
4491                        statusMessage =
4492                                Message.createStatusMessage(
4493                                        conversation,
4494                                        getString(
4495                                                R.string.contact_has_read_up_to_this_point,
4496                                                UIHelper.getDisplayName(shownMarkers.get(0))));
4497                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
4498                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
4499                    } else {
4500                        statusMessage = null;
4501                    }
4502                    if (statusMessage != null) {
4503                        this.messageList.add(i + 1, statusMessage);
4504                    }
4505                    addedMarkers.add(markerForSender);
4506                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
4507                        break;
4508                    }
4509                }
4510            }
4511            if (users.size() > 0) {
4512                Message statusMessage;
4513                if (users.size() == 1) {
4514                    MucOptions.User user = users.get(0);
4515                    int id =
4516                            state == ChatState.COMPOSING
4517                                    ? R.string.contact_is_typing
4518                                    : R.string.contact_has_stopped_typing;
4519                    statusMessage =
4520                            Message.createStatusMessage(
4521                                    conversation, getString(id, UIHelper.getDisplayName(user)));
4522                    statusMessage.setTrueCounterpart(user.getRealJid());
4523                    statusMessage.setCounterpart(user.getFullJid());
4524                } else {
4525                    int id =
4526                            state == ChatState.COMPOSING
4527                                    ? R.string.contacts_are_typing
4528                                    : R.string.contacts_have_stopped_typing;
4529                    statusMessage =
4530                            Message.createStatusMessage(
4531                                    conversation, getString(id, UIHelper.concatNames(users)));
4532                    statusMessage.setCounterparts(users);
4533                }
4534                this.messageList.add(statusMessage);
4535            }
4536        }
4537    }
4538
4539    private void stopScrolling() {
4540        long now = SystemClock.uptimeMillis();
4541        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
4542        binding.messagesView.dispatchTouchEvent(cancel);
4543    }
4544
4545    private boolean showLoadMoreMessages(final Conversation c) {
4546        if (activity == null || activity.xmppConnectionService == null) {
4547            return false;
4548        }
4549        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
4550        final MessageArchiveService service =
4551                activity.xmppConnectionService.getMessageArchiveService();
4552        return mam
4553                && (c.getLastClearHistory().getTimestamp() != 0
4554                        || (c.countMessages() == 0
4555                                && c.messagesLoaded.get()
4556                                && c.hasMessagesLeftOnServer()
4557                                && !service.queryInProgress(c)));
4558    }
4559
4560    private boolean hasMamSupport(final Conversation c) {
4561        if (c.getMode() == Conversation.MODE_SINGLE) {
4562            final XmppConnection connection = c.getAccount().getXmppConnection();
4563            return connection != null && connection.getFeatures().mam();
4564        } else {
4565            return c.getMucOptions().mamSupport();
4566        }
4567    }
4568
4569    protected void showSnackbar(
4570            final int message, final int action, final OnClickListener clickListener) {
4571        showSnackbar(message, action, clickListener, null);
4572    }
4573
4574    protected void showSnackbar(
4575            final int message,
4576            final int action,
4577            final OnClickListener clickListener,
4578            final View.OnLongClickListener longClickListener) {
4579        this.binding.snackbar.setVisibility(View.VISIBLE);
4580        this.binding.snackbar.setOnClickListener(null);
4581        this.binding.snackbarMessage.setText(message);
4582        this.binding.snackbarMessage.setOnClickListener(null);
4583        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
4584        if (action != 0) {
4585            this.binding.snackbarAction.setText(action);
4586        }
4587        this.binding.snackbarAction.setOnClickListener(clickListener);
4588        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
4589    }
4590
4591    protected void hideSnackbar() {
4592        this.binding.snackbar.setVisibility(View.GONE);
4593    }
4594
4595    protected void sendMessage(Message message) {
4596        new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
4597        messageSent();
4598    }
4599
4600    protected void sendPgpMessage(final Message message) {
4601        final XmppConnectionService xmppService = activity.xmppConnectionService;
4602        final Contact contact = message.getConversation().getContact();
4603        if (!activity.hasPgp()) {
4604            activity.showInstallPgpDialog();
4605            return;
4606        }
4607        if (conversation.getAccount().getPgpSignature() == null) {
4608            activity.announcePgp(
4609                    conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
4610            return;
4611        }
4612        if (!mSendingPgpMessage.compareAndSet(false, true)) {
4613            Log.d(Config.LOGTAG, "sending pgp message already in progress");
4614        }
4615        if (conversation.getMode() == Conversation.MODE_SINGLE) {
4616            if (contact.getPgpKeyId() != 0) {
4617                xmppService
4618                        .getPgpEngine()
4619                        .hasKey(
4620                                contact,
4621                                new UiCallback<Contact>() {
4622
4623                                    @Override
4624                                    public void userInputRequired(
4625                                            PendingIntent pi, Contact contact) {
4626                                        startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
4627                                    }
4628
4629                                    @Override
4630                                    public void success(Contact contact) {
4631                                        encryptTextMessage(message);
4632                                    }
4633
4634                                    @Override
4635                                    public void error(int error, Contact contact) {
4636                                        activity.runOnUiThread(
4637                                                () ->
4638                                                        Toast.makeText(
4639                                                                        activity,
4640                                                                        R.string
4641                                                                                .unable_to_connect_to_keychain,
4642                                                                        Toast.LENGTH_SHORT)
4643                                                                .show());
4644                                        mSendingPgpMessage.set(false);
4645                                    }
4646                                });
4647
4648            } else {
4649                showNoPGPKeyDialog(
4650                        false,
4651                        (dialog, which) -> {
4652                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4653                            xmppService.updateConversation(conversation);
4654                            message.setEncryption(Message.ENCRYPTION_NONE);
4655                            xmppService.sendMessage(message);
4656                            messageSent();
4657                        });
4658            }
4659        } else {
4660            if (conversation.getMucOptions().pgpKeysInUse()) {
4661                if (!conversation.getMucOptions().everybodyHasKeys()) {
4662                    Toast warning =
4663                            Toast.makeText(
4664                                    getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
4665                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
4666                    warning.show();
4667                }
4668                encryptTextMessage(message);
4669            } else {
4670                showNoPGPKeyDialog(
4671                        true,
4672                        (dialog, which) -> {
4673                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4674                            message.setEncryption(Message.ENCRYPTION_NONE);
4675                            xmppService.updateConversation(conversation);
4676                            xmppService.sendMessage(message);
4677                            messageSent();
4678                        });
4679            }
4680        }
4681    }
4682
4683    public void encryptTextMessage(Message message) {
4684        activity.xmppConnectionService
4685                .getPgpEngine()
4686                .encrypt(
4687                        message,
4688                        new UiCallback<Message>() {
4689
4690                            @Override
4691                            public void userInputRequired(PendingIntent pi, Message message) {
4692                                startPendingIntent(pi, REQUEST_SEND_MESSAGE);
4693                            }
4694
4695                            @Override
4696                            public void success(Message message) {
4697                                // TODO the following two call can be made before the callback
4698                                getActivity().runOnUiThread(() -> messageSent());
4699                            }
4700
4701                            @Override
4702                            public void error(final int error, Message message) {
4703                                getActivity()
4704                                        .runOnUiThread(
4705                                                () -> {
4706                                                    doneSendingPgpMessage();
4707                                                    Toast.makeText(
4708                                                                    getActivity(),
4709                                                                    error == 0
4710                                                                            ? R.string
4711                                                                                    .unable_to_connect_to_keychain
4712                                                                            : error,
4713                                                                    Toast.LENGTH_SHORT)
4714                                                            .show();
4715                                                });
4716                            }
4717                        });
4718    }
4719
4720    public void showNoPGPKeyDialog(
4721            final boolean plural, final DialogInterface.OnClickListener listener) {
4722        final MaterialAlertDialogBuilder builder =
4723                new MaterialAlertDialogBuilder(requireActivity());
4724        if (plural) {
4725            builder.setTitle(getString(R.string.no_pgp_keys));
4726            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4727        } else {
4728            builder.setTitle(getString(R.string.no_pgp_key));
4729            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4730        }
4731        builder.setNegativeButton(getString(R.string.cancel), null);
4732        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4733        builder.create().show();
4734    }
4735
4736    public void appendText(String text, final boolean doNotAppend) {
4737        if (text == null) {
4738            return;
4739        }
4740        final Editable editable = this.binding.textinput.getText();
4741        String previous = editable == null ? "" : editable.toString();
4742        if (doNotAppend && !TextUtils.isEmpty(previous)) {
4743            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4744                    .show();
4745            return;
4746        }
4747        if (UIHelper.isLastLineQuote(previous)) {
4748            text = '\n' + text;
4749        } else if (previous.length() != 0
4750                && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4751            text = " " + text;
4752        }
4753        this.binding.textinput.append(text);
4754    }
4755
4756    @Override
4757    public boolean onEnterPressed(final boolean isCtrlPressed) {
4758        if (isCtrlPressed || enterIsSend()) {
4759            sendMessage();
4760            return true;
4761        }
4762        return false;
4763    }
4764
4765    private boolean enterIsSend() {
4766        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4767        return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4768    }
4769
4770    public boolean onArrowUpCtrlPressed() {
4771        final Message lastEditableMessage =
4772                conversation == null ? null : conversation.getLastEditableMessage();
4773        if (lastEditableMessage != null) {
4774            correctMessage(lastEditableMessage);
4775            return true;
4776        } else {
4777            Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4778                    .show();
4779            return false;
4780        }
4781    }
4782
4783    @Override
4784    public void onTypingStarted() {
4785        final XmppConnectionService service =
4786                activity == null ? null : activity.xmppConnectionService;
4787        if (service == null) {
4788            return;
4789        }
4790        final Account.State status = conversation.getAccount().getStatus();
4791        if (status == Account.State.ONLINE
4792                && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4793            service.sendChatState(conversation);
4794        }
4795        runOnUiThread(this::updateSendButton);
4796    }
4797
4798    @Override
4799    public void onTypingStopped() {
4800        final XmppConnectionService service =
4801                activity == null ? null : activity.xmppConnectionService;
4802        if (service == null) {
4803            return;
4804        }
4805        final Account.State status = conversation.getAccount().getStatus();
4806        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4807            service.sendChatState(conversation);
4808        }
4809    }
4810
4811    @Override
4812    public void onTextDeleted() {
4813        final XmppConnectionService service =
4814                activity == null ? null : activity.xmppConnectionService;
4815        if (service == null) {
4816            return;
4817        }
4818        final Account.State status = conversation.getAccount().getStatus();
4819        if (status == Account.State.ONLINE
4820                && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4821            service.sendChatState(conversation);
4822        }
4823        final boolean stored = storeNextMessage(null);
4824        runOnUiThread(
4825                () -> {
4826                    if (stored && activity != null) {
4827                        activity.onConversationsListItemUpdated();
4828                    }
4829                    updateSendButton();
4830                });
4831    }
4832
4833    @Override
4834    public void onTextChanged() {
4835        if (conversation != null && conversation.getCorrectingMessage() != null) {
4836            runOnUiThread(this::updateSendButton);
4837        }
4838    }
4839
4840    @Override
4841    public boolean onTabPressed(boolean repeated) {
4842        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4843            return false;
4844        }
4845        if (repeated) {
4846            completionIndex++;
4847        } else {
4848            lastCompletionLength = 0;
4849            completionIndex = 0;
4850            final String content = this.binding.textinput.getText().toString();
4851            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4852            int start =
4853                    lastCompletionCursor > 0
4854                            ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4855                            : 0;
4856            firstWord = start == 0;
4857            incomplete = content.substring(start, lastCompletionCursor);
4858        }
4859        List<String> completions = new ArrayList<>();
4860        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4861            String name = user.getNick();
4862            if (name != null && name.startsWith(incomplete)) {
4863                completions.add(name + (firstWord ? ": " : " "));
4864            }
4865        }
4866        Collections.sort(completions);
4867        if (completions.size() > completionIndex) {
4868            String completion = completions.get(completionIndex).substring(incomplete.length());
4869            this.binding
4870                    .textinput
4871                    .getEditableText()
4872                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4873            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4874            lastCompletionLength = completion.length();
4875        } else {
4876            completionIndex = -1;
4877            this.binding
4878                    .textinput
4879                    .getEditableText()
4880                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4881            lastCompletionLength = 0;
4882        }
4883        return true;
4884    }
4885
4886    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4887        try {
4888            getActivity()
4889                    .startIntentSenderForResult(
4890                            pendingIntent.getIntentSender(),
4891                            requestCode,
4892                            null,
4893                            0,
4894                            0,
4895                            0,
4896                            Compatibility.pgpStartIntentSenderOptions());
4897        } catch (final SendIntentException ignored) {
4898        }
4899    }
4900
4901    @Override
4902    public void onBackendConnected() {
4903        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4904        setupEmojiSearch();
4905        String uuid = pendingConversationsUuid.pop();
4906        if (uuid != null) {
4907            if (!findAndReInitByUuidOrArchive(uuid)) {
4908                return;
4909            }
4910        } else {
4911            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4912                clearPending();
4913                activity.onConversationArchived(conversation);
4914                return;
4915            }
4916        }
4917        ActivityResult activityResult = postponedActivityResult.pop();
4918        if (activityResult != null) {
4919            handleActivityResult(activityResult);
4920        }
4921        clearPending();
4922    }
4923
4924    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4925        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4926        if (conversation == null) {
4927            clearPending();
4928            activity.onConversationArchived(null);
4929            return false;
4930        }
4931        reInit(conversation);
4932        ScrollState scrollState = pendingScrollState.pop();
4933        String lastMessageUuid = pendingLastMessageUuid.pop();
4934        List<Attachment> attachments = pendingMediaPreviews.pop();
4935        if (scrollState != null) {
4936            setScrollPosition(scrollState, lastMessageUuid);
4937        }
4938        if (attachments != null && attachments.size() > 0) {
4939            Log.d(Config.LOGTAG, "had attachments on restore");
4940            mediaPreviewAdapter.addMediaPreviews(attachments);
4941            toggleInputMethod();
4942        }
4943        return true;
4944    }
4945
4946    private void clearPending() {
4947        if (postponedActivityResult.clear()) {
4948            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4949            if (pendingTakePhotoUri.clear()) {
4950                Log.e(Config.LOGTAG, "cleared pending photo uri");
4951            }
4952        }
4953        if (pendingScrollState.clear()) {
4954            Log.e(Config.LOGTAG, "cleared scroll state");
4955        }
4956        if (pendingConversationsUuid.clear()) {
4957            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4958        }
4959        if (pendingMediaPreviews.clear()) {
4960            Log.e(Config.LOGTAG, "cleared pending media previews");
4961        }
4962    }
4963
4964    public Conversation getConversation() {
4965        return conversation;
4966    }
4967
4968    @Override
4969    public void onContactPictureLongClicked(View v, final Message message) {
4970        final String fingerprint;
4971        if (message.getEncryption() == Message.ENCRYPTION_PGP
4972                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4973            fingerprint = "pgp";
4974        } else {
4975            fingerprint = message.getFingerprint();
4976        }
4977        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4978        final Contact contact = message.getContact();
4979        if (message.getStatus() <= Message.STATUS_RECEIVED
4980                && (contact == null || !contact.isSelf())) {
4981            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4982                final Jid cp = message.getCounterpart();
4983                if (cp == null || cp.isBareJid()) {
4984                    return;
4985                }
4986                final Jid tcp = message.getTrueCounterpart();
4987                final String occupantId = message.getOccupantId();
4988                final User userByRealJid =
4989                        tcp != null
4990                                ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp, occupantId)
4991                                : null;
4992                final User userByOccupantId =
4993                        occupantId != null
4994                                ? conversation.getMucOptions().findUserByOccupantId(occupantId, cp)
4995                                : null;
4996                final User user =
4997                        userByRealJid != null
4998                                ? userByRealJid
4999                                : (userByOccupantId != null ? userByOccupantId : conversation.getMucOptions().findUserByFullJid(cp));
5000                if (user == null) return;
5001                popupMenu.inflate(R.menu.muc_details_context);
5002                final Menu menu = popupMenu.getMenu();
5003                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
5004                        activity, menu, conversation, user);
5005                popupMenu.setOnMenuItemClickListener(
5006                        menuItem ->
5007                                MucDetailsContextMenuHelper.onContextItemSelected(
5008                                        menuItem, user, activity, fingerprint));
5009            } else {
5010                popupMenu.inflate(R.menu.one_on_one_context);
5011                popupMenu.setOnMenuItemClickListener(
5012                        item -> {
5013                            switch (item.getItemId()) {
5014                                case R.id.action_contact_details:
5015                                    activity.switchToContactDetails(
5016                                            message.getContact(), fingerprint);
5017                                    break;
5018                                case R.id.action_show_qr_code:
5019                                    activity.showQrCode(
5020                                            "xmpp:"
5021                                                    + message.getContact()
5022                                                            .getJid()
5023                                                            .asBareJid()
5024                                                            .toString());
5025                                    break;
5026                            }
5027                            return true;
5028                        });
5029            }
5030        } else {
5031            popupMenu.inflate(R.menu.account_context);
5032            final Menu menu = popupMenu.getMenu();
5033            menu.findItem(R.id.action_manage_accounts)
5034                    .setVisible(QuickConversationsService.isConversations());
5035            popupMenu.setOnMenuItemClickListener(
5036                    item -> {
5037                        final XmppActivity activity = this.activity;
5038                        if (activity == null) {
5039                            Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
5040                            return true;
5041                        }
5042                        switch (item.getItemId()) {
5043                            case R.id.action_show_qr_code:
5044                                activity.showQrCode(conversation.getAccount().getShareableUri());
5045                                break;
5046                            case R.id.action_account_details:
5047                                activity.switchToAccount(
5048                                        message.getConversation().getAccount(), fingerprint);
5049                                break;
5050                            case R.id.action_manage_accounts:
5051                                AccountUtils.launchManageAccounts(activity);
5052                                break;
5053                        }
5054                        return true;
5055                    });
5056        }
5057        popupMenu.show();
5058    }
5059
5060    @Override
5061    public void onContactPictureClicked(Message message) {
5062        setThread(message.getThread());
5063        if (message.isPrivateMessage()) {
5064            privateMessageWith(message.getCounterpart());
5065            return;
5066        }
5067        forkNullThread(message);
5068        conversation.setUserSelectedThread(true);
5069
5070        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
5071        if (received) {
5072            if (message.getConversation() instanceof Conversation
5073                    && message.getConversation().getMode() == Conversation.MODE_MULTI) {
5074                Jid tcp = message.getTrueCounterpart();
5075                Jid user = message.getCounterpart();
5076                if (user != null && !user.isBareJid()) {
5077                    final MucOptions mucOptions =
5078                            ((Conversation) message.getConversation()).getMucOptions();
5079                    if (mucOptions.participating()
5080                            || ((Conversation) message.getConversation()).getNextCounterpart()
5081                                    != null) {
5082                        MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
5083                        MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
5084                        if (mucUser == null && tcpMucUser == null) {
5085                            Toast.makeText(
5086                                            getActivity(),
5087                                            activity.getString(
5088                                                    R.string.user_has_left_conference,
5089                                                    user.getResource()),
5090                                            Toast.LENGTH_SHORT)
5091                                    .show();
5092                        }
5093                        highlightInConference(mucUser == null || mucUser.getNick() == null ? (tcpMucUser == null || tcpMucUser.getNick() == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
5094                    } else {
5095                        Toast.makeText(
5096                                        getActivity(),
5097                                        R.string.you_are_not_participating,
5098                                        Toast.LENGTH_SHORT)
5099                                .show();
5100                    }
5101                }
5102            }
5103        }
5104    }
5105
5106    private Activity requireActivity() {
5107        Activity activity = getActivity();
5108        if (activity == null) activity = this.activity;
5109        if (activity == null) {
5110            throw new IllegalStateException("Activity not attached");
5111        }
5112        return activity;
5113    }
5114}