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