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                    final var allUsers = conversation.getMucOptions().getUsers();
1543                    if (!conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).isEmpty()) {
1544                        final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0role:moderator", "Notify active moderators", new HashSet<>());
1545                        u.setRole("participant");
1546                        allUsers.add(u);
1547                    }
1548                    if (!allUsers.isEmpty() && conversation.getMucOptions().getSelf() != null && conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
1549                        final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0attention", "Notify active participants", new HashSet<>());
1550                        u.setRole("participant");
1551                        allUsers.add(u);
1552                    }
1553                    final String needle = query.toString().toLowerCase(Locale.getDefault());
1554                    adapter.submitList(
1555                        Ordering.natural().immutableSortedCopy(Collections2.filter(
1556                            allUsers,
1557                            user -> {
1558                                if ("mods".contains(needle) && "\0role:moderator".equals(user.getOccupantId())) return true;
1559                                if ("here".contains(needle) && "\0attention".equals(user.getOccupantId())) return true;
1560                                final String name = user.getNick();
1561                                if (name == null) return false;
1562                                for (final var hat : user.getHats()) {
1563                                    if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1564                                }
1565                                for (final var hat : user.getPseudoHats(activity)) {
1566                                    if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1567                                }
1568                                final Contact contact = user.getContact();
1569                                return name.toLowerCase(Locale.getDefault()).contains(needle)
1570                                    || contact != null
1571                                    && contact.getDisplayName().toLowerCase(Locale.getDefault()).contains(needle);
1572                            })));
1573                }
1574
1575                @Override
1576                protected AutocompletePresenter.PopupDimensions getPopupDimensions() {
1577                    final var dim = new AutocompletePresenter.PopupDimensions();
1578                    dim.width = displayMetrics.widthPixels * 4/5;
1579                    return dim;
1580                }
1581            })
1582            .with(new AutocompleteCallback<MucOptions.User>() {
1583                @Override
1584                public boolean onPopupItemClicked(Editable editable, MucOptions.User user) {
1585                    int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1586                    if (range == null) return false;
1587                    range[0] -= 1;
1588                    if ("\0attention".equals(user.getOccupantId())) {
1589	                    editable.delete(Math.max(0, range[0]), Math.min(editable.length(), range[1]));
1590                        editable.insert(0, "@here ");
1591                        return true;
1592                    }
1593                    int colon = editable.toString().indexOf(':');
1594                    final var beforeColon = range[0] < colon;
1595                    String prefix = "";
1596                    String suffix = " ";
1597                    if (beforeColon) suffix = ", ";
1598                    if (colon < 0 && range[0] == 0) suffix = ": ";
1599                    if (colon > 0 && colon == range[0] - 2) {
1600                        prefix = ", ";
1601                        suffix = ": ";
1602                        range[0] -= 2;
1603                    }
1604                    var insert = user.getNick();
1605                    if ("\0role:moderator".equals(user.getOccupantId())) {
1606                        insert = conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).stream().map(MucOptions.User::getNick).collect(Collectors.joining(", "));
1607                    }
1608                    editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), prefix + insert + suffix);
1609                    return true;
1610                }
1611
1612                @Override
1613                public void onPopupVisibilityChanged(boolean shown) {}
1614            }).build();
1615
1616        Handler emojiDebounce = new Handler(Looper.getMainLooper());
1617        setupEmojiSearch();
1618        Autocomplete.<EmojiSearch.Emoji>on(binding.textinput)
1619            .with(activity.getDrawable(R.drawable.background_message_bubble))
1620            .with(new CharPolicy(':'))
1621            .with(new RecyclerViewPresenter<EmojiSearch.Emoji>(activity) {
1622                protected EmojiSearch.EmojiSearchAdapter adapter;
1623
1624                @Override
1625                protected Adapter instantiateAdapter() {
1626                    setupEmojiSearch();
1627                    adapter = emojiSearch.makeAdapter(item -> dispatchClick(item));
1628                    return adapter;
1629                }
1630
1631                @Override
1632                protected void onViewHidden() {
1633                    if (getRecyclerView() == null) return;
1634                    super.onViewHidden();
1635                }
1636
1637                @Override
1638                protected void onQuery(@Nullable CharSequence query) {
1639                    if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1640
1641                    emojiDebounce.removeCallbacksAndMessages(null);
1642                    emojiDebounce.postDelayed(() -> {
1643                        if (getRecyclerView() == null) return;
1644                        getRecyclerView().setItemAnimator(null);
1645                        adapter.search(activity, getRecyclerView(), query.toString());
1646                    }, 100L);
1647                }
1648            })
1649            .with(new AutocompleteCallback<EmojiSearch.Emoji>() {
1650                @Override
1651                public boolean onPopupItemClicked(Editable editable, EmojiSearch.Emoji emoji) {
1652                    int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1653                    if (range == null) return false;
1654                    range[0] -= 1;
1655                    final var toInsert = emoji.toInsert();
1656                    toInsert.append(" ");
1657                    editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), toInsert);
1658                    return true;
1659                }
1660
1661                @Override
1662                public void onPopupVisibilityChanged(boolean shown) {}
1663            }).build();
1664
1665        return binding.getRoot();
1666    }
1667
1668    protected void setupEmojiSearch() {
1669        if (activity != null && activity.xmppConnectionService != null) {
1670            if (emojiSearch == null) {
1671                emojiSearch = activity.xmppConnectionService.emojiSearch();
1672            }
1673        }
1674    }
1675
1676    protected void newThreadTutorialToast(String s) {
1677        if (activity == null) return;
1678        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1679        final int tutorialCount = p.getInt("thread_tutorial", 0);
1680        if (tutorialCount < 5) {
1681            Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1682            p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1683        }
1684    }
1685
1686    @Override
1687    public void onDestroyView() {
1688        super.onDestroyView();
1689        Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1690        messageListAdapter.setOnContactPictureClicked(null);
1691        messageListAdapter.setOnContactPictureLongClicked(null);
1692        messageListAdapter.setOnInlineImageLongClicked(null);
1693        messageListAdapter.setConversationFragment(null);
1694        messageListAdapter.setOnMessageBoxClicked(null);
1695        messageListAdapter.setOnMessageBoxSwiped(null);
1696        binding.conversationViewPager.setAdapter(null);
1697        if (conversation != null) conversation.setupViewPager(null, null, false, null);
1698    }
1699
1700    public void quoteText(String text) {
1701        if (binding.textinput.isEnabled()) {
1702            binding.textinput.insertAsQuote(text);
1703            binding.textinput.requestFocus();
1704            InputMethodManager inputMethodManager =
1705                    (InputMethodManager)
1706                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1707            if (inputMethodManager != null) {
1708                inputMethodManager.showSoftInput(
1709                        binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1710            }
1711        }
1712    }
1713
1714    private void quoteMessage(Message message) {
1715        if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1716        setThread(message.getThread());
1717        conversation.setUserSelectedThread(true);
1718        if (!forkNullThread(message)) newThread();
1719        setupReply(message);
1720    }
1721
1722    private boolean forkNullThread(Message message) {
1723        if (message.getThread() != null || conversation.getMode() != Conversation.MODE_MULTI) return true;
1724        for (final Message m : conversation.findReplies(message.getServerMsgId())) {
1725            final Element thread = m.getThread();
1726            if (thread != null) {
1727                setThread(thread);
1728                return true;
1729            }
1730        }
1731
1732        return false;
1733    }
1734
1735    private void setupReply(Message message) {
1736        conversation.setReplyTo(message);
1737        if (message == null) {
1738            binding.contextPreview.setVisibility(View.GONE);
1739            binding.textsend.setBackgroundResource(R.drawable.textsend);
1740            return;
1741        }
1742
1743        SpannableStringBuilder body = message.getSpannableBody(null, null);
1744        if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1745        messageListAdapter.handleTextQuotes(binding.contextPreviewText, body);
1746        binding.contextPreviewText.setText(body);
1747        binding.contextPreview.setVisibility(View.VISIBLE);
1748    }
1749
1750    private void setThread(Element thread) {
1751        this.conversation.setThread(thread);
1752        binding.threadIdenticon.setAlpha(0f);
1753        binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1754        if (thread != null) {
1755            final String threadId = thread.getContent();
1756            if (threadId != null) {
1757                binding.threadIdenticon.setAlpha(1f);
1758                binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1759                binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1760            }
1761        }
1762        updateSendButton();
1763    }
1764
1765    @Override
1766    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1767        // This should cancel any remaining click events that would otherwise trigger links
1768        v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1769
1770        if (v == binding.textSendButton) {
1771            super.onCreateContextMenu(menu, v, menuInfo);
1772            try {
1773                java.lang.reflect.Method m = menu.getClass().getSuperclass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
1774                m.setAccessible(true);
1775                m.invoke(menu, true);
1776            } catch (Exception e) {
1777                e.printStackTrace();
1778            }
1779            Menu tmpMenu = new PopupMenu(activity, null).getMenu();
1780            activity.getMenuInflater().inflate(R.menu.fragment_conversation, tmpMenu);
1781            MenuItem attachMenu = tmpMenu.findItem(R.id.action_attach_file);
1782            for (int i = 0; i < attachMenu.getSubMenu().size(); i++) {
1783                MenuItem item = attachMenu.getSubMenu().getItem(i);
1784                MenuItem newItem = menu.add(item.getGroupId(), item.getItemId(), item.getOrder(), item.getTitle());
1785                newItem.setIcon(item.getIcon());
1786            }
1787            ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1788            return;
1789        }
1790
1791        synchronized (this.messageList) {
1792            super.onCreateContextMenu(menu, v, menuInfo);
1793            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1794            this.selectedMessage = this.messageList.get(acmi.position);
1795            populateContextMenu(menu);
1796        }
1797    }
1798
1799    private void populateContextMenu(ContextMenu menu) {
1800        final Message m = this.selectedMessage;
1801        final Transferable t = m.getTransferable();
1802        Message relevantForCorrection = m;
1803        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1804            relevantForCorrection = relevantForCorrection.next();
1805        }
1806        if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1807
1808            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1809                    || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1810                return;
1811            }
1812
1813            if (m.getStatus() == Message.STATUS_RECEIVED
1814                    && t != null
1815                    && (t.getStatus() == Transferable.STATUS_CANCELLED
1816                            || t.getStatus() == Transferable.STATUS_FAILED)) {
1817                return;
1818            }
1819
1820            final boolean deleted = m.isDeleted();
1821            final boolean encrypted =
1822                    m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1823                            || m.getEncryption() == Message.ENCRYPTION_PGP;
1824            final boolean receiving =
1825                    m.getStatus() == Message.STATUS_RECEIVED
1826                            && (t instanceof JingleFileTransferConnection
1827                                    || t instanceof HttpDownloadConnection);
1828            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1829            final MenuItem reportAndBlock = menu.findItem(R.id.action_report_and_block);
1830            final MenuItem addReaction = menu.findItem(R.id.action_add_reaction);
1831            MenuItem openWith = menu.findItem(R.id.open_with);
1832            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1833            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1834            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1835            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1836            MenuItem retractMessage = menu.findItem(R.id.retract_message);
1837            MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1838            MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1839            MenuItem shareWith = menu.findItem(R.id.share_with);
1840            MenuItem sendAgain = menu.findItem(R.id.send_again);
1841            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1842            MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1843            MenuItem downloadFile = menu.findItem(R.id.download_file);
1844            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1845            MenuItem blockMedia = menu.findItem(R.id.block_media);
1846            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1847            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1848            onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1849            final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1850            final boolean showError =
1851                    m.getStatus() == Message.STATUS_SEND_FAILED
1852                            && m.getErrorMessage() != null
1853                            && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1854            final Conversational conversational = m.getConversation();
1855            if (m.getStatus() == Message.STATUS_RECEIVED && conversational instanceof Conversation c) {
1856                final XmppConnection connection = c.getAccount().getXmppConnection();
1857                if (c.isWithStranger()
1858                        && m.getServerMsgId() != null
1859                        && !c.isBlocked()
1860                        && connection != null
1861                        && connection.getFeatures().spamReporting()) {
1862                    reportAndBlock.setVisible(true);
1863                }
1864            }
1865            if (!encrypted) {
1866                addReaction.setVisible(!showError && !m.isDeleted());
1867            }
1868            if (!m.isFileOrImage()
1869                    && !encrypted
1870                    && !m.isGeoUri()
1871                    && !m.treatAsDownloadable()
1872                    && !unInitiatedButKnownSize
1873                    && t == null) {
1874                copyMessage.setVisible(true);
1875            }
1876            quoteMessage.setVisible(!encrypted && !showError);
1877            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1878                retryDecryption.setVisible(true);
1879            }
1880            if (!showError
1881                    && relevantForCorrection.getType() == Message.TYPE_TEXT
1882                    && relevantForCorrection.isEditable()
1883                    && !m.isGeoUri()
1884                    && m.getConversation() instanceof Conversation) {
1885                correctMessage.setVisible(true);
1886                if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1887            }
1888            if (relevantForCorrection.getStatus() == Message.STATUS_WAITING) {
1889                correctMessage.setVisible(true);
1890                retractMessage.setVisible(true);
1891            }
1892            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")) {
1893                moderateMessage.setVisible(true);
1894            }
1895            if ((m.isFileOrImage() && !deleted && !receiving)
1896                    || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1897                            && !unInitiatedButKnownSize
1898                            && t == null) {
1899                shareWith.setVisible(true);
1900            }
1901            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1902                sendAgain.setVisible(true);
1903            }
1904            if (m.hasFileOnRemoteHost()
1905                    || m.isGeoUri()
1906                    || m.treatAsDownloadable()
1907                    || unInitiatedButKnownSize
1908                    || t instanceof HttpDownloadConnection) {
1909                copyUrl.setVisible(true);
1910            }
1911            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1912                downloadFile.setVisible(true);
1913                downloadFile.setTitle(
1914                        activity.getString(
1915                                R.string.download_x_file,
1916                                UIHelper.getFileDescriptionString(activity, m)));
1917            }
1918            final boolean waitingOfferedSending =
1919                    m.getStatus() == Message.STATUS_WAITING
1920                            || m.getStatus() == Message.STATUS_UNSEND
1921                            || m.getStatus() == Message.STATUS_OFFERED;
1922            final boolean cancelable =
1923                    (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1924            if (cancelable) {
1925                cancelTransmission.setVisible(true);
1926            }
1927            if (m.isFileOrImage() && !deleted && !cancelable) {
1928                final String path = m.getRelativeFilePath();
1929                if (path != null) {
1930                    final var file = new File(path);
1931                    if (file.canRead()) saveAsSticker.setVisible(true);
1932                    blockMedia.setVisible(true);
1933                    if (file.canWrite()) deleteFile.setVisible(true);
1934                    deleteFile.setTitle(
1935                            activity.getString(
1936                                    R.string.delete_x_file,
1937                                    UIHelper.getFileDescriptionString(activity, m)));
1938                }
1939            }
1940
1941            if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1942                // We might be showing a thumbnail worth blocking
1943                blockMedia.setVisible(true);
1944            }
1945            if (showError) {
1946                showErrorMessage.setVisible(true);
1947            }
1948            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1949            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1950                    || (mime != null && mime.startsWith("audio/"))) {
1951                openWith.setVisible(true);
1952            }
1953        }
1954    }
1955
1956    @Override
1957    public boolean onContextItemSelected(MenuItem item) {
1958        switch (item.getItemId()) {
1959            case R.id.share_with:
1960                ShareUtil.share(activity, selectedMessage);
1961                return true;
1962            case R.id.correct_message:
1963                correctMessage(selectedMessage);
1964                return true;
1965            case R.id.retract_message:
1966                new AlertDialog.Builder(activity)
1967                    .setTitle(R.string.retract_message)
1968                    .setMessage("Do you really want to retract this message?")
1969                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1970                        Message message = selectedMessage;
1971                        while (message.mergeable(message.next())) {
1972                            message = message.next();
1973                        }
1974                        if (message.getStatus() == Message.STATUS_WAITING || message.getStatus() == Message.STATUS_OFFERED) {
1975                            activity.xmppConnectionService.deleteMessage(message);
1976                            return;
1977                        }
1978                        Element reactions = message.getReactionsEl();
1979                        if (reactions != null) {
1980                            final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
1981                            if (previousReaction != null) reactions = previousReaction.getReactionsEl();
1982                            for (Element el : reactions.getChildren()) {
1983                                if (message.getRawBody().endsWith(el.getContent())) {
1984                                    reactions.removeChild(el);
1985                                }
1986                            }
1987                            message.setReactions(reactions);
1988                            if (previousReaction != null) {
1989                                previousReaction.setReactions(reactions);
1990                                activity.xmppConnectionService.updateMessage(previousReaction);
1991                            }
1992                        } else {
1993                            message.setInReplyTo(null);
1994                            message.clearPayloads();
1995                        }
1996                        message.setBody(" ");
1997                        message.setSubject(null);
1998                        message.putEdited(message.getUuid(), message.getServerMsgId());
1999                        message.setServerMsgId(null);
2000                        message.setUuid(UUID.randomUUID().toString());
2001                        sendMessage(message);
2002                    })
2003                    .setNegativeButton(R.string.no, null).show();
2004                return true;
2005            case R.id.moderate_message:
2006                activity.quickEdit("Spam", (reason) -> {
2007                    Message message = selectedMessage;
2008                    do {
2009                        activity.xmppConnectionService.moderateMessage(conversation.getAccount(), message, reason);
2010                        message = message.mergeable(message.next()) ? message.next() : null;
2011                    } while (message != null);
2012                    return null;
2013                }, R.string.moderate_reason, false, false, true, true);
2014                return true;
2015            case R.id.copy_message:
2016                ShareUtil.copyToClipboard(activity, selectedMessage);
2017                return true;
2018            case R.id.quote_message:
2019                quoteMessage(selectedMessage);
2020                return true;
2021            case R.id.send_again:
2022                resendMessage(selectedMessage);
2023                return true;
2024            case R.id.copy_url:
2025                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
2026                return true;
2027            case R.id.save_as_sticker:
2028                saveAsSticker(selectedMessage);
2029                return true;
2030            case R.id.download_file:
2031                startDownloadable(selectedMessage);
2032                return true;
2033            case R.id.cancel_transmission:
2034                cancelTransmission(selectedMessage);
2035                return true;
2036            case R.id.retry_decryption:
2037                retryDecryption(selectedMessage);
2038                return true;
2039            case R.id.block_media:
2040                new AlertDialog.Builder(activity)
2041                    .setTitle(R.string.block_media)
2042                    .setMessage("Do you really want to block this media in all messages?")
2043                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2044                        List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2045                        if (thumbs != null && !thumbs.isEmpty()) {
2046                            for (Element thumb : thumbs) {
2047                                Uri uri = Uri.parse(thumb.getAttribute("uri"));
2048                                if (uri.getScheme().equals("cid")) {
2049                                    Cid cid = BobTransfer.cid(uri);
2050                                    if (cid == null) continue;
2051                                    DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2052                                    activity.xmppConnectionService.blockMedia(f);
2053                                    activity.xmppConnectionService.evictPreview(f);
2054                                    f.delete();
2055                                }
2056                            }
2057                        }
2058                        File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
2059                        activity.xmppConnectionService.blockMedia(f);
2060                        activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
2061                        activity.xmppConnectionService.evictPreview(f);
2062                        activity.xmppConnectionService.updateMessage(selectedMessage, false);
2063                        activity.onConversationsListItemUpdated();
2064                        refresh();
2065                    })
2066                    .setNegativeButton(R.string.no, null).show();
2067                return true;
2068            case R.id.delete_file:
2069                deleteFile(selectedMessage);
2070                return true;
2071            case R.id.show_error_message:
2072                showErrorMessage(selectedMessage);
2073                return true;
2074            case R.id.open_with:
2075                openWith(selectedMessage);
2076                return true;
2077            case R.id.only_this_thread:
2078                conversation.setLockThread(true);
2079                backPressedLeaveSingleThread.setEnabled(true);
2080                setThread(selectedMessage.getThread());
2081                refresh();
2082                return true;
2083            case R.id.action_report_and_block:
2084                reportMessage(selectedMessage);
2085                return true;
2086            case R.id.action_add_reaction:
2087                addReaction(selectedMessage);
2088                return true;
2089            default:
2090                return onOptionsItemSelected(item);
2091        }
2092    }
2093
2094    @Override
2095    public boolean onOptionsItemSelected(final MenuItem item) {
2096        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
2097            return false;
2098        } else if (conversation == null) {
2099            return super.onOptionsItemSelected(item);
2100        }
2101        switch (item.getItemId()) {
2102            case R.id.encryption_choice_axolotl:
2103            case R.id.encryption_choice_pgp:
2104            case R.id.encryption_choice_none:
2105                handleEncryptionSelection(item);
2106                break;
2107            case R.id.attach_choose_picture:
2108            case R.id.attach_take_picture:
2109            case R.id.attach_record_video:
2110            case R.id.attach_choose_file:
2111            case R.id.attach_record_voice:
2112            case R.id.attach_location:
2113                handleAttachmentSelection(item);
2114                break;
2115            case R.id.attach_webxdc:
2116                final Intent intent = new Intent(getActivity(), WebxdcStore.class);
2117                startActivityForResult(intent, REQUEST_WEBXDC_STORE);
2118                break;
2119            case R.id.attach_subject:
2120                binding.textinputSubject.setVisibility(binding.textinputSubject.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
2121                break;
2122            case R.id.attach_schedule:
2123                scheduleMessage();
2124                break;
2125            case R.id.action_search:
2126                startSearch();
2127                break;
2128            case R.id.action_archive:
2129                activity.xmppConnectionService.archiveConversation(conversation);
2130                break;
2131            case R.id.action_contact_details:
2132                activity.switchToContactDetails(conversation.getContact());
2133                break;
2134            case R.id.action_muc_details:
2135                ConferenceDetailsActivity.open(activity, conversation);
2136                break;
2137            case R.id.action_invite:
2138                startActivityForResult(
2139                        ChooseContactActivity.create(activity, conversation),
2140                        REQUEST_INVITE_TO_CONVERSATION);
2141                break;
2142            case R.id.action_clear_history:
2143                clearHistoryDialog(conversation);
2144                break;
2145            case R.id.action_mute:
2146                muteConversationDialog(conversation);
2147                break;
2148            case R.id.action_unmute:
2149                unMuteConversation(conversation);
2150                break;
2151            case R.id.action_block:
2152            case R.id.action_unblock:
2153                BlockContactDialog.show(activity, conversation);
2154                break;
2155            case R.id.action_audio_call:
2156                checkPermissionAndTriggerAudioCall();
2157                break;
2158            case R.id.action_video_call:
2159                checkPermissionAndTriggerVideoCall();
2160                break;
2161            case R.id.action_ongoing_call:
2162                returnToOngoingCall();
2163                break;
2164            case R.id.action_toggle_pinned:
2165                togglePinned();
2166                break;
2167            case R.id.action_add_shortcut:
2168                addShortcut();
2169                break;
2170            case R.id.action_block_avatar:
2171                new AlertDialog.Builder(activity)
2172                    .setTitle(R.string.block_media)
2173                    .setMessage("Do you really want to block this avatar?")
2174                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2175                            activity.xmppConnectionService.blockMedia(activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()));
2176                            activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()).delete();
2177                            activity.avatarService().clear(conversation);
2178                            conversation.getContact().setAvatar(null);
2179                            activity.xmppConnectionService.updateConversationUi();
2180                    })
2181                    .setNegativeButton(R.string.no, null).show();
2182            case R.id.action_refresh_feature_discovery:
2183                refreshFeatureDiscovery();
2184                break;
2185            default:
2186                break;
2187        }
2188        return super.onOptionsItemSelected(item);
2189    }
2190
2191    public boolean onBackPressed() {
2192        boolean wasLocked = conversation.getLockThread();
2193        conversation.setLockThread(false);
2194        backPressedLeaveSingleThread.setEnabled(false);
2195        if (wasLocked) {
2196            setThread(null);
2197            conversation.setUserSelectedThread(false);
2198            refresh();
2199            updateThreadFromLastMessage();
2200            return true;
2201        }
2202        return false;
2203    }
2204
2205    private void startSearch() {
2206        final Intent intent = new Intent(getActivity(), SearchActivity.class);
2207        intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
2208        startActivity(intent);
2209    }
2210
2211    private void scheduleMessage() {
2212        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
2213            final var datePicker = com.google.android.material.datepicker.MaterialDatePicker.Builder.datePicker()
2214                .setTitleText("Schedule Message")
2215                .setSelection(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2216                .setCalendarConstraints(
2217                    new com.google.android.material.datepicker.CalendarConstraints.Builder()
2218                        .setStart(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2219                        .build()
2220                 )
2221                .build();
2222            datePicker.addOnPositiveButtonClickListener((date) -> {
2223                final Calendar now = Calendar.getInstance();
2224                final var timePicker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
2225                    .setTitleText("Schedule Message")
2226                    .setHour(now.get(Calendar.HOUR_OF_DAY))
2227                    .setMinute(now.get(Calendar.MINUTE))
2228                    .setTimeFormat(android.text.format.DateFormat.is24HourFormat(activity) ? com.google.android.material.timepicker.TimeFormat.CLOCK_24H : com.google.android.material.timepicker.TimeFormat.CLOCK_12H)
2229                    .build();
2230                timePicker.addOnPositiveButtonClickListener((v2) -> {
2231                        final var dateCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
2232                        dateCal.setTimeInMillis(date);
2233                        final var time = Calendar.getInstance();
2234                        time.set(dateCal.get(Calendar.YEAR), dateCal.get(Calendar.MONTH), dateCal.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0);
2235                        final long timestamp = time.getTimeInMillis();
2236                        sendMessage(timestamp);
2237                        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": scheduled message for " + timestamp);
2238                    });
2239                timePicker.show(activity.getSupportFragmentManager(), "schedulMessageTime");
2240            });
2241            datePicker.show(activity.getSupportFragmentManager(), "schedulMessageDate");
2242        }
2243    }
2244
2245    private void returnToOngoingCall() {
2246        final Optional<OngoingRtpSession> ongoingRtpSession =
2247                activity.xmppConnectionService
2248                        .getJingleConnectionManager()
2249                        .getOngoingRtpConnection(conversation.getContact());
2250        if (ongoingRtpSession.isPresent()) {
2251            final OngoingRtpSession id = ongoingRtpSession.get();
2252            final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
2253            intent.setAction(Intent.ACTION_VIEW);
2254            intent.putExtra(
2255                    RtpSessionActivity.EXTRA_ACCOUNT,
2256                    id.getAccount().getJid().asBareJid().toEscapedString());
2257            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
2258            if (id instanceof AbstractJingleConnection) {
2259                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2260                startActivity(intent);
2261            } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
2262                if (Media.audioOnly(proposal.media)) {
2263                    intent.putExtra(
2264                            RtpSessionActivity.EXTRA_LAST_ACTION,
2265                            RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2266                } else {
2267                    intent.putExtra(
2268                            RtpSessionActivity.EXTRA_LAST_ACTION,
2269                            RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2270                }
2271                intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
2272                startActivity(intent);
2273            }
2274        }
2275    }
2276
2277    private void refreshFeatureDiscovery() {
2278        Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
2279        if (presences.isEmpty()) {
2280            presences = new HashSet<>();
2281            presences.add(new AbstractMap.SimpleEntry("", null));
2282        }
2283        for (Map.Entry<String, Presence> entry : presences) {
2284            Jid jid = conversation.getContact().getJid();
2285            if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
2286            activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
2287                if (activity == null) return;
2288                activity.runOnUiThread(() -> {
2289                    refresh();
2290                    refreshCommands(true);
2291                });
2292            });
2293        }
2294    }
2295
2296    private void addShortcut() {
2297        ShortcutInfoCompat info;
2298        if (conversation.getMode() == Conversation.MODE_MULTI) {
2299            info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getMucOptions());
2300        } else {
2301            info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
2302        }
2303        ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2304    }
2305
2306    private void togglePinned() {
2307        final boolean pinned =
2308                conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2309        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2310        activity.xmppConnectionService.updateConversation(conversation);
2311        activity.invalidateOptionsMenu();
2312    }
2313
2314    private void checkPermissionAndTriggerAudioCall() {
2315        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2316            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2317            return;
2318        }
2319        final List<String> permissions;
2320        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2321            permissions =
2322                    Arrays.asList(
2323                            Manifest.permission.RECORD_AUDIO,
2324                            Manifest.permission.BLUETOOTH_CONNECT);
2325        } else {
2326            permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2327        }
2328        if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2329            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2330        }
2331    }
2332
2333    private void checkPermissionAndTriggerVideoCall() {
2334        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2335            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2336            return;
2337        }
2338        final List<String> permissions;
2339        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2340            permissions =
2341                    Arrays.asList(
2342                            Manifest.permission.RECORD_AUDIO,
2343                            Manifest.permission.CAMERA,
2344                            Manifest.permission.BLUETOOTH_CONNECT);
2345        } else {
2346            permissions =
2347                    Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2348        }
2349        if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2350            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2351        }
2352    }
2353
2354    private void triggerRtpSession(final String action) {
2355        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
2356            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2357                    .show();
2358            return;
2359        }
2360        final Account account = conversation.getAccount();
2361        if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2362            activity.xmppConnectionService.updateAccount(account);
2363        }
2364        final Contact contact = conversation.getContact();
2365        if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
2366            triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2367        } else {
2368            final RtpCapability.Capability capability;
2369            if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2370                capability = RtpCapability.Capability.VIDEO;
2371            } else {
2372                capability = RtpCapability.Capability.AUDIO;
2373            }
2374            PresenceSelector.selectFullJidForDirectRtpConnection(
2375                    activity,
2376                    contact,
2377                    capability,
2378                    fullJid -> {
2379                        triggerRtpSession(contact.getAccount(), fullJid, action);
2380                    });
2381        }
2382    }
2383
2384    private void triggerRtpSession(final Account account, final Jid with, final String action) {
2385        CallIntegrationConnectionService.placeCall(activity.xmppConnectionService, account,with,RtpSessionActivity.actionToMedia(action));
2386    }
2387
2388    private void handleAttachmentSelection(MenuItem item) {
2389        switch (item.getItemId()) {
2390            case R.id.attach_choose_picture:
2391                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2392                break;
2393            case R.id.attach_take_picture:
2394                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2395                break;
2396            case R.id.attach_record_video:
2397                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2398                break;
2399            case R.id.attach_choose_file:
2400                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2401                break;
2402            case R.id.attach_record_voice:
2403                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2404                break;
2405            case R.id.attach_location:
2406                attachFile(ATTACHMENT_CHOICE_LOCATION);
2407                break;
2408        }
2409    }
2410
2411    private void handleEncryptionSelection(MenuItem item) {
2412        if (conversation == null) {
2413            return;
2414        }
2415        final boolean updated;
2416        switch (item.getItemId()) {
2417            case R.id.encryption_choice_none:
2418                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2419                item.setChecked(true);
2420                break;
2421            case R.id.encryption_choice_pgp:
2422                if (activity.hasPgp()) {
2423                    if (conversation.getAccount().getPgpSignature() != null) {
2424                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2425                        item.setChecked(true);
2426                    } else {
2427                        updated = false;
2428                        activity.announcePgp(
2429                                conversation.getAccount(),
2430                                conversation,
2431                                null,
2432                                activity.onOpenPGPKeyPublished);
2433                    }
2434                } else {
2435                    activity.showInstallPgpDialog();
2436                    updated = false;
2437                }
2438                break;
2439            case R.id.encryption_choice_axolotl:
2440                Log.d(
2441                        Config.LOGTAG,
2442                        AxolotlService.getLogprefix(conversation.getAccount())
2443                                + "Enabled axolotl for Contact "
2444                                + conversation.getContact().getJid());
2445                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2446                item.setChecked(true);
2447                break;
2448            default:
2449                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2450                break;
2451        }
2452        if (updated) {
2453            activity.xmppConnectionService.updateConversation(conversation);
2454        }
2455        updateChatMsgHint();
2456        getActivity().invalidateOptionsMenu();
2457        activity.refreshUi();
2458    }
2459
2460    public void attachFile(final int attachmentChoice) {
2461        attachFile(attachmentChoice, true);
2462    }
2463
2464    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2465        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2466            if (!hasPermissions(
2467                    attachmentChoice,
2468                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2469                    Manifest.permission.RECORD_AUDIO)) {
2470                return;
2471            }
2472        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2473                || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
2474            if (!hasPermissions(
2475                    attachmentChoice,
2476                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2477                    Manifest.permission.CAMERA)) {
2478                return;
2479            }
2480        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2481            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2482                return;
2483            }
2484        }
2485        if (updateRecentlyUsed) {
2486            storeRecentlyUsedQuickAction(attachmentChoice);
2487        }
2488        final int encryption = conversation.getNextEncryption();
2489        final int mode = conversation.getMode();
2490        if (encryption == Message.ENCRYPTION_PGP) {
2491            if (activity.hasPgp()) {
2492                if (mode == Conversation.MODE_SINGLE
2493                        && conversation.getContact().getPgpKeyId() != 0) {
2494                    activity.xmppConnectionService
2495                            .getPgpEngine()
2496                            .hasKey(
2497                                    conversation.getContact(),
2498                                    new UiCallback<Contact>() {
2499
2500                                        @Override
2501                                        public void userInputRequired(
2502                                                PendingIntent pi, Contact contact) {
2503                                            startPendingIntent(pi, attachmentChoice);
2504                                        }
2505
2506                                        @Override
2507                                        public void success(Contact contact) {
2508                                            invokeAttachFileIntent(attachmentChoice);
2509                                        }
2510
2511                                        @Override
2512                                        public void error(int error, Contact contact) {
2513                                            activity.replaceToast(getString(error));
2514                                        }
2515                                    });
2516                } else if (mode == Conversation.MODE_MULTI
2517                        && conversation.getMucOptions().pgpKeysInUse()) {
2518                    if (!conversation.getMucOptions().everybodyHasKeys()) {
2519                        Toast warning =
2520                                Toast.makeText(
2521                                        getActivity(),
2522                                        R.string.missing_public_keys,
2523                                        Toast.LENGTH_LONG);
2524                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2525                        warning.show();
2526                    }
2527                    invokeAttachFileIntent(attachmentChoice);
2528                } else {
2529                    showNoPGPKeyDialog(
2530                            false,
2531                            (dialog, which) -> {
2532                                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2533                                activity.xmppConnectionService.updateConversation(conversation);
2534                                invokeAttachFileIntent(attachmentChoice);
2535                            });
2536                }
2537            } else {
2538                activity.showInstallPgpDialog();
2539            }
2540        } else {
2541            invokeAttachFileIntent(attachmentChoice);
2542        }
2543    }
2544
2545    private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2546        try {
2547            activity.getPreferences()
2548                    .edit()
2549                    .putString(
2550                            RECENTLY_USED_QUICK_ACTION,
2551                            SendButtonAction.of(attachmentChoice).toString())
2552                    .apply();
2553        } catch (IllegalArgumentException e) {
2554            // just do not save
2555        }
2556    }
2557
2558    @Override
2559    public void onRequestPermissionsResult(
2560            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2561        final PermissionUtils.PermissionResult permissionResult =
2562                PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2563        if (grantResults.length > 0) {
2564            if (allGranted(permissionResult.grantResults)) {
2565                switch (requestCode) {
2566                    case REQUEST_START_DOWNLOAD:
2567                        if (this.mPendingDownloadableMessage != null) {
2568                            startDownloadable(this.mPendingDownloadableMessage);
2569                        }
2570                        break;
2571                    case REQUEST_ADD_EDITOR_CONTENT:
2572                        if (this.mPendingEditorContent != null) {
2573                            attachEditorContentToConversation(this.mPendingEditorContent);
2574                        }
2575                        break;
2576                    case REQUEST_COMMIT_ATTACHMENTS:
2577                        commitAttachments();
2578                        break;
2579                    case REQUEST_START_AUDIO_CALL:
2580                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2581                        break;
2582                    case REQUEST_START_VIDEO_CALL:
2583                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2584                        break;
2585                    default:
2586                        attachFile(requestCode);
2587                        break;
2588                }
2589            } else {
2590                @StringRes int res;
2591                String firstDenied =
2592                        getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2593                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2594                    res = R.string.no_microphone_permission;
2595                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2596                    res = R.string.no_camera_permission;
2597                } else {
2598                    res = R.string.no_storage_permission;
2599                }
2600                Toast.makeText(
2601                                getActivity(),
2602                                getString(res, getString(R.string.app_name)),
2603                                Toast.LENGTH_SHORT)
2604                        .show();
2605            }
2606        }
2607        if (writeGranted(grantResults, permissions)) {
2608            if (activity != null && activity.xmppConnectionService != null) {
2609                activity.xmppConnectionService.getDrawableCache().evictAll();
2610                activity.xmppConnectionService.restartFileObserver();
2611            }
2612            refresh();
2613        }
2614        if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2615            XmppConnectionService.toggleForegroundService(activity);
2616        }
2617    }
2618
2619    public void startDownloadable(Message message) {
2620        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2621            this.mPendingDownloadableMessage = message;
2622            return;
2623        }
2624        Transferable transferable = message.getTransferable();
2625        if (transferable != null) {
2626            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2627                createNewConnection(message);
2628                return;
2629            }
2630            if (!transferable.start()) {
2631                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2632                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2633                        .show();
2634            }
2635        } else if (message.treatAsDownloadable()
2636                || message.hasFileOnRemoteHost()
2637                || MessageUtils.unInitiatedButKnownSize(message)) {
2638            createNewConnection(message);
2639        } else {
2640            Log.d(
2641                    Config.LOGTAG,
2642                    message.getConversation().getAccount() + ": unable to start downloadable");
2643        }
2644    }
2645
2646    private void createNewConnection(final Message message) {
2647        if (!activity.xmppConnectionService.hasInternetConnection()) {
2648            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2649                    .show();
2650            return;
2651        }
2652        if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2653            try {
2654                BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2655                message.setTransferable(transfer);
2656                transfer.start();
2657            } catch (URISyntaxException e) {
2658                Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2659            }
2660        } else {
2661            activity.xmppConnectionService
2662                    .getHttpConnectionManager()
2663                    .createNewDownloadConnection(message, true);
2664        }
2665    }
2666
2667    @SuppressLint("InflateParams")
2668    protected void clearHistoryDialog(final Conversation conversation) {
2669        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2670        builder.setTitle(R.string.clear_conversation_history);
2671        final View dialogView =
2672                requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2673        final CheckBox endConversationCheckBox =
2674                dialogView.findViewById(R.id.end_conversation_checkbox);
2675        builder.setView(dialogView);
2676        builder.setNegativeButton(getString(R.string.cancel), null);
2677        builder.setPositiveButton(
2678                getString(R.string.confirm),
2679                (dialog, which) -> {
2680                    this.activity.xmppConnectionService.clearConversationHistory(conversation);
2681                    if (endConversationCheckBox.isChecked()) {
2682                        this.activity.xmppConnectionService.archiveConversation(conversation);
2683                        this.activity.onConversationArchived(conversation);
2684                    } else {
2685                        activity.onConversationsListItemUpdated();
2686                        refresh();
2687                    }
2688                });
2689        builder.create().show();
2690    }
2691
2692    protected void muteConversationDialog(final Conversation conversation) {
2693        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2694        builder.setTitle(R.string.disable_notifications);
2695        final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2696        final CharSequence[] labels = new CharSequence[durations.length];
2697        for (int i = 0; i < durations.length; ++i) {
2698            if (durations[i] == -1) {
2699                labels[i] = activity.getString(R.string.until_further_notice);
2700            } else {
2701                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2702            }
2703        }
2704        builder.setItems(
2705                labels,
2706                (dialog, which) -> {
2707                    final long till;
2708                    if (durations[which] == -1) {
2709                        till = Long.MAX_VALUE;
2710                    } else {
2711                        till = System.currentTimeMillis() + (durations[which] * 1000L);
2712                    }
2713                    conversation.setMutedTill(till);
2714                    activity.xmppConnectionService.updateConversation(conversation);
2715                    activity.onConversationsListItemUpdated();
2716                    refresh();
2717                    activity.invalidateOptionsMenu();
2718                });
2719        builder.create().show();
2720    }
2721
2722    private boolean hasPermissions(int requestCode, List<String> permissions) {
2723        final List<String> missingPermissions = new ArrayList<>();
2724        for (String permission : permissions) {
2725            if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU || Config.ONLY_INTERNAL_STORAGE) && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2726                continue;
2727            }
2728            if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2729                missingPermissions.add(permission);
2730            }
2731        }
2732        if (missingPermissions.size() == 0) {
2733            return true;
2734        } else {
2735            requestPermissions(
2736                    missingPermissions.toArray(new String[0]),
2737                    requestCode);
2738            return false;
2739        }
2740    }
2741
2742    private boolean hasPermissions(int requestCode, String... permissions) {
2743        return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2744    }
2745
2746    public void unMuteConversation(final Conversation conversation) {
2747        conversation.setMutedTill(0);
2748        this.activity.xmppConnectionService.updateConversation(conversation);
2749        this.activity.onConversationsListItemUpdated();
2750        refresh();
2751        this.activity.invalidateOptionsMenu();
2752    }
2753
2754    protected void invokeAttachFileIntent(final int attachmentChoice) {
2755        Intent intent = new Intent();
2756        boolean chooser = false;
2757        switch (attachmentChoice) {
2758            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2759                intent.setAction(Intent.ACTION_GET_CONTENT);
2760                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2761                intent.setType("image/*");
2762                chooser = true;
2763                break;
2764            case ATTACHMENT_CHOICE_RECORD_VIDEO:
2765                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2766                break;
2767            case ATTACHMENT_CHOICE_TAKE_PHOTO:
2768                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2769                pendingTakePhotoUri.push(uri);
2770                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2771                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2772                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2773                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2774                break;
2775            case ATTACHMENT_CHOICE_CHOOSE_FILE:
2776                chooser = true;
2777                intent.setType("*/*");
2778                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2779                intent.addCategory(Intent.CATEGORY_OPENABLE);
2780                intent.setAction(Intent.ACTION_GET_CONTENT);
2781                break;
2782            case ATTACHMENT_CHOICE_RECORD_VOICE:
2783                intent = new Intent(getActivity(), RecordingActivity.class);
2784                break;
2785            case ATTACHMENT_CHOICE_LOCATION:
2786                intent = GeoHelper.getFetchIntent(activity);
2787                break;
2788        }
2789        final Context context = getActivity();
2790        if (context == null) {
2791            return;
2792        }
2793        try {
2794            if (chooser) {
2795                startActivityForResult(
2796                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
2797                        attachmentChoice);
2798            } else {
2799                startActivityForResult(intent, attachmentChoice);
2800            }
2801        } catch (final ActivityNotFoundException e) {
2802            Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2803        }
2804    }
2805
2806    @Override
2807    public void onResume() {
2808        super.onResume();
2809        binding.messagesView.post(this::fireReadEvent);
2810    }
2811
2812    private void fireReadEvent() {
2813        if (activity != null && this.conversation != null) {
2814            String uuid = getLastVisibleMessageUuid();
2815            if (uuid != null) {
2816                activity.onConversationRead(this.conversation, uuid);
2817            }
2818        }
2819    }
2820
2821    private void newSubThread() {
2822        Element oldThread = conversation.getThread();
2823        Element thread = new Element("thread", "jabber:client");
2824        thread.setContent(UUID.randomUUID().toString());
2825        if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2826        setThread(thread);
2827    }
2828
2829    private void newThread() {
2830        Element thread = new Element("thread", "jabber:client");
2831        thread.setContent(UUID.randomUUID().toString());
2832        setThread(thread);
2833    }
2834
2835    private void updateThreadFromLastMessage() {
2836        if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2837            Message message = getLastVisibleMessage();
2838            if (message == null) {
2839                newThread();
2840            } else {
2841                if (conversation.getMode() == Conversation.MODE_MULTI) {
2842                    if (activity == null || activity.xmppConnectionService == null) return;
2843                    if (message.getStatus() < Message.STATUS_SEND) {
2844                        if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2845                    }
2846                }
2847
2848                setThread(message.getThread());
2849            }
2850        }
2851    }
2852
2853    private String getLastVisibleMessageUuid() {
2854        Message message =  getLastVisibleMessage();
2855        return message == null ? null : message.getUuid();
2856    }
2857
2858    private Message getLastVisibleMessage() {
2859        if (binding == null) {
2860            return null;
2861        }
2862        synchronized (this.messageList) {
2863            int pos = binding.messagesView.getLastVisiblePosition();
2864            if (pos >= 0) {
2865                Message message = null;
2866                for (int i = pos; i >= 0; --i) {
2867                    try {
2868                        message = (Message) binding.messagesView.getItemAtPosition(i);
2869                    } catch (IndexOutOfBoundsException e) {
2870                        // should not happen if we synchronize properly. however if that fails we
2871                        // just gonna try item -1
2872                        continue;
2873                    }
2874                    if (message.getType() != Message.TYPE_STATUS) {
2875                        break;
2876                    }
2877                }
2878                if (message != null) {
2879                    while (message.next() != null && message.next().wasMergedIntoPrevious(activity == null ? null : activity.xmppConnectionService)) {
2880                        message = message.next();
2881                    }
2882                    return message;
2883                }
2884            }
2885        }
2886        return null;
2887    }
2888
2889    public void jumpTo(final Message message) {
2890        if (message.getUuid() == null) return;
2891        for (int i = 0; i < messageList.size(); i++) {
2892            final var m = messageList.get(i);
2893            if (m == null) continue;
2894            if (message.getUuid().equals(m.getUuid())) {
2895                binding.messagesView.setSelection(i);
2896                return;
2897            }
2898        }
2899    }
2900
2901    private void openWith(final Message message) {
2902        if (message.isGeoUri()) {
2903            GeoHelper.view(getActivity(), message);
2904        } else {
2905            final DownloadableFile file =
2906                    activity.xmppConnectionService.getFileBackend().getFile(message);
2907            ViewUtil.view(activity, file);
2908        }
2909    }
2910
2911    private void addReaction(final Message message) {
2912        activity.addReaction(message, reactions -> activity.xmppConnectionService.sendReactions(message, reactions));
2913    }
2914
2915    private void reportMessage(final Message message) {
2916        BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
2917    }
2918
2919    private void showErrorMessage(final Message message) {
2920        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2921        builder.setTitle(R.string.error_message);
2922        final String errorMessage = message.getErrorMessage();
2923        final String[] errorMessageParts =
2924                errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2925        final String displayError;
2926        if (errorMessageParts.length == 2) {
2927            displayError = errorMessageParts[1];
2928        } else {
2929            displayError = errorMessage;
2930        }
2931        builder.setMessage(displayError);
2932        builder.setNegativeButton(
2933                R.string.copy_to_clipboard,
2934                (dialog, which) -> {
2935                    activity.copyTextToClipboard(displayError, R.string.error_message);
2936                    Toast.makeText(
2937                                    activity,
2938                                    R.string.error_message_copied_to_clipboard,
2939                                    Toast.LENGTH_SHORT)
2940                            .show();
2941                });
2942        builder.setPositiveButton(R.string.confirm, null);
2943        builder.create().show();
2944    }
2945
2946    public boolean onInlineImageLongClicked(Cid cid) {
2947        DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2948        if (f == null) return false;
2949
2950        saveAsSticker(f, null);
2951        return true;
2952    }
2953
2954    private void saveAsSticker(final Message m) {
2955        String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
2956        existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
2957        saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
2958    }
2959
2960    private void saveAsSticker(final File file, final String name) {
2961        savingAsSticker = file;
2962
2963        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
2964        intent.addCategory(Intent.CATEGORY_OPENABLE);
2965        intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
2966        intent.putExtra(Intent.EXTRA_TITLE, name);
2967
2968        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2969        final String dir = p.getString("sticker_directory", "Stickers");
2970        if (dir.startsWith("content://")) {
2971            intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
2972        } else {
2973            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
2974            Uri uri;
2975            if (Build.VERSION.SDK_INT >= 29) {
2976                Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
2977                uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
2978                uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
2979            } else {
2980                uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
2981            }
2982            intent.putExtra("android.provider.extra.INITIAL_URI", uri);
2983            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
2984        }
2985
2986        Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
2987        startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
2988    }
2989
2990    private void deleteFile(final Message message) {
2991        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2992        builder.setNegativeButton(R.string.cancel, null);
2993        builder.setTitle(R.string.delete_file_dialog);
2994        builder.setMessage(R.string.delete_file_dialog_msg);
2995        builder.setPositiveButton(
2996                R.string.confirm,
2997                (dialog, which) -> {
2998                    List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2999                    if (thumbs != null && !thumbs.isEmpty()) {
3000                        for (Element thumb : thumbs) {
3001                            Uri uri = Uri.parse(thumb.getAttribute("uri"));
3002                            if (uri.getScheme().equals("cid")) {
3003                                Cid cid = BobTransfer.cid(uri);
3004                                if (cid == null) continue;
3005                                DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3006                                activity.xmppConnectionService.evictPreview(f);
3007                                f.delete();
3008                            }
3009                        }
3010                    }
3011                    if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
3012                        activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
3013                        activity.xmppConnectionService.updateMessage(message, false);
3014                        activity.onConversationsListItemUpdated();
3015                        refresh();
3016                    }
3017                });
3018        builder.create().show();
3019    }
3020
3021    private void resendMessage(final Message message) {
3022        if (message.isFileOrImage()) {
3023            if (!(message.getConversation() instanceof Conversation)) {
3024                return;
3025            }
3026            final Conversation conversation = (Conversation) message.getConversation();
3027            final DownloadableFile file =
3028                    activity.xmppConnectionService.getFileBackend().getFile(message);
3029            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
3030                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
3031                if (!message.hasFileOnRemoteHost()
3032                        && xmppConnection != null
3033                        && conversation.getMode() == Conversational.MODE_SINGLE
3034                        && !xmppConnection
3035                                .getFeatures()
3036                                .httpUpload(message.getFileParams().getSize())) {
3037                    activity.selectPresence(
3038                            conversation,
3039                            () -> {
3040                                message.setCounterpart(conversation.getNextCounterpart());
3041                                activity.xmppConnectionService.resendFailedMessages(message);
3042                                new Handler()
3043                                        .post(
3044                                                () -> {
3045                                                    int size = messageList.size();
3046                                                    this.binding.messagesView.setSelection(
3047                                                            size - 1);
3048                                                });
3049                            });
3050                    return;
3051                }
3052            } else if (!Compatibility.hasStoragePermission(getActivity())) {
3053                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
3054                return;
3055            } else {
3056                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
3057                message.setDeleted(true);
3058                activity.xmppConnectionService.updateMessage(message, false);
3059                activity.onConversationsListItemUpdated();
3060                refresh();
3061                return;
3062            }
3063        }
3064        activity.xmppConnectionService.resendFailedMessages(message);
3065        new Handler()
3066                .post(
3067                        () -> {
3068                            int size = messageList.size();
3069                            this.binding.messagesView.setSelection(size - 1);
3070                        });
3071    }
3072
3073    private void cancelTransmission(Message message) {
3074        Transferable transferable = message.getTransferable();
3075        if (transferable != null) {
3076            transferable.cancel();
3077        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
3078            activity.xmppConnectionService.markMessage(
3079                    message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
3080        }
3081    }
3082
3083    private void retryDecryption(Message message) {
3084        message.setEncryption(Message.ENCRYPTION_PGP);
3085        activity.onConversationsListItemUpdated();
3086        refresh();
3087        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
3088    }
3089
3090    public void privateMessageWith(final Jid counterpart) {
3091        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3092            activity.xmppConnectionService.sendChatState(conversation);
3093        }
3094        this.binding.textinput.setText("");
3095        this.conversation.setNextCounterpart(counterpart);
3096        updateChatMsgHint();
3097        updateSendButton();
3098        updateEditablity();
3099    }
3100
3101    private void correctMessage(Message message) {
3102        while (message.mergeable(message.next())) {
3103            message = message.next();
3104        }
3105        setThread(message.getThread());
3106        conversation.setUserSelectedThread(true);
3107        this.conversation.setCorrectingMessage(message);
3108        final Editable editable = binding.textinput.getText();
3109        this.conversation.setDraftMessage(editable.toString());
3110        this.binding.textinput.setText("");
3111        this.binding.textinput.append(message.getBody(true));
3112        if (message.getSubject() != null && message.getSubject().length() > 0) {
3113            this.binding.textinputSubject.setText(message.getSubject());
3114            this.binding.textinputSubject.setVisibility(View.VISIBLE);
3115        }
3116        final var replyTo = message.getInReplyTo();
3117        if (replyTo != null) {
3118            setupReply(replyTo);
3119        }
3120    }
3121
3122    private void highlightInConference(String nick) {
3123        final Editable editable = this.binding.textinput.getText();
3124        String oldString = editable.toString().trim();
3125        final int pos = this.binding.textinput.getSelectionStart();
3126        if (oldString.isEmpty() || pos == 0) {
3127            editable.insert(0, nick + ": ");
3128        } else {
3129            final char before = editable.charAt(pos - 1);
3130            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
3131            if (before == '\n') {
3132                editable.insert(pos, nick + ": ");
3133            } else {
3134                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
3135                    if (NickValidityChecker.check(
3136                            conversation,
3137                            Arrays.asList(
3138                                    editable.subSequence(0, pos - 2).toString().split(", ")))) {
3139                        editable.insert(pos - 2, ", " + nick);
3140                        return;
3141                    }
3142                }
3143                editable.insert(
3144                        pos,
3145                        (Character.isWhitespace(before) ? "" : " ")
3146                                + nick
3147                                + (Character.isWhitespace(after) ? "" : " "));
3148                if (Character.isWhitespace(after)) {
3149                    this.binding.textinput.setSelection(
3150                            this.binding.textinput.getSelectionStart() + 1);
3151                }
3152            }
3153        }
3154    }
3155
3156    @Override
3157    public void startActivityForResult(Intent intent, int requestCode) {
3158        final Activity activity = getActivity();
3159        if (activity instanceof ConversationsActivity) {
3160            ((ConversationsActivity) activity).clearPendingViewIntent();
3161        }
3162        super.startActivityForResult(intent, requestCode);
3163    }
3164
3165    @Override
3166    public void onSaveInstanceState(@NonNull Bundle outState) {
3167        super.onSaveInstanceState(outState);
3168        if (conversation != null) {
3169            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
3170            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
3171            final Uri uri = pendingTakePhotoUri.peek();
3172            if (uri != null) {
3173                outState.putString(STATE_PHOTO_URI, uri.toString());
3174            }
3175            final ScrollState scrollState = getScrollPosition();
3176            if (scrollState != null) {
3177                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
3178            }
3179            final ArrayList<Attachment> attachments =
3180                    mediaPreviewAdapter == null
3181                            ? new ArrayList<>()
3182                            : mediaPreviewAdapter.getAttachments();
3183            if (attachments.size() > 0) {
3184                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
3185            }
3186        }
3187    }
3188
3189    @Override
3190    public void onActivityCreated(Bundle savedInstanceState) {
3191        super.onActivityCreated(savedInstanceState);
3192        if (savedInstanceState == null) {
3193            return;
3194        }
3195        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
3196        ArrayList<Attachment> attachments =
3197                savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
3198        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
3199        if (uuid != null) {
3200            QuickLoader.set(uuid);
3201            this.pendingConversationsUuid.push(uuid);
3202            if (attachments != null && attachments.size() > 0) {
3203                this.pendingMediaPreviews.push(attachments);
3204            }
3205            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
3206            if (takePhotoUri != null) {
3207                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
3208            }
3209            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
3210        }
3211    }
3212
3213    @Override
3214    public void onStart() {
3215        super.onStart();
3216        if (this.reInitRequiredOnStart && this.conversation != null) {
3217            final Bundle extras = pendingExtras.pop();
3218            reInit(this.conversation, extras != null);
3219            if (extras != null) {
3220                processExtras(extras);
3221            }
3222        } else if (conversation == null
3223                && activity != null
3224                && activity.xmppConnectionService != null) {
3225            final String uuid = pendingConversationsUuid.pop();
3226            Log.d(
3227                    Config.LOGTAG,
3228                    "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
3229                            + uuid);
3230            if (uuid != null) {
3231                findAndReInitByUuidOrArchive(uuid);
3232            }
3233        }
3234    }
3235
3236    @Override
3237    public void onStop() {
3238        super.onStop();
3239        final Activity activity = getActivity();
3240        messageListAdapter.unregisterListenerInAudioPlayer();
3241        if (activity == null || !activity.isChangingConfigurations()) {
3242            hideSoftKeyboard(activity);
3243            messageListAdapter.stopAudioPlayer();
3244        }
3245        if (this.conversation != null) {
3246            final String msg = this.binding.textinput.getText().toString();
3247            storeNextMessage(msg);
3248            updateChatState(this.conversation, msg);
3249            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
3250        }
3251        this.reInitRequiredOnStart = true;
3252    }
3253
3254    private void updateChatState(final Conversation conversation, final String msg) {
3255        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
3256        Account.State status = conversation.getAccount().getStatus();
3257        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
3258            activity.xmppConnectionService.sendChatState(conversation);
3259        }
3260    }
3261
3262    private void saveMessageDraftStopAudioPlayer() {
3263        final Conversation previousConversation = this.conversation;
3264        if (this.activity == null || this.binding == null || previousConversation == null) {
3265            return;
3266        }
3267        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
3268        final String msg = this.binding.textinput.getText().toString();
3269        storeNextMessage(msg);
3270        updateChatState(this.conversation, msg);
3271        messageListAdapter.stopAudioPlayer();
3272        mediaPreviewAdapter.clearPreviews();
3273        toggleInputMethod();
3274    }
3275
3276    public void reInit(final Conversation conversation, final Bundle extras) {
3277        QuickLoader.set(conversation.getUuid());
3278        final boolean changedConversation = this.conversation != conversation;
3279        if (changedConversation) {
3280            this.saveMessageDraftStopAudioPlayer();
3281        }
3282        this.clearPending();
3283        if (this.reInit(conversation, extras != null)) {
3284            if (extras != null) {
3285                processExtras(extras);
3286            }
3287            this.reInitRequiredOnStart = false;
3288        } else {
3289            this.reInitRequiredOnStart = true;
3290            pendingExtras.push(extras);
3291        }
3292        resetUnreadMessagesCount();
3293    }
3294
3295    private void reInit(Conversation conversation) {
3296        reInit(conversation, false);
3297    }
3298
3299    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
3300        if (conversation == null) {
3301            return false;
3302        }
3303        final Conversation originalConversation = this.conversation;
3304        this.conversation = conversation;
3305        // once we set the conversation all is good and it will automatically do the right thing in
3306        // onStart()
3307        if (this.activity == null || this.binding == null) {
3308            return false;
3309        }
3310
3311        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3312            activity.onConversationArchived(this.conversation);
3313            return false;
3314        }
3315
3316        final var cursord = activity.getDrawable(R.drawable.cursor_on_tertiary_container);
3317        if (activity.xmppConnectionService != null && activity.xmppConnectionService.getAccounts().size() > 1) {
3318            final var bg = MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorSurface);
3319            final var accountColor = conversation.getAccount().getColor(activity.isDark());
3320            final var colors = MaterialColors.getColorRoles(activity, accountColor);
3321            final var accent = activity.isDark() ? ColorUtils.blendARGB(colors.getAccentContainer(), bg, 1.0f - Math.max(0.25f, Color.alpha(accountColor) / 255.0f)) : colors.getAccentContainer();
3322            cursord.setTintList(ColorStateList.valueOf(colors.getOnAccentContainer()));
3323            binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(accent));
3324            binding.textinputSubject.setTextColor(colors.getOnAccentContainer());
3325            binding.textinput.setTextColor(colors.getOnAccentContainer());
3326            binding.textinputSubject.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3327            binding.textinput.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3328            binding.textInputHint.setTextColor(colors.getOnAccentContainer());
3329        } else {
3330            cursord.setTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer)));
3331            binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.inputLayout, com.google.android.material.R.attr.colorTertiaryContainer)));
3332            binding.textinputSubject.setTextColor(MaterialColors.getColor(binding.textinputSubject, com.google.android.material.R.attr.colorOnTertiaryContainer));
3333            binding.textinput.setTextColor(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer));
3334            binding.textinputSubject.setHintTextColor(R.color.hint_on_tertiary_container);
3335            binding.textinput.setHintTextColor(R.color.hint_on_tertiary_container);
3336            binding.textInputHint.setTextColor(MaterialColors.getColor(binding.textInputHint, com.google.android.material.R.attr.colorOnTertiaryContainer));
3337        }
3338        if (Build.VERSION.SDK_INT >= 29) {
3339            binding.textinputSubject.setTextCursorDrawable(cursord);
3340            binding.textinput.setTextCursorDrawable(cursord);
3341        }
3342
3343        setThread(conversation.getThread());
3344        setupReply(conversation.getReplyTo());
3345
3346        stopScrolling();
3347        Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3348
3349        if (this.conversation.isRead(activity == null ? null : activity.xmppConnectionService) && hasExtras) {
3350            Log.d(Config.LOGTAG, "trimming conversation");
3351            this.conversation.trim();
3352        }
3353
3354        setupIme();
3355
3356        final boolean scrolledToBottomAndNoPending =
3357                this.scrolledToBottom() && pendingScrollState.peek() == null;
3358
3359        this.binding.textSendButton.setContentDescription(
3360                activity.getString(R.string.send_message_to_x, conversation.getName()));
3361        this.binding.textinput.setKeyboardListener(null);
3362        this.binding.textinputSubject.setKeyboardListener(null);
3363        final boolean participating =
3364                conversation.getMode() == Conversational.MODE_SINGLE
3365                        || conversation.getMucOptions().participating();
3366        if (participating) {
3367            this.binding.textinput.setText(this.conversation.getNextMessage());
3368            this.binding.textinput.setSelection(this.binding.textinput.length());
3369        } else {
3370            this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3371        }
3372        this.binding.textinput.setKeyboardListener(this);
3373        this.binding.textinputSubject.setKeyboardListener(this);
3374        messageListAdapter.updatePreferences();
3375        refresh(false);
3376        activity.invalidateOptionsMenu();
3377        this.conversation.messagesLoaded.set(true);
3378        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3379
3380        if (hasExtras || scrolledToBottomAndNoPending) {
3381            resetUnreadMessagesCount();
3382            synchronized (this.messageList) {
3383                Log.d(Config.LOGTAG, "jump to first unread message");
3384                final Message first = conversation.getFirstUnreadMessage();
3385                final int bottom = Math.max(0, this.messageList.size() - 1);
3386                final int pos;
3387                final boolean jumpToBottom;
3388                if (first == null) {
3389                    pos = bottom;
3390                    jumpToBottom = true;
3391                } else {
3392                    int i = getIndexOf(first.getUuid(), this.messageList);
3393                    pos = i < 0 ? bottom : i;
3394                    jumpToBottom = false;
3395                }
3396                setSelection(pos, jumpToBottom);
3397            }
3398        }
3399
3400        this.binding.messagesView.post(this::fireReadEvent);
3401        // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3402        // layout which might be unnecessary since we can *see* it
3403        activity.xmppConnectionService
3404                .getNotificationService()
3405                .setOpenConversation(this.conversation);
3406
3407        if (commandAdapter != null && conversation != originalConversation) {
3408            commandAdapter.clear();
3409            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3410            refreshCommands(false);
3411        }
3412        if (commandAdapter == null && conversation != null) {
3413            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3414            commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3415            binding.commandsView.setAdapter(commandAdapter);
3416            binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3417                if (activity == null) return;
3418
3419                commandAdapter.getItem(position).start(activity, ConversationFragment.this.conversation);
3420            });
3421            refreshCommands(false);
3422        }
3423
3424        binding.commandsNote.setVisibility(activity.xmppConnectionService.isOnboarding() ? View.VISIBLE : View.GONE);
3425
3426        return true;
3427    }
3428
3429    @Override
3430    public void refreshForNewCaps(final Set<Jid> newCapsJids) {
3431        if (newCapsJids.isEmpty() || (conversation != null && newCapsJids.contains(conversation.getJid().asBareJid()))) {
3432            refreshCommands(true);
3433        }
3434    }
3435
3436    protected void refreshCommands(boolean delayShow) {
3437        if (commandAdapter == null) return;
3438
3439        final CommandAdapter.MucConfig mucConfig =
3440            conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER) ?
3441            new CommandAdapter.MucConfig() :
3442            null;
3443
3444        Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3445        if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3446            commandJid = conversation.getJid().asBareJid();
3447        }
3448        if (commandJid == null && conversation.getJid().isDomainJid()) {
3449            commandJid = conversation.getJid();
3450        }
3451        if (commandJid == null) {
3452            binding.commandsViewProgressbar.setVisibility(View.GONE);
3453            if (mucConfig == null) {
3454                conversation.hideViewPager();
3455            } else {
3456                commandAdapter.clear();
3457                commandAdapter.add(mucConfig);
3458                conversation.showViewPager();
3459            }
3460        } else {
3461            if (!delayShow) conversation.showViewPager();
3462            binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3463            activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (iq) -> {
3464                if (activity == null) return;
3465
3466                activity.runOnUiThread(() -> {
3467                    binding.commandsViewProgressbar.setVisibility(View.GONE);
3468                    commandAdapter.clear();
3469                    if (iq.getType() == Iq.Type.RESULT) {
3470                        for (Element child : iq.query().getChildren()) {
3471                            if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3472                            commandAdapter.add(new CommandAdapter.Command0050(child));
3473                        }
3474                    }
3475
3476                    if (mucConfig != null) commandAdapter.add(mucConfig);
3477
3478                    if (commandAdapter.getCount() < 1) {
3479                        conversation.hideViewPager();
3480                    } else if (delayShow) {
3481                        conversation.showViewPager();
3482                    }
3483                });
3484            });
3485        }
3486    }
3487
3488    private void resetUnreadMessagesCount() {
3489        lastMessageUuid = null;
3490        hideUnreadMessagesCount();
3491    }
3492
3493    private void hideUnreadMessagesCount() {
3494        if (this.binding == null) {
3495            return;
3496        }
3497        this.binding.scrollToBottomButton.setEnabled(false);
3498        this.binding.scrollToBottomButton.hide();
3499        this.binding.unreadCountCustomView.setVisibility(View.GONE);
3500    }
3501
3502    private void setSelection(int pos, boolean jumpToBottom) {
3503        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3504        this.binding.messagesView.post(
3505                () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3506        this.binding.messagesView.post(this::fireReadEvent);
3507    }
3508
3509    private boolean scrolledToBottom() {
3510        return this.binding != null && scrolledToBottom(this.binding.messagesView);
3511    }
3512
3513    private void processExtras(final Bundle extras) {
3514        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3515        final String text = extras.getString(Intent.EXTRA_TEXT);
3516        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3517        final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3518        final String postInitAction =
3519                extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3520        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3521        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3522        final boolean doNotAppend =
3523                extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3524        final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3525
3526        final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3527        if (thread != null) {
3528            conversation.setLockThread(true);
3529            backPressedLeaveSingleThread.setEnabled(true);
3530            setThread(new Element("thread").setContent(thread));
3531            refresh();
3532        }
3533
3534        final List<Uri> uris = extractUris(extras);
3535        if (uris != null && uris.size() > 0) {
3536            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3537                mediaPreviewAdapter.addMediaPreviews(
3538                        Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3539            } else {
3540                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3541                mediaPreviewAdapter.addMediaPreviews(
3542                        Attachment.of(getActivity(), cleanedUris, type));
3543            }
3544            toggleInputMethod();
3545            return;
3546        }
3547        if (nick != null) {
3548            if (pm) {
3549                Jid jid = conversation.getJid();
3550                try {
3551                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3552                    privateMessageWith(next);
3553                } catch (final IllegalArgumentException ignored) {
3554                    // do nothing
3555                }
3556            } else {
3557                final MucOptions mucOptions = conversation.getMucOptions();
3558                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3559                    highlightInConference(nick);
3560                }
3561            }
3562        } else {
3563            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3564                mediaPreviewAdapter.addMediaPreviews(
3565                        Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3566                toggleInputMethod();
3567                return;
3568            } else if (text != null && asQuote) {
3569                quoteText(text);
3570            } else {
3571                appendText(text, doNotAppend);
3572            }
3573        }
3574        if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3575            attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3576            return;
3577        }
3578        if ("call".equals(postInitAction)) {
3579            checkPermissionAndTriggerAudioCall();
3580        }
3581        if ("message".equals(postInitAction)) {
3582            binding.conversationViewPager.post(() -> {
3583                binding.conversationViewPager.setCurrentItem(0);
3584            });
3585        }
3586        if ("command".equals(postInitAction)) {
3587            binding.conversationViewPager.post(() -> {
3588                PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3589                if (adapter != null && adapter.getCount() > 1) {
3590                    binding.conversationViewPager.setCurrentItem(1);
3591                }
3592                final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3593                Jid commandJid = null;
3594                if (jid != null) {
3595                    try {
3596                        commandJid = Jid.of(jid);
3597                    } catch (final IllegalArgumentException e) { }
3598                }
3599                if (commandJid == null || !commandJid.isFullJid()) {
3600                    final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3601                    if (discoJid != null) commandJid = discoJid;
3602                }
3603                if (node != null && commandJid != null && activity != null) {
3604                    conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3605                }
3606            });
3607            return;
3608        }
3609        Message message =
3610                downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3611        if ("webxdc".equals(postInitAction)) {
3612            if (message == null) {
3613                message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3614            }
3615            if (message == null) return;
3616
3617            Cid webxdcCid = message.getFileParams().getCids().get(0);
3618            WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
3619            Conversation conversation = (Conversation) message.getConversation();
3620            if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3621                conversation.startWebxdc(webxdc);
3622            }
3623        }
3624        if (message != null) {
3625            startDownloadable(message);
3626        }
3627        if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3628            if (!conversation.switchToSession("jabber:iq:register")) {
3629                conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3630            }
3631        }
3632    }
3633
3634    private Element commandFor(final Jid jid, final String node) {
3635        if (commandAdapter != null) {
3636            for (int i = 0; i < commandAdapter.getCount(); i++) {
3637                final CommandAdapter.Command c = commandAdapter.getItem(i);
3638                if (!(c instanceof CommandAdapter.Command0050)) continue;
3639
3640                final Element command = ((CommandAdapter.Command0050) c).el;
3641                final String commandNode = command.getAttribute("node");
3642                if (commandNode == null || !commandNode.equals(node)) continue;
3643
3644                final Jid commandJid = command.getAttributeAsJid("jid");
3645                if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3646
3647                return command;
3648            }
3649        }
3650
3651        return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3652    }
3653
3654    private List<Uri> extractUris(final Bundle extras) {
3655        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3656        if (uris != null) {
3657            return uris;
3658        }
3659        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3660        if (uri != null) {
3661            return Collections.singletonList(uri);
3662        } else {
3663            return null;
3664        }
3665    }
3666
3667    private List<Uri> cleanUris(final List<Uri> uris) {
3668        final Iterator<Uri> iterator = uris.iterator();
3669        while (iterator.hasNext()) {
3670            final Uri uri = iterator.next();
3671            if (FileBackend.dangerousFile(uri)) {
3672                iterator.remove();
3673                Toast.makeText(
3674                                requireActivity(),
3675                                R.string.security_violation_not_attaching_file,
3676                                Toast.LENGTH_SHORT)
3677                        .show();
3678            }
3679        }
3680        return uris;
3681    }
3682
3683    private boolean showBlockSubmenu(View view) {
3684        final Jid jid = conversation.getJid();
3685        final int mode = conversation.getMode();
3686        final var contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3687        final boolean showReject = contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3688        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3689        popupMenu.inflate(R.menu.block);
3690        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3691        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3692        popupMenu.getMenu().findItem(R.id.add_contact).setVisible(!contact.showInRoster());
3693        popupMenu.setOnMenuItemClickListener(
3694                menuItem -> {
3695                    Blockable blockable;
3696                    switch (menuItem.getItemId()) {
3697                        case R.id.reject:
3698                            activity.xmppConnectionService.stopPresenceUpdatesTo(
3699                                    conversation.getContact());
3700                            updateSnackBar(conversation);
3701                            return true;
3702                        case R.id.add_contact:
3703                            mAddBackClickListener.onClick(view);
3704                            return true;
3705                        case R.id.block_domain:
3706                            blockable =
3707                                    conversation
3708                                            .getAccount()
3709                                            .getRoster()
3710                                            .getContact(jid.getDomain());
3711                            break;
3712                        default:
3713                            blockable = conversation;
3714                    }
3715                    BlockContactDialog.show(activity, blockable);
3716                    return true;
3717                });
3718        popupMenu.show();
3719        return true;
3720    }
3721
3722    private boolean showBlockMucSubmenu(View view) {
3723        final var jid = conversation.getJid();
3724        final var popupMenu = new PopupMenu(getActivity(), view);
3725        popupMenu.inflate(R.menu.block_muc);
3726        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3727        popupMenu.setOnMenuItemClickListener(
3728                menuItem -> {
3729                    Blockable blockable;
3730                    switch (menuItem.getItemId()) {
3731                        case R.id.reject:
3732                            activity.xmppConnectionService.clearConversationHistory(conversation);
3733                            activity.xmppConnectionService.archiveConversation(conversation);
3734                            return true;
3735                        case R.id.add_bookmark:
3736                            activity.xmppConnectionService.saveConversationAsBookmark(conversation, "");
3737                            updateSnackBar(conversation);
3738                            return true;
3739                        case R.id.block_contact:
3740                            blockable =
3741                                    conversation
3742                                            .getAccount()
3743                                            .getRoster()
3744                                            .getContact(Jid.of(conversation.getAttribute("inviter")));
3745                            break;
3746                        default:
3747                            blockable = conversation;
3748                    }
3749                    BlockContactDialog.show(activity, blockable);
3750                    activity.xmppConnectionService.archiveConversation(conversation);
3751                    return true;
3752                });
3753        popupMenu.show();
3754        return true;
3755    }
3756
3757    private void updateSnackBar(final Conversation conversation) {
3758        final Account account = conversation.getAccount();
3759        final XmppConnection connection = account.getXmppConnection();
3760        final int mode = conversation.getMode();
3761        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3762        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3763            return;
3764        }
3765        if (account.getStatus() == Account.State.DISABLED) {
3766            showSnackbar(
3767                    R.string.this_account_is_disabled,
3768                    R.string.enable,
3769                    this.mEnableAccountListener);
3770        } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3771            showSnackbar(R.string.this_account_is_logged_out,R.string.log_in,this.mEnableAccountListener);
3772        } else if (conversation.isBlocked()) {
3773            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3774        } else if (account.getStatus() == Account.State.CONNECTING) {
3775            showSnackbar(R.string.this_account_is_connecting, 0, null);
3776        } else if (account.getStatus() != Account.State.ONLINE) {
3777            showSnackbar(R.string.this_account_is_offline, 0, null);
3778        } else if (contact != null
3779                && !contact.showInRoster()
3780                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3781            showSnackbar(
3782                    R.string.contact_added_you,
3783                    R.string.options,
3784                    this.mBlockClickListener,
3785                    this.mLongPressBlockListener);
3786        } else if (contact != null
3787                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3788            showSnackbar(
3789                    R.string.contact_asks_for_presence_subscription,
3790                    R.string.allow,
3791                    this.mAllowPresenceSubscription,
3792                    this.mLongPressBlockListener);
3793        } else if (mode == Conversation.MODE_MULTI
3794                && !conversation.getMucOptions().online()
3795                && account.getStatus() == Account.State.ONLINE) {
3796            switch (conversation.getMucOptions().getError()) {
3797                case NICK_IN_USE:
3798                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3799                    break;
3800                case NO_RESPONSE:
3801                    showSnackbar(R.string.joining_conference, 0, null);
3802                    break;
3803                case SERVER_NOT_FOUND:
3804                    if (conversation.receivedMessagesCount() > 0) {
3805                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3806                    } else {
3807                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3808                    }
3809                    break;
3810                case REMOTE_SERVER_TIMEOUT:
3811                    if (conversation.receivedMessagesCount() > 0) {
3812                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3813                    } else {
3814                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3815                    }
3816                    break;
3817                case PASSWORD_REQUIRED:
3818                    showSnackbar(
3819                            R.string.conference_requires_password,
3820                            R.string.enter_password,
3821                            enterPassword);
3822                    break;
3823                case BANNED:
3824                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3825                    break;
3826                case MEMBERS_ONLY:
3827                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3828                    break;
3829                case RESOURCE_CONSTRAINT:
3830                    showSnackbar(
3831                            R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3832                    break;
3833                case KICKED:
3834                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3835                    break;
3836                case TECHNICAL_PROBLEMS:
3837                    showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3838                    break;
3839                case UNKNOWN:
3840                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3841                    break;
3842                case INVALID_NICK:
3843                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3844                case SHUTDOWN:
3845                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3846                    break;
3847                case DESTROYED:
3848                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3849                    break;
3850                case NON_ANONYMOUS:
3851                    showSnackbar(
3852                            R.string.group_chat_will_make_your_jabber_id_public,
3853                            R.string.join,
3854                            acceptJoin);
3855                    break;
3856                default:
3857                    hideSnackbar();
3858                    break;
3859            }
3860        } else if (account.hasPendingPgpIntent(conversation)) {
3861            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3862        } else if (connection != null
3863                && connection.getFeatures().blocking()
3864                && conversation.strangerInvited()) {
3865            showSnackbar(
3866                    R.string.received_invite_from_stranger,
3867                    R.string.options,
3868                    (v) -> showBlockMucSubmenu(v),
3869                    (v) -> showBlockMucSubmenu(v));
3870        } else if (connection != null
3871                && connection.getFeatures().blocking()
3872                && conversation.countMessages() != 0
3873                && !conversation.isBlocked()
3874                && conversation.isWithStranger()) {
3875            showSnackbar(
3876                    R.string.received_message_from_stranger,
3877                    R.string.options,
3878                    this.mBlockClickListener,
3879                    this.mLongPressBlockListener);
3880        } else {
3881            hideSnackbar();
3882        }
3883    }
3884
3885    @Override
3886    public void refresh() {
3887        if (this.binding == null) {
3888            Log.d(
3889                    Config.LOGTAG,
3890                    "ConversationFragment.refresh() skipped updated because view binding was null");
3891            return;
3892        }
3893        if (this.conversation != null
3894                && this.activity != null
3895                && this.activity.xmppConnectionService != null) {
3896            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3897                activity.onConversationArchived(this.conversation);
3898                return;
3899            }
3900        }
3901        this.refresh(true);
3902    }
3903
3904    private void refresh(boolean notifyConversationRead) {
3905        synchronized (this.messageList) {
3906            if (this.conversation != null) {
3907                if (messageListAdapter.hasSelection()) {
3908                    if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3909                } else {
3910                    conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
3911                    updateStatusMessages();
3912                    this.messageListAdapter.notifyDataSetChanged();
3913                }
3914                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3915                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3916                    binding.unreadCountCustomView.setUnreadCount(
3917                            conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3918                }
3919                updateSnackBar(conversation);
3920                if (activity != null) updateChatMsgHint();
3921                if (notifyConversationRead && activity != null) {
3922                    binding.messagesView.post(this::fireReadEvent);
3923                }
3924                updateSendButton();
3925                updateEditablity();
3926                conversation.refreshSessions();
3927            }
3928        }
3929    }
3930
3931    protected void messageSent() {
3932        binding.textinputSubject.setText("");
3933        binding.textinputSubject.setVisibility(View.GONE);
3934        setThread(null);
3935        conversation.setUserSelectedThread(false);
3936        mSendingPgpMessage.set(false);
3937        this.binding.textinput.setText("");
3938        if (conversation.setCorrectingMessage(null)) {
3939            this.binding.textinput.append(conversation.getDraftMessage());
3940            conversation.setDraftMessage(null);
3941        }
3942        storeNextMessage();
3943        updateChatMsgHint();
3944        if (activity == null) return;
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}