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