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