ConversationFragment.java

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