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