ConversationFragment.java

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