ConversationFragment.java

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