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