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