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