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