ConversationFragment.java

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