ConversationFragment.java

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