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