ConversationFragment.java

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