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