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