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        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1492        final int tutorialCount = p.getInt("thread_tutorial", 0);
1493        if (tutorialCount < 5) {
1494            Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1495            p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1496        }
1497    }
1498
1499    @Override
1500    public void onDestroyView() {
1501        super.onDestroyView();
1502        Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1503        messageListAdapter.setOnContactPictureClicked(null);
1504        messageListAdapter.setOnContactPictureLongClicked(null);
1505        messageListAdapter.setOnInlineImageLongClicked(null);
1506        messageListAdapter.setConversationFragment(null);
1507        binding.conversationViewPager.setAdapter(null);
1508        if (conversation != null) conversation.setupViewPager(null, null, false, null);
1509    }
1510
1511    public void quoteText(String text) {
1512        if (binding.textinput.isEnabled()) {
1513            binding.textinput.insertAsQuote(text);
1514            binding.textinput.requestFocus();
1515            InputMethodManager inputMethodManager =
1516                    (InputMethodManager)
1517                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1518            if (inputMethodManager != null) {
1519                inputMethodManager.showSoftInput(
1520                        binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1521            }
1522        }
1523    }
1524
1525    private void quoteMessage(Message message) {
1526        if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1527        setThread(message.getThread());
1528        conversation.setUserSelectedThread(true);
1529        if (!forkNullThread(message)) newThread();
1530        setupReply(message);
1531    }
1532
1533    private boolean forkNullThread(Message message) {
1534        if (message.getThread() != null || conversation.getMode() != Conversation.MODE_MULTI) return true;
1535        for (final Message m : conversation.findReplies(message.getServerMsgId())) {
1536            final Element thread = m.getThread();
1537            if (thread != null) {
1538                setThread(thread);
1539                return true;
1540            }
1541        }
1542
1543        return false;
1544    }
1545
1546    private void setupReply(Message message) {
1547        conversation.setReplyTo(message);
1548        if (message == null) {
1549            binding.contextPreview.setVisibility(View.GONE);
1550            return;
1551        }
1552
1553        SpannableStringBuilder body = message.getSpannableBody(null, null);
1554        if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1555        messageListAdapter.handleTextQuotes(body, activity.isDarkTheme());
1556        binding.contextPreviewText.setText(body);
1557        binding.contextPreview.setVisibility(View.VISIBLE);
1558    }
1559
1560    private void setThread(Element thread) {
1561        this.conversation.setThread(thread);
1562        binding.threadIdenticon.setAlpha(0f);
1563        binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1564        if (thread != null) {
1565            final String threadId = thread.getContent();
1566            if (threadId != null) {
1567                binding.threadIdenticon.setAlpha(1f);
1568                binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1569                binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1570            }
1571        }
1572        updateSendButton();
1573    }
1574
1575    @Override
1576    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1577        // This should cancel any remaining click events that would otherwise trigger links
1578        v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1579
1580        if (v == binding.textSendButton) {
1581            super.onCreateContextMenu(menu, v, menuInfo);
1582            try {
1583                java.lang.reflect.Method m = menu.getClass().getSuperclass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
1584                m.setAccessible(true);
1585                m.invoke(menu, true);
1586            } catch (Exception e) {
1587                e.printStackTrace();
1588            }
1589            Menu tmpMenu = new PopupMenu(activity, null).getMenu();
1590            activity.getMenuInflater().inflate(R.menu.fragment_conversation, tmpMenu);
1591            MenuItem attachMenu = tmpMenu.findItem(R.id.action_attach_file);
1592            for (int i = 0; i < attachMenu.getSubMenu().size(); i++) {
1593                MenuItem item = attachMenu.getSubMenu().getItem(i);
1594                MenuItem newItem = menu.add(item.getGroupId(), item.getItemId(), item.getOrder(), item.getTitle());
1595                newItem.setIcon(item.getIcon());
1596            }
1597            return;
1598        }
1599
1600        synchronized (this.messageList) {
1601            super.onCreateContextMenu(menu, v, menuInfo);
1602            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1603            this.selectedMessage = this.messageList.get(acmi.position);
1604            populateContextMenu(menu);
1605        }
1606    }
1607
1608    private void populateContextMenu(ContextMenu menu) {
1609        final Message m = this.selectedMessage;
1610        final Transferable t = m.getTransferable();
1611        Message relevantForCorrection = m;
1612        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1613            relevantForCorrection = relevantForCorrection.next();
1614        }
1615        if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1616
1617            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1618                    || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1619                return;
1620            }
1621
1622            if (m.getStatus() == Message.STATUS_RECEIVED
1623                    && t != null
1624                    && (t.getStatus() == Transferable.STATUS_CANCELLED
1625                            || t.getStatus() == Transferable.STATUS_FAILED)) {
1626                return;
1627            }
1628
1629            final boolean deleted = m.isDeleted();
1630            final boolean encrypted =
1631                    m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1632                            || m.getEncryption() == Message.ENCRYPTION_PGP;
1633            final boolean receiving =
1634                    m.getStatus() == Message.STATUS_RECEIVED
1635                            && (t instanceof JingleFileTransferConnection
1636                                    || t instanceof HttpDownloadConnection);
1637            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1638            MenuItem openWith = menu.findItem(R.id.open_with);
1639            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1640            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1641            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1642            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1643            MenuItem retractMessage = menu.findItem(R.id.retract_message);
1644            MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1645            MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1646            MenuItem shareWith = menu.findItem(R.id.share_with);
1647            MenuItem sendAgain = menu.findItem(R.id.send_again);
1648            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1649            MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1650            MenuItem downloadFile = menu.findItem(R.id.download_file);
1651            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1652            MenuItem blockMedia = menu.findItem(R.id.block_media);
1653            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1654            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1655            onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1656            final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1657            final boolean showError =
1658                    m.getStatus() == Message.STATUS_SEND_FAILED
1659                            && m.getErrorMessage() != null
1660                            && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1661            if (!encrypted && !m.getBody().equals("")) {
1662                copyMessage.setVisible(true);
1663            }
1664            quoteMessage.setVisible(!encrypted && !showError);
1665            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1666                retryDecryption.setVisible(true);
1667            }
1668            if (!showError
1669                    && relevantForCorrection.getType() == Message.TYPE_TEXT
1670                    && !m.isGeoUri()
1671                    && relevantForCorrection.isLastCorrectableMessage()
1672                    && m.getConversation() instanceof Conversation) {
1673                correctMessage.setVisible(true);
1674                if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1675            }
1676            if (relevantForCorrection.getReactions() != null) {
1677                correctMessage.setVisible(false);
1678                retractMessage.setVisible(true);
1679            }
1680            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")) {
1681                moderateMessage.setVisible(true);
1682            }
1683            if ((m.isFileOrImage() && !deleted && !receiving)
1684                    || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1685                            && !unInitiatedButKnownSize
1686                            && t == null) {
1687                shareWith.setVisible(true);
1688            }
1689            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1690                sendAgain.setVisible(true);
1691            }
1692            if (m.hasFileOnRemoteHost()
1693                    || m.isGeoUri()
1694                    || m.treatAsDownloadable()
1695                    || unInitiatedButKnownSize
1696                    || t instanceof HttpDownloadConnection) {
1697                copyUrl.setVisible(true);
1698            }
1699            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1700                downloadFile.setVisible(true);
1701                downloadFile.setTitle(
1702                        activity.getString(
1703                                R.string.download_x_file,
1704                                UIHelper.getFileDescriptionString(activity, m)));
1705            }
1706            final boolean waitingOfferedSending =
1707                    m.getStatus() == Message.STATUS_WAITING
1708                            || m.getStatus() == Message.STATUS_UNSEND
1709                            || m.getStatus() == Message.STATUS_OFFERED;
1710            final boolean cancelable =
1711                    (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1712            if (cancelable) {
1713                cancelTransmission.setVisible(true);
1714            }
1715            if (m.isFileOrImage() && !deleted && !cancelable) {
1716                final String path = m.getRelativeFilePath();
1717                if (path == null
1718                        || !path.startsWith("/")
1719                        || FileBackend.inConversationsDirectory(requireActivity(), path)) {
1720                    saveAsSticker.setVisible(true);
1721                    blockMedia.setVisible(true);
1722                    deleteFile.setVisible(true);
1723                    deleteFile.setTitle(
1724                            activity.getString(
1725                                    R.string.delete_x_file,
1726                                    UIHelper.getFileDescriptionString(activity, m)));
1727                }
1728            }
1729
1730            if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1731                // We might be showing a thumbnail worth blocking
1732                blockMedia.setVisible(true);
1733            }
1734            if (showError) {
1735                showErrorMessage.setVisible(true);
1736            }
1737            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1738            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1739                    || (mime != null && mime.startsWith("audio/"))) {
1740                openWith.setVisible(true);
1741            }
1742        }
1743    }
1744
1745    @Override
1746    public boolean onContextItemSelected(MenuItem item) {
1747        switch (item.getItemId()) {
1748            case R.id.share_with:
1749                ShareUtil.share(activity, selectedMessage);
1750                return true;
1751            case R.id.correct_message:
1752                correctMessage(selectedMessage);
1753                return true;
1754            case R.id.retract_message:
1755                new AlertDialog.Builder(activity)
1756                    .setTitle(R.string.retract_message)
1757                    .setMessage("Do you really want to retract this message?")
1758                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1759                        Message message = selectedMessage;
1760                        while (message.mergeable(message.next())) {
1761                            message = message.next();
1762                        }
1763                        Element reactions = message.getReactions();
1764                        if (reactions != null) {
1765                            final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
1766                            if (previousReaction != null) reactions = previousReaction.getReactions();
1767                            for (Element el : reactions.getChildren()) {
1768                                if (message.getQuoteableBody().endsWith(el.getContent())) {
1769                                    reactions.removeChild(el);
1770                                }
1771                            }
1772                            message.setReactions(reactions);
1773                            if (previousReaction != null) {
1774                                previousReaction.setReactions(reactions);
1775                                activity.xmppConnectionService.updateMessage(previousReaction);
1776                            }
1777                        }
1778                        message.setBody(" ");
1779                        message.putEdited(message.getUuid(), message.getServerMsgId());
1780                        message.setServerMsgId(null);
1781                        message.setUuid(UUID.randomUUID().toString());
1782                        sendMessage(message);
1783                    })
1784                    .setNegativeButton(R.string.no, null).show();
1785                return true;
1786            case R.id.moderate_message:
1787                activity.quickEdit("Spam", (reason) -> {
1788                    Message message = selectedMessage;
1789                    do {
1790                        activity.xmppConnectionService.moderateMessage(conversation.getAccount(), message, reason);
1791                        message = message.mergeable(message.next()) ? message.next() : null;
1792                    } while (message != null);
1793                    return null;
1794                }, R.string.moderate_reason, false, false, true);
1795                return true;
1796            case R.id.copy_message:
1797                ShareUtil.copyToClipboard(activity, selectedMessage);
1798                return true;
1799            case R.id.quote_message:
1800                quoteMessage(selectedMessage);
1801                return true;
1802            case R.id.send_again:
1803                resendMessage(selectedMessage);
1804                return true;
1805            case R.id.copy_url:
1806                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1807                return true;
1808            case R.id.save_as_sticker:
1809                saveAsSticker(selectedMessage);
1810                return true;
1811            case R.id.download_file:
1812                startDownloadable(selectedMessage);
1813                return true;
1814            case R.id.cancel_transmission:
1815                cancelTransmission(selectedMessage);
1816                return true;
1817            case R.id.retry_decryption:
1818                retryDecryption(selectedMessage);
1819                return true;
1820            case R.id.block_media:
1821                new AlertDialog.Builder(activity)
1822                    .setTitle(R.string.block_media)
1823                    .setMessage("Do you really want to block this media in all messages?")
1824                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1825                        List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
1826                        if (thumbs != null && !thumbs.isEmpty()) {
1827                            for (Element thumb : thumbs) {
1828                                Uri uri = Uri.parse(thumb.getAttribute("uri"));
1829                                if (uri.getScheme().equals("cid")) {
1830                                    Cid cid = BobTransfer.cid(uri);
1831                                    if (cid == null) continue;
1832                                    DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
1833                                    activity.xmppConnectionService.blockMedia(f);
1834                                    activity.xmppConnectionService.evictPreview(f);
1835                                    f.delete();
1836                                }
1837                            }
1838                        }
1839                        File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
1840                        activity.xmppConnectionService.blockMedia(f);
1841                        activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
1842                        activity.xmppConnectionService.evictPreview(f);
1843                        activity.xmppConnectionService.updateMessage(selectedMessage, false);
1844                        activity.onConversationsListItemUpdated();
1845                        refresh();
1846                    })
1847                    .setNegativeButton(R.string.no, null).show();
1848                return true;
1849            case R.id.delete_file:
1850                deleteFile(selectedMessage);
1851                return true;
1852            case R.id.show_error_message:
1853                showErrorMessage(selectedMessage);
1854                return true;
1855            case R.id.open_with:
1856                openWith(selectedMessage);
1857                return true;
1858            case R.id.only_this_thread:
1859                conversation.setLockThread(true);
1860                backPressedLeaveSingleThread.setEnabled(true);
1861                setThread(selectedMessage.getThread());
1862                refresh();
1863                return true;
1864            default:
1865                return onOptionsItemSelected(item);
1866        }
1867    }
1868
1869    @Override
1870    public boolean onOptionsItemSelected(final MenuItem item) {
1871        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1872            return false;
1873        } else if (conversation == null) {
1874            return super.onOptionsItemSelected(item);
1875        }
1876        switch (item.getItemId()) {
1877            case R.id.encryption_choice_axolotl:
1878            case R.id.encryption_choice_pgp:
1879            case R.id.encryption_choice_none:
1880                handleEncryptionSelection(item);
1881                break;
1882            case R.id.attach_choose_picture:
1883            case R.id.attach_take_picture:
1884            case R.id.attach_record_video:
1885            case R.id.attach_choose_file:
1886            case R.id.attach_record_voice:
1887            case R.id.attach_location:
1888                handleAttachmentSelection(item);
1889                break;
1890            case R.id.action_search:
1891                startSearch();
1892                break;
1893            case R.id.action_archive:
1894                activity.xmppConnectionService.archiveConversation(conversation);
1895                break;
1896            case R.id.action_contact_details:
1897                activity.switchToContactDetails(conversation.getContact());
1898                break;
1899            case R.id.action_muc_details:
1900                ConferenceDetailsActivity.open(activity, conversation);
1901                break;
1902            case R.id.action_invite:
1903                startActivityForResult(
1904                        ChooseContactActivity.create(activity, conversation),
1905                        REQUEST_INVITE_TO_CONVERSATION);
1906                break;
1907            case R.id.action_clear_history:
1908                clearHistoryDialog(conversation);
1909                break;
1910            case R.id.action_mute:
1911                muteConversationDialog(conversation);
1912                break;
1913            case R.id.action_unmute:
1914                unMuteConversation(conversation);
1915                break;
1916            case R.id.action_block:
1917            case R.id.action_unblock:
1918                final Activity activity = getActivity();
1919                if (activity instanceof XmppActivity) {
1920                    BlockContactDialog.show((XmppActivity) activity, conversation);
1921                }
1922                break;
1923            case R.id.action_audio_call:
1924                checkPermissionAndTriggerAudioCall();
1925                break;
1926            case R.id.action_video_call:
1927                checkPermissionAndTriggerVideoCall();
1928                break;
1929            case R.id.action_ongoing_call:
1930                returnToOngoingCall();
1931                break;
1932            case R.id.action_toggle_pinned:
1933                togglePinned();
1934                break;
1935            case R.id.action_add_shortcut:
1936                addShortcut();
1937                break;
1938            case R.id.action_refresh_feature_discovery:
1939                refreshFeatureDiscovery();
1940                break;
1941            default:
1942                break;
1943        }
1944        return super.onOptionsItemSelected(item);
1945    }
1946
1947    public boolean onBackPressed() {
1948        boolean wasLocked = conversation.getLockThread();
1949        conversation.setLockThread(false);
1950        backPressedLeaveSingleThread.setEnabled(false);
1951        if (wasLocked) {
1952            setThread(null);
1953            conversation.setUserSelectedThread(false);
1954            refresh();
1955            updateThreadFromLastMessage();
1956            return true;
1957        }
1958        return false;
1959    }
1960
1961    private void startSearch() {
1962        final Intent intent = new Intent(getActivity(), SearchActivity.class);
1963        intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1964        startActivity(intent);
1965    }
1966
1967    private void returnToOngoingCall() {
1968        final Optional<OngoingRtpSession> ongoingRtpSession =
1969                activity.xmppConnectionService
1970                        .getJingleConnectionManager()
1971                        .getOngoingRtpConnection(conversation.getContact());
1972        if (ongoingRtpSession.isPresent()) {
1973            final OngoingRtpSession id = ongoingRtpSession.get();
1974            final Intent intent = new Intent(activity, RtpSessionActivity.class);
1975            intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.getAccount().getJid().asBareJid().toEscapedString());
1976            intent.putExtra(
1977                    RtpSessionActivity.EXTRA_ACCOUNT,
1978                    id.getAccount().getJid().asBareJid().toEscapedString());
1979            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
1980            if (id instanceof AbstractJingleConnection.Id) {
1981                intent.setAction(Intent.ACTION_VIEW);
1982                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
1983            } else if (id instanceof JingleConnectionManager.RtpSessionProposal) {
1984                if (((JingleConnectionManager.RtpSessionProposal) id).media.contains(Media.VIDEO)) {
1985                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1986                } else {
1987                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1988                }
1989            }
1990            activity.startActivity(intent);
1991        }
1992    }
1993
1994    private void refreshFeatureDiscovery() {
1995        Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
1996        if (presences.isEmpty()) {
1997            presences = new HashSet<>();
1998            presences.add(new AbstractMap.SimpleEntry("", null));
1999        }
2000        for (Map.Entry<String, Presence> entry : presences) {
2001            Jid jid = conversation.getContact().getJid();
2002            if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
2003            activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
2004                if (activity == null) return;
2005                activity.runOnUiThread(() -> {
2006                    refresh();
2007                    refreshCommands(true);
2008                });
2009            });
2010        }
2011    }
2012
2013    private void addShortcut() {
2014        ShortcutInfoCompat info;
2015        if (conversation.getMode() == Conversation.MODE_MULTI) {
2016            info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getMucOptions());
2017        } else {
2018            info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
2019        }
2020        ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2021    }
2022
2023    private void togglePinned() {
2024        final boolean pinned =
2025                conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2026        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2027        activity.xmppConnectionService.updateConversation(conversation);
2028        activity.invalidateOptionsMenu();
2029    }
2030
2031    private void checkPermissionAndTriggerAudioCall() {
2032        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2033            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2034            return;
2035        }
2036        final List<String> permissions;
2037        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2038            permissions =
2039                    Arrays.asList(
2040                            Manifest.permission.RECORD_AUDIO,
2041                            Manifest.permission.BLUETOOTH_CONNECT);
2042        } else {
2043            permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2044        }
2045        if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2046            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2047        }
2048    }
2049
2050    private void checkPermissionAndTriggerVideoCall() {
2051        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2052            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2053            return;
2054        }
2055        final List<String> permissions;
2056        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2057            permissions =
2058                    Arrays.asList(
2059                            Manifest.permission.RECORD_AUDIO,
2060                            Manifest.permission.CAMERA,
2061                            Manifest.permission.BLUETOOTH_CONNECT);
2062        } else {
2063            permissions =
2064                    Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2065        }
2066        if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2067            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2068        }
2069    }
2070
2071    private void triggerRtpSession(final String action) {
2072        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy() != null) {
2073            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2074                    .show();
2075            return;
2076        }
2077        final Contact contact = conversation.getContact();
2078        if (RtpCapability.jmiSupport(contact)) {
2079            triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2080        } else {
2081            final RtpCapability.Capability capability;
2082            if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2083                capability = RtpCapability.Capability.VIDEO;
2084            } else {
2085                capability = RtpCapability.Capability.AUDIO;
2086            }
2087            PresenceSelector.selectFullJidForDirectRtpConnection(
2088                    activity,
2089                    contact,
2090                    capability,
2091                    fullJid -> {
2092                        triggerRtpSession(contact.getAccount(), fullJid, action);
2093                    });
2094        }
2095    }
2096
2097    private void triggerRtpSession(final Account account, final Jid with, final String action) {
2098        final Intent intent = new Intent(activity, RtpSessionActivity.class);
2099        intent.setAction(action);
2100        intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, account.getJid().toEscapedString());
2101        intent.putExtra(RtpSessionActivity.EXTRA_WITH, with.toEscapedString());
2102        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2103        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
2104        startActivity(intent);
2105    }
2106
2107    private void handleAttachmentSelection(MenuItem item) {
2108        switch (item.getItemId()) {
2109            case R.id.attach_choose_picture:
2110                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2111                break;
2112            case R.id.attach_take_picture:
2113                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2114                break;
2115            case R.id.attach_record_video:
2116                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2117                break;
2118            case R.id.attach_choose_file:
2119                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2120                break;
2121            case R.id.attach_record_voice:
2122                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2123                break;
2124            case R.id.attach_location:
2125                attachFile(ATTACHMENT_CHOICE_LOCATION);
2126                break;
2127        }
2128    }
2129
2130    private void handleEncryptionSelection(MenuItem item) {
2131        if (conversation == null) {
2132            return;
2133        }
2134        final boolean updated;
2135        switch (item.getItemId()) {
2136            case R.id.encryption_choice_none:
2137                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2138                item.setChecked(true);
2139                break;
2140            case R.id.encryption_choice_pgp:
2141                if (activity.hasPgp()) {
2142                    if (conversation.getAccount().getPgpSignature() != null) {
2143                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2144                        item.setChecked(true);
2145                    } else {
2146                        updated = false;
2147                        activity.announcePgp(
2148                                conversation.getAccount(),
2149                                conversation,
2150                                null,
2151                                activity.onOpenPGPKeyPublished);
2152                    }
2153                } else {
2154                    activity.showInstallPgpDialog();
2155                    updated = false;
2156                }
2157                break;
2158            case R.id.encryption_choice_axolotl:
2159                Log.d(
2160                        Config.LOGTAG,
2161                        AxolotlService.getLogprefix(conversation.getAccount())
2162                                + "Enabled axolotl for Contact "
2163                                + conversation.getContact().getJid());
2164                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2165                item.setChecked(true);
2166                break;
2167            default:
2168                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2169                break;
2170        }
2171        if (updated) {
2172            activity.xmppConnectionService.updateConversation(conversation);
2173        }
2174        updateChatMsgHint();
2175        getActivity().invalidateOptionsMenu();
2176        activity.refreshUi();
2177    }
2178
2179    public void attachFile(final int attachmentChoice) {
2180        attachFile(attachmentChoice, true);
2181    }
2182
2183    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2184        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2185            if (!hasPermissions(
2186                    attachmentChoice,
2187                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2188                    Manifest.permission.RECORD_AUDIO)) {
2189                return;
2190            }
2191        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2192                || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
2193            if (!hasPermissions(
2194                    attachmentChoice,
2195                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2196                    Manifest.permission.CAMERA)) {
2197                return;
2198            }
2199        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2200            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2201                return;
2202            }
2203        }
2204        if (updateRecentlyUsed) {
2205            storeRecentlyUsedQuickAction(attachmentChoice);
2206        }
2207        final int encryption = conversation.getNextEncryption();
2208        final int mode = conversation.getMode();
2209        if (encryption == Message.ENCRYPTION_PGP) {
2210            if (activity.hasPgp()) {
2211                if (mode == Conversation.MODE_SINGLE
2212                        && conversation.getContact().getPgpKeyId() != 0) {
2213                    activity.xmppConnectionService
2214                            .getPgpEngine()
2215                            .hasKey(
2216                                    conversation.getContact(),
2217                                    new UiCallback<Contact>() {
2218
2219                                        @Override
2220                                        public void userInputRequired(
2221                                                PendingIntent pi, Contact contact) {
2222                                            startPendingIntent(pi, attachmentChoice);
2223                                        }
2224
2225                                        @Override
2226                                        public void success(Contact contact) {
2227                                            invokeAttachFileIntent(attachmentChoice);
2228                                        }
2229
2230                                        @Override
2231                                        public void error(int error, Contact contact) {
2232                                            activity.replaceToast(getString(error));
2233                                        }
2234                                    });
2235                } else if (mode == Conversation.MODE_MULTI
2236                        && conversation.getMucOptions().pgpKeysInUse()) {
2237                    if (!conversation.getMucOptions().everybodyHasKeys()) {
2238                        Toast warning =
2239                                Toast.makeText(
2240                                        getActivity(),
2241                                        R.string.missing_public_keys,
2242                                        Toast.LENGTH_LONG);
2243                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2244                        warning.show();
2245                    }
2246                    invokeAttachFileIntent(attachmentChoice);
2247                } else {
2248                    showNoPGPKeyDialog(
2249                            false,
2250                            (dialog, which) -> {
2251                                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2252                                activity.xmppConnectionService.updateConversation(conversation);
2253                                invokeAttachFileIntent(attachmentChoice);
2254                            });
2255                }
2256            } else {
2257                activity.showInstallPgpDialog();
2258            }
2259        } else {
2260            invokeAttachFileIntent(attachmentChoice);
2261        }
2262    }
2263
2264    private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2265        try {
2266            activity.getPreferences()
2267                    .edit()
2268                    .putString(
2269                            RECENTLY_USED_QUICK_ACTION,
2270                            SendButtonAction.of(attachmentChoice).toString())
2271                    .apply();
2272        } catch (IllegalArgumentException e) {
2273            // just do not save
2274        }
2275    }
2276
2277    @Override
2278    public void onRequestPermissionsResult(
2279            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2280        final PermissionUtils.PermissionResult permissionResult =
2281                PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2282        if (grantResults.length > 0) {
2283            if (allGranted(permissionResult.grantResults)) {
2284                switch (requestCode) {
2285                    case REQUEST_START_DOWNLOAD:
2286                        if (this.mPendingDownloadableMessage != null) {
2287                            startDownloadable(this.mPendingDownloadableMessage);
2288                        }
2289                        break;
2290                    case REQUEST_ADD_EDITOR_CONTENT:
2291                        if (this.mPendingEditorContent != null) {
2292                            attachEditorContentToConversation(this.mPendingEditorContent);
2293                        }
2294                        break;
2295                    case REQUEST_COMMIT_ATTACHMENTS:
2296                        commitAttachments();
2297                        break;
2298                    case REQUEST_START_AUDIO_CALL:
2299                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2300                        break;
2301                    case REQUEST_START_VIDEO_CALL:
2302                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2303                        break;
2304                    default:
2305                        attachFile(requestCode);
2306                        break;
2307                }
2308            } else {
2309                @StringRes int res;
2310                String firstDenied =
2311                        getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2312                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2313                    res = R.string.no_microphone_permission;
2314                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2315                    res = R.string.no_camera_permission;
2316                } else {
2317                    res = R.string.no_storage_permission;
2318                }
2319                Toast.makeText(
2320                                getActivity(),
2321                                getString(res, getString(R.string.app_name)),
2322                                Toast.LENGTH_SHORT)
2323                        .show();
2324            }
2325        }
2326        if (writeGranted(grantResults, permissions)) {
2327            if (activity != null && activity.xmppConnectionService != null) {
2328                activity.xmppConnectionService.getDrawableCache().evictAll();
2329                activity.xmppConnectionService.restartFileObserver();
2330            }
2331            refresh();
2332        }
2333    }
2334
2335    public void startDownloadable(Message message) {
2336        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2337            this.mPendingDownloadableMessage = message;
2338            return;
2339        }
2340        Transferable transferable = message.getTransferable();
2341        if (transferable != null) {
2342            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2343                createNewConnection(message);
2344                return;
2345            }
2346            if (!transferable.start()) {
2347                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2348                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2349                        .show();
2350            }
2351        } else if (message.treatAsDownloadable()
2352                || message.hasFileOnRemoteHost()
2353                || MessageUtils.unInitiatedButKnownSize(message)) {
2354            createNewConnection(message);
2355        } else {
2356            Log.d(
2357                    Config.LOGTAG,
2358                    message.getConversation().getAccount() + ": unable to start downloadable");
2359        }
2360    }
2361
2362    private void createNewConnection(final Message message) {
2363        if (!activity.xmppConnectionService.hasInternetConnection()) {
2364            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2365                    .show();
2366            return;
2367        }
2368        if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2369            try {
2370                BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2371                message.setTransferable(transfer);
2372                transfer.start();
2373            } catch (URISyntaxException e) {
2374                Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2375            }
2376        } else {
2377            activity.xmppConnectionService
2378                    .getHttpConnectionManager()
2379                    .createNewDownloadConnection(message, true);
2380        }
2381    }
2382
2383    @SuppressLint("InflateParams")
2384    protected void clearHistoryDialog(final Conversation conversation) {
2385        final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2386        builder.setTitle(getString(R.string.clear_conversation_history));
2387        final View dialogView =
2388                requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2389        final CheckBox endConversationCheckBox =
2390                dialogView.findViewById(R.id.end_conversation_checkbox);
2391        builder.setView(dialogView);
2392        builder.setNegativeButton(getString(R.string.cancel), null);
2393        builder.setPositiveButton(
2394                getString(R.string.confirm),
2395                (dialog, which) -> {
2396                    this.activity.xmppConnectionService.clearConversationHistory(conversation);
2397                    if (endConversationCheckBox.isChecked()) {
2398                        this.activity.xmppConnectionService.archiveConversation(conversation);
2399                        this.activity.onConversationArchived(conversation);
2400                    } else {
2401                        activity.onConversationsListItemUpdated();
2402                        refresh();
2403                    }
2404                });
2405        builder.create().show();
2406    }
2407
2408    protected void muteConversationDialog(final Conversation conversation) {
2409        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
2410        builder.setTitle(R.string.disable_notifications);
2411        final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2412        final CharSequence[] labels = new CharSequence[durations.length];
2413        for (int i = 0; i < durations.length; ++i) {
2414            if (durations[i] == -1) {
2415                labels[i] = activity.getString(R.string.until_further_notice);
2416            } else {
2417                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2418            }
2419        }
2420        builder.setItems(
2421                labels,
2422                (dialog, which) -> {
2423                    final long till;
2424                    if (durations[which] == -1) {
2425                        till = Long.MAX_VALUE;
2426                    } else {
2427                        till = System.currentTimeMillis() + (durations[which] * 1000L);
2428                    }
2429                    conversation.setMutedTill(till);
2430                    activity.xmppConnectionService.updateConversation(conversation);
2431                    activity.onConversationsListItemUpdated();
2432                    refresh();
2433                    activity.invalidateOptionsMenu();
2434                });
2435        builder.create().show();
2436    }
2437
2438    private boolean hasPermissions(int requestCode, List<String> permissions) {
2439        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
2440            final List<String> missingPermissions = new ArrayList<>();
2441            for (String permission : permissions) {
2442                if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU || Config.ONLY_INTERNAL_STORAGE) && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2443                    continue;
2444                }
2445                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2446                    missingPermissions.add(permission);
2447                }
2448            }
2449            if (missingPermissions.size() == 0) {
2450                return true;
2451            } else {
2452                requestPermissions(
2453                        missingPermissions.toArray(new String[0]),
2454                        requestCode);
2455                return false;
2456            }
2457        } else {
2458            return true;
2459        }
2460    }
2461
2462    private boolean hasPermissions(int requestCode, String... permissions) {
2463        return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2464    }
2465
2466    public void unMuteConversation(final Conversation conversation) {
2467        conversation.setMutedTill(0);
2468        this.activity.xmppConnectionService.updateConversation(conversation);
2469        this.activity.onConversationsListItemUpdated();
2470        refresh();
2471        this.activity.invalidateOptionsMenu();
2472    }
2473
2474    protected void invokeAttachFileIntent(final int attachmentChoice) {
2475        Intent intent = new Intent();
2476        boolean chooser = false;
2477        switch (attachmentChoice) {
2478            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2479                intent.setAction(Intent.ACTION_GET_CONTENT);
2480                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2481                intent.setType("image/*");
2482                chooser = true;
2483                break;
2484            case ATTACHMENT_CHOICE_RECORD_VIDEO:
2485                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2486                break;
2487            case ATTACHMENT_CHOICE_TAKE_PHOTO:
2488                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2489                pendingTakePhotoUri.push(uri);
2490                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2491                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2492                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2493                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2494                break;
2495            case ATTACHMENT_CHOICE_CHOOSE_FILE:
2496                chooser = true;
2497                intent.setType("*/*");
2498                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2499                intent.addCategory(Intent.CATEGORY_OPENABLE);
2500                intent.setAction(Intent.ACTION_GET_CONTENT);
2501                break;
2502            case ATTACHMENT_CHOICE_RECORD_VOICE:
2503                intent = new Intent(getActivity(), RecordingActivity.class);
2504                break;
2505            case ATTACHMENT_CHOICE_LOCATION:
2506                intent = GeoHelper.getFetchIntent(activity);
2507                break;
2508        }
2509        final Context context = getActivity();
2510        if (context == null) {
2511            return;
2512        }
2513        try {
2514            if (chooser) {
2515                startActivityForResult(
2516                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
2517                        attachmentChoice);
2518            } else {
2519                startActivityForResult(intent, attachmentChoice);
2520            }
2521        } catch (final ActivityNotFoundException e) {
2522            Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2523        }
2524    }
2525
2526    @Override
2527    public void onResume() {
2528        super.onResume();
2529        binding.messagesView.post(this::fireReadEvent);
2530    }
2531
2532    private void fireReadEvent() {
2533        if (activity != null && this.conversation != null) {
2534            String uuid = getLastVisibleMessageUuid();
2535            if (uuid != null) {
2536                activity.onConversationRead(this.conversation, uuid);
2537            }
2538        }
2539    }
2540
2541    private void newSubThread() {
2542        Element oldThread = conversation.getThread();
2543        Element thread = new Element("thread", "jabber:client");
2544        thread.setContent(UUID.randomUUID().toString());
2545        if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2546        setThread(thread);
2547    }
2548
2549    private void newThread() {
2550        Element thread = new Element("thread", "jabber:client");
2551        thread.setContent(UUID.randomUUID().toString());
2552        setThread(thread);
2553    }
2554
2555    private void updateThreadFromLastMessage() {
2556        if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2557            Message message = getLastVisibleMessage();
2558            if (message == null) {
2559                newThread();
2560            } else {
2561                if (conversation.getMode() == Conversation.MODE_MULTI) {
2562                    if (activity == null || activity.xmppConnectionService == null) return;
2563                    if (message.getStatus() < Message.STATUS_SEND) {
2564                        if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2565                    }
2566                }
2567
2568                setThread(message.getThread());
2569            }
2570        }
2571    }
2572
2573    private String getLastVisibleMessageUuid() {
2574        Message message =  getLastVisibleMessage();
2575        return message == null ? null : message.getUuid();
2576    }
2577
2578    private Message getLastVisibleMessage() {
2579        if (binding == null) {
2580            return null;
2581        }
2582        synchronized (this.messageList) {
2583            int pos = binding.messagesView.getLastVisiblePosition();
2584            if (pos >= 0) {
2585                Message message = null;
2586                for (int i = pos; i >= 0; --i) {
2587                    try {
2588                        message = (Message) binding.messagesView.getItemAtPosition(i);
2589                    } catch (IndexOutOfBoundsException e) {
2590                        // should not happen if we synchronize properly. however if that fails we
2591                        // just gonna try item -1
2592                        continue;
2593                    }
2594                    if (message.getType() != Message.TYPE_STATUS) {
2595                        break;
2596                    }
2597                }
2598                if (message != null) {
2599                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
2600                        message = message.next();
2601                    }
2602                    return message;
2603                }
2604            }
2605        }
2606        return null;
2607    }
2608
2609    private void openWith(final Message message) {
2610        if (message.isGeoUri()) {
2611            GeoHelper.view(getActivity(), message);
2612        } else {
2613            final DownloadableFile file =
2614                    activity.xmppConnectionService.getFileBackend().getFile(message);
2615            ViewUtil.view(activity, file);
2616        }
2617    }
2618
2619    private void showErrorMessage(final Message message) {
2620        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2621        builder.setTitle(R.string.error_message);
2622        final String errorMessage = message.getErrorMessage();
2623        final String[] errorMessageParts =
2624                errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2625        final String displayError;
2626        if (errorMessageParts.length == 2) {
2627            displayError = errorMessageParts[1];
2628        } else {
2629            displayError = errorMessage;
2630        }
2631        builder.setMessage(displayError);
2632        builder.setNegativeButton(
2633                R.string.copy_to_clipboard,
2634                (dialog, which) -> {
2635                    activity.copyTextToClipboard(displayError, R.string.error_message);
2636                    Toast.makeText(
2637                                    activity,
2638                                    R.string.error_message_copied_to_clipboard,
2639                                    Toast.LENGTH_SHORT)
2640                            .show();
2641                });
2642        builder.setPositiveButton(R.string.confirm, null);
2643        builder.create().show();
2644    }
2645
2646    public boolean onInlineImageLongClicked(Cid cid) {
2647        DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2648        if (f == null) return false;
2649
2650        saveAsSticker(f, null);
2651        return true;
2652    }
2653
2654    private void saveAsSticker(final Message m) {
2655        String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
2656        existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
2657        saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
2658    }
2659
2660    private void saveAsSticker(final File file, final String name) {
2661        savingAsSticker = file;
2662
2663        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
2664        intent.addCategory(Intent.CATEGORY_OPENABLE);
2665        intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
2666        intent.putExtra(Intent.EXTRA_TITLE, name);
2667
2668        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2669        final String dir = p.getString("sticker_directory", "Stickers");
2670        if (dir.startsWith("content://")) {
2671            intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
2672        } else {
2673            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
2674            Uri uri;
2675            if (Build.VERSION.SDK_INT >= 29) {
2676                Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
2677                uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
2678                uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
2679            } else {
2680                uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
2681            }
2682            intent.putExtra("android.provider.extra.INITIAL_URI", uri);
2683            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
2684        }
2685
2686        Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
2687        startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
2688    }
2689
2690    private void deleteFile(final Message message) {
2691        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2692        builder.setNegativeButton(R.string.cancel, null);
2693        builder.setTitle(R.string.delete_file_dialog);
2694        builder.setMessage(R.string.delete_file_dialog_msg);
2695        builder.setPositiveButton(
2696                R.string.confirm,
2697                (dialog, which) -> {
2698                    List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2699                    if (thumbs != null && !thumbs.isEmpty()) {
2700                        for (Element thumb : thumbs) {
2701                            Uri uri = Uri.parse(thumb.getAttribute("uri"));
2702                            if (uri.getScheme().equals("cid")) {
2703                                Cid cid = BobTransfer.cid(uri);
2704                                if (cid == null) continue;
2705                                DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2706                                activity.xmppConnectionService.evictPreview(f);
2707                                f.delete();
2708                            }
2709                        }
2710                    }
2711                    if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2712                        activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
2713                        activity.xmppConnectionService.updateMessage(message, false);
2714                        activity.onConversationsListItemUpdated();
2715                        refresh();
2716                    }
2717                });
2718        builder.create().show();
2719    }
2720
2721    private void resendMessage(final Message message) {
2722        if (message.isFileOrImage()) {
2723            if (!(message.getConversation() instanceof Conversation)) {
2724                return;
2725            }
2726            final Conversation conversation = (Conversation) message.getConversation();
2727            final DownloadableFile file =
2728                    activity.xmppConnectionService.getFileBackend().getFile(message);
2729            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2730                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2731                if (!message.hasFileOnRemoteHost()
2732                        && xmppConnection != null
2733                        && conversation.getMode() == Conversational.MODE_SINGLE
2734                        && !xmppConnection
2735                                .getFeatures()
2736                                .httpUpload(message.getFileParams().getSize())) {
2737                    activity.selectPresence(
2738                            conversation,
2739                            () -> {
2740                                message.setCounterpart(conversation.getNextCounterpart());
2741                                activity.xmppConnectionService.resendFailedMessages(message);
2742                                new Handler()
2743                                        .post(
2744                                                () -> {
2745                                                    int size = messageList.size();
2746                                                    this.binding.messagesView.setSelection(
2747                                                            size - 1);
2748                                                });
2749                            });
2750                    return;
2751                }
2752            } else if (!Compatibility.hasStoragePermission(getActivity())) {
2753                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2754                return;
2755            } else {
2756                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2757                message.setDeleted(true);
2758                activity.xmppConnectionService.updateMessage(message, false);
2759                activity.onConversationsListItemUpdated();
2760                refresh();
2761                return;
2762            }
2763        }
2764        activity.xmppConnectionService.resendFailedMessages(message);
2765        new Handler()
2766                .post(
2767                        () -> {
2768                            int size = messageList.size();
2769                            this.binding.messagesView.setSelection(size - 1);
2770                        });
2771    }
2772
2773    private void cancelTransmission(Message message) {
2774        Transferable transferable = message.getTransferable();
2775        if (transferable != null) {
2776            transferable.cancel();
2777        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2778            activity.xmppConnectionService.markMessage(
2779                    message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2780        }
2781    }
2782
2783    private void retryDecryption(Message message) {
2784        message.setEncryption(Message.ENCRYPTION_PGP);
2785        activity.onConversationsListItemUpdated();
2786        refresh();
2787        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2788    }
2789
2790    public void privateMessageWith(final Jid counterpart) {
2791        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2792            activity.xmppConnectionService.sendChatState(conversation);
2793        }
2794        this.binding.textinput.setText("");
2795        this.conversation.setNextCounterpart(counterpart);
2796        updateChatMsgHint();
2797        updateSendButton();
2798        updateEditablity();
2799    }
2800
2801    private void correctMessage(Message message) {
2802        while (message.mergeable(message.next())) {
2803            message = message.next();
2804        }
2805        setThread(message.getThread());
2806        conversation.setUserSelectedThread(true);
2807        this.conversation.setCorrectingMessage(message);
2808        final Editable editable = binding.textinput.getText();
2809        this.conversation.setDraftMessage(editable.toString());
2810        this.binding.textinput.setText("");
2811        this.binding.textinput.append(message.getBody());
2812    }
2813
2814    private void highlightInConference(String nick) {
2815        final Editable editable = this.binding.textinput.getText();
2816        String oldString = editable.toString().trim();
2817        final int pos = this.binding.textinput.getSelectionStart();
2818        if (oldString.isEmpty() || pos == 0) {
2819            editable.insert(0, nick + ": ");
2820        } else {
2821            final char before = editable.charAt(pos - 1);
2822            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2823            if (before == '\n') {
2824                editable.insert(pos, nick + ": ");
2825            } else {
2826                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2827                    if (NickValidityChecker.check(
2828                            conversation,
2829                            Arrays.asList(
2830                                    editable.subSequence(0, pos - 2).toString().split(", ")))) {
2831                        editable.insert(pos - 2, ", " + nick);
2832                        return;
2833                    }
2834                }
2835                editable.insert(
2836                        pos,
2837                        (Character.isWhitespace(before) ? "" : " ")
2838                                + nick
2839                                + (Character.isWhitespace(after) ? "" : " "));
2840                if (Character.isWhitespace(after)) {
2841                    this.binding.textinput.setSelection(
2842                            this.binding.textinput.getSelectionStart() + 1);
2843                }
2844            }
2845        }
2846    }
2847
2848    @Override
2849    public void startActivityForResult(Intent intent, int requestCode) {
2850        final Activity activity = getActivity();
2851        if (activity instanceof ConversationsActivity) {
2852            ((ConversationsActivity) activity).clearPendingViewIntent();
2853        }
2854        super.startActivityForResult(intent, requestCode);
2855    }
2856
2857    @Override
2858    public void onSaveInstanceState(@NotNull Bundle outState) {
2859        super.onSaveInstanceState(outState);
2860        if (conversation != null) {
2861            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2862            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2863            final Uri uri = pendingTakePhotoUri.peek();
2864            if (uri != null) {
2865                outState.putString(STATE_PHOTO_URI, uri.toString());
2866            }
2867            final ScrollState scrollState = getScrollPosition();
2868            if (scrollState != null) {
2869                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2870            }
2871            final ArrayList<Attachment> attachments =
2872                    mediaPreviewAdapter == null
2873                            ? new ArrayList<>()
2874                            : mediaPreviewAdapter.getAttachments();
2875            if (attachments.size() > 0) {
2876                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2877            }
2878        }
2879    }
2880
2881    @Override
2882    public void onActivityCreated(Bundle savedInstanceState) {
2883        super.onActivityCreated(savedInstanceState);
2884        if (savedInstanceState == null) {
2885            return;
2886        }
2887        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2888        ArrayList<Attachment> attachments =
2889                savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2890        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2891        if (uuid != null) {
2892            QuickLoader.set(uuid);
2893            this.pendingConversationsUuid.push(uuid);
2894            if (attachments != null && attachments.size() > 0) {
2895                this.pendingMediaPreviews.push(attachments);
2896            }
2897            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2898            if (takePhotoUri != null) {
2899                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2900            }
2901            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2902        }
2903    }
2904
2905    @Override
2906    public void onStart() {
2907        super.onStart();
2908        if (this.reInitRequiredOnStart && this.conversation != null) {
2909            final Bundle extras = pendingExtras.pop();
2910            reInit(this.conversation, extras != null);
2911            if (extras != null) {
2912                processExtras(extras);
2913            }
2914        } else if (conversation == null
2915                && activity != null
2916                && activity.xmppConnectionService != null) {
2917            final String uuid = pendingConversationsUuid.pop();
2918            Log.d(
2919                    Config.LOGTAG,
2920                    "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
2921                            + uuid);
2922            if (uuid != null) {
2923                findAndReInitByUuidOrArchive(uuid);
2924            }
2925        }
2926    }
2927
2928    @Override
2929    public void onStop() {
2930        super.onStop();
2931        final Activity activity = getActivity();
2932        messageListAdapter.unregisterListenerInAudioPlayer();
2933        if (activity == null || !activity.isChangingConfigurations()) {
2934            hideSoftKeyboard(activity);
2935            messageListAdapter.stopAudioPlayer();
2936        }
2937        if (this.conversation != null) {
2938            final String msg = this.binding.textinput.getText().toString();
2939            storeNextMessage(msg);
2940            updateChatState(this.conversation, msg);
2941            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2942        }
2943        this.reInitRequiredOnStart = true;
2944        if (emojiPopup != null) emojiPopup.dismiss();
2945    }
2946
2947    private void updateChatState(final Conversation conversation, final String msg) {
2948        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2949        Account.State status = conversation.getAccount().getStatus();
2950        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2951            activity.xmppConnectionService.sendChatState(conversation);
2952        }
2953    }
2954
2955    private void saveMessageDraftStopAudioPlayer() {
2956        final Conversation previousConversation = this.conversation;
2957        if (this.activity == null || this.binding == null || previousConversation == null) {
2958            return;
2959        }
2960        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2961        final String msg = this.binding.textinput.getText().toString();
2962        storeNextMessage(msg);
2963        updateChatState(this.conversation, msg);
2964        messageListAdapter.stopAudioPlayer();
2965        mediaPreviewAdapter.clearPreviews();
2966        toggleInputMethod();
2967    }
2968
2969    public void reInit(final Conversation conversation, final Bundle extras) {
2970        QuickLoader.set(conversation.getUuid());
2971        final boolean changedConversation = this.conversation != conversation;
2972        if (changedConversation) {
2973            this.saveMessageDraftStopAudioPlayer();
2974        }
2975        this.clearPending();
2976        if (this.reInit(conversation, extras != null)) {
2977            if (extras != null) {
2978                processExtras(extras);
2979            }
2980            this.reInitRequiredOnStart = false;
2981        } else {
2982            this.reInitRequiredOnStart = true;
2983            pendingExtras.push(extras);
2984        }
2985        resetUnreadMessagesCount();
2986    }
2987
2988    private void reInit(Conversation conversation) {
2989        reInit(conversation, false);
2990    }
2991
2992    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2993        if (conversation == null) {
2994            return false;
2995        }
2996        final Conversation originalConversation = this.conversation;
2997        this.conversation = conversation;
2998        // once we set the conversation all is good and it will automatically do the right thing in
2999        // onStart()
3000        if (this.activity == null || this.binding == null) {
3001            return false;
3002        }
3003
3004        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3005            activity.onConversationArchived(this.conversation);
3006            return false;
3007        }
3008
3009        setThread(conversation.getThread());
3010        setupReply(conversation.getReplyTo());
3011
3012        stopScrolling();
3013        Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3014
3015        if (this.conversation.isRead() && hasExtras) {
3016            Log.d(Config.LOGTAG, "trimming conversation");
3017            this.conversation.trim();
3018        }
3019
3020        setupIme();
3021
3022        final boolean scrolledToBottomAndNoPending =
3023                this.scrolledToBottom() && pendingScrollState.peek() == null;
3024
3025        this.binding.textSendButton.setContentDescription(
3026                activity.getString(R.string.send_message_to_x, conversation.getName()));
3027        this.binding.textinput.setKeyboardListener(null);
3028        final boolean participating =
3029                conversation.getMode() == Conversational.MODE_SINGLE
3030                        || conversation.getMucOptions().participating();
3031        if (participating) {
3032            this.binding.textinput.setText(this.conversation.getNextMessage());
3033            this.binding.textinput.setSelection(this.binding.textinput.length());
3034        } else {
3035            this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3036        }
3037        this.binding.textinput.setKeyboardListener(this);
3038        messageListAdapter.updatePreferences();
3039        refresh(false);
3040        activity.invalidateOptionsMenu();
3041        this.conversation.messagesLoaded.set(true);
3042        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3043
3044        if (hasExtras || scrolledToBottomAndNoPending) {
3045            resetUnreadMessagesCount();
3046            synchronized (this.messageList) {
3047                Log.d(Config.LOGTAG, "jump to first unread message");
3048                final Message first = conversation.getFirstUnreadMessage();
3049                final int bottom = Math.max(0, this.messageList.size() - 1);
3050                final int pos;
3051                final boolean jumpToBottom;
3052                if (first == null) {
3053                    pos = bottom;
3054                    jumpToBottom = true;
3055                } else {
3056                    int i = getIndexOf(first.getUuid(), this.messageList);
3057                    pos = i < 0 ? bottom : i;
3058                    jumpToBottom = false;
3059                }
3060                setSelection(pos, jumpToBottom);
3061            }
3062        }
3063
3064        this.binding.messagesView.post(this::fireReadEvent);
3065        // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3066        // layout which might be unnecessary since we can *see* it
3067        activity.xmppConnectionService
3068                .getNotificationService()
3069                .setOpenConversation(this.conversation);
3070
3071        if (commandAdapter != null && conversation != originalConversation) {
3072            commandAdapter.clear();
3073            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3074            refreshCommands(false);
3075        }
3076        if (commandAdapter == null && conversation != null) {
3077            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3078            commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3079            binding.commandsView.setAdapter(commandAdapter);
3080            binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3081                if (activity == null) return;
3082
3083                final Element command = commandAdapter.getItem(position);
3084                activity.startCommand(ConversationFragment.this.conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
3085            });
3086            refreshCommands(false);
3087        }
3088
3089        return true;
3090    }
3091
3092    public void refreshForNewCaps() {
3093        refreshCommands(true);
3094    }
3095
3096    protected void refreshCommands(boolean delayShow) {
3097        if (commandAdapter == null) return;
3098
3099        Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3100        if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3101            commandJid = conversation.getJid().asBareJid();
3102        }
3103        if (commandJid == null && conversation.getJid().isDomainJid()) {
3104            commandJid = conversation.getJid();
3105        }
3106        if (commandJid == null) {
3107            conversation.hideViewPager();
3108        } else {
3109            if (!delayShow) conversation.showViewPager();
3110            binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3111            activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
3112                if (activity == null) return;
3113
3114                activity.runOnUiThread(() -> {
3115                    if (iq.getType() == IqPacket.TYPE.RESULT) {
3116                        binding.commandsViewProgressbar.setVisibility(View.GONE);
3117                        commandAdapter.clear();
3118                        for (Element child : iq.query().getChildren()) {
3119                            if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3120                            commandAdapter.add(child);
3121                        }
3122                    }
3123
3124                    if (commandAdapter.getCount() < 1) {
3125                        conversation.hideViewPager();
3126                    } else if (delayShow) {
3127                        conversation.showViewPager();
3128                    }
3129                });
3130            });
3131        }
3132    }
3133
3134    private void resetUnreadMessagesCount() {
3135        lastMessageUuid = null;
3136        hideUnreadMessagesCount();
3137    }
3138
3139    private void hideUnreadMessagesCount() {
3140        if (this.binding == null) {
3141            return;
3142        }
3143        this.binding.scrollToBottomButton.setEnabled(false);
3144        this.binding.scrollToBottomButton.hide();
3145        this.binding.unreadCountCustomView.setVisibility(View.GONE);
3146    }
3147
3148    private void setSelection(int pos, boolean jumpToBottom) {
3149        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3150        this.binding.messagesView.post(
3151                () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3152        this.binding.messagesView.post(this::fireReadEvent);
3153    }
3154
3155    private boolean scrolledToBottom() {
3156        return this.binding != null && scrolledToBottom(this.binding.messagesView);
3157    }
3158
3159    private void processExtras(final Bundle extras) {
3160        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3161        final String text = extras.getString(Intent.EXTRA_TEXT);
3162        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3163        final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3164        final String postInitAction =
3165                extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3166        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3167        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3168        final boolean doNotAppend =
3169                extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3170        final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3171        final List<Uri> uris = extractUris(extras);
3172        if (uris != null && uris.size() > 0) {
3173            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3174                mediaPreviewAdapter.addMediaPreviews(
3175                        Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3176            } else {
3177                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3178                mediaPreviewAdapter.addMediaPreviews(
3179                        Attachment.of(getActivity(), cleanedUris, type));
3180            }
3181            toggleInputMethod();
3182            return;
3183        }
3184        if (nick != null) {
3185            if (pm) {
3186                Jid jid = conversation.getJid();
3187                try {
3188                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3189                    privateMessageWith(next);
3190                } catch (final IllegalArgumentException ignored) {
3191                    // do nothing
3192                }
3193            } else {
3194                final MucOptions mucOptions = conversation.getMucOptions();
3195                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3196                    highlightInConference(nick);
3197                }
3198            }
3199        } else {
3200            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3201                mediaPreviewAdapter.addMediaPreviews(
3202                        Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3203                toggleInputMethod();
3204                return;
3205            } else if (text != null && asQuote) {
3206                quoteText(text);
3207            } else {
3208                appendText(text, doNotAppend);
3209            }
3210        }
3211        if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3212            attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3213            return;
3214        }
3215        if ("call".equals(postInitAction)) {
3216            checkPermissionAndTriggerAudioCall();
3217        }
3218        if ("message".equals(postInitAction)) {
3219            binding.conversationViewPager.post(() -> {
3220                binding.conversationViewPager.setCurrentItem(0);
3221            });
3222        }
3223        if ("command".equals(postInitAction)) {
3224            binding.conversationViewPager.post(() -> {
3225                PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3226                if (adapter != null && adapter.getCount() > 1) {
3227                    binding.conversationViewPager.setCurrentItem(1);
3228                }
3229                final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3230                Jid commandJid = null;
3231                if (jid != null) {
3232                    try {
3233                        commandJid = Jid.of(jid);
3234                    } catch (final IllegalArgumentException e) { }
3235                }
3236                if (commandJid == null || !commandJid.isFullJid()) {
3237                    final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3238                    if (discoJid != null) commandJid = discoJid;
3239                }
3240                if (node != null && commandJid != null) {
3241                    conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3242                }
3243            });
3244            return;
3245        }
3246        final Message message =
3247                downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3248        if ("webxdc".equals(postInitAction)) {
3249            if (message == null) return;
3250
3251            Cid webxdcCid = message.getFileParams().getCids().get(0);
3252            WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
3253            Conversation conversation = (Conversation) message.getConversation();
3254            if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3255                conversation.startWebxdc(webxdc);
3256            }
3257        }
3258        if (message != null) {
3259            startDownloadable(message);
3260        }
3261        if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3262            if (!conversation.switchToSession("jabber:iq:register")) {
3263                conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3264            }
3265        }
3266    }
3267
3268    private Element commandFor(final Jid jid, final String node) {
3269        if (commandAdapter != null) {
3270            for (int i = 0; i < commandAdapter.getCount(); i++) {
3271                Element command = commandAdapter.getItem(i);
3272                final String commandNode = command.getAttribute("node");
3273                if (commandNode == null || !commandNode.equals(node)) continue;
3274
3275                final Jid commandJid = command.getAttributeAsJid("jid");
3276                if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3277
3278                return command;
3279            }
3280        }
3281
3282        return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3283    }
3284
3285    private List<Uri> extractUris(final Bundle extras) {
3286        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3287        if (uris != null) {
3288            return uris;
3289        }
3290        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3291        if (uri != null) {
3292            return Collections.singletonList(uri);
3293        } else {
3294            return null;
3295        }
3296    }
3297
3298    private List<Uri> cleanUris(final List<Uri> uris) {
3299        final Iterator<Uri> iterator = uris.iterator();
3300        while (iterator.hasNext()) {
3301            final Uri uri = iterator.next();
3302            if (FileBackend.weOwnFile(uri)) {
3303                iterator.remove();
3304                Toast.makeText(
3305                                getActivity(),
3306                                R.string.security_violation_not_attaching_file,
3307                                Toast.LENGTH_SHORT)
3308                        .show();
3309            }
3310        }
3311        return uris;
3312    }
3313
3314    private boolean showBlockSubmenu(View view) {
3315        final Jid jid = conversation.getJid();
3316        final boolean showReject =
3317                !conversation.isWithStranger()
3318                        && conversation
3319                                .getContact()
3320                                .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3321        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3322        popupMenu.inflate(R.menu.block);
3323        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3324        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3325        popupMenu.setOnMenuItemClickListener(
3326                menuItem -> {
3327                    Blockable blockable;
3328                    switch (menuItem.getItemId()) {
3329                        case R.id.reject:
3330                            activity.xmppConnectionService.stopPresenceUpdatesTo(
3331                                    conversation.getContact());
3332                            updateSnackBar(conversation);
3333                            return true;
3334                        case R.id.block_domain:
3335                            blockable =
3336                                    conversation
3337                                            .getAccount()
3338                                            .getRoster()
3339                                            .getContact(jid.getDomain());
3340                            break;
3341                        default:
3342                            blockable = conversation;
3343                    }
3344                    BlockContactDialog.show(activity, blockable);
3345                    return true;
3346                });
3347        popupMenu.show();
3348        return true;
3349    }
3350
3351    private void updateSnackBar(final Conversation conversation) {
3352        final Account account = conversation.getAccount();
3353        final XmppConnection connection = account.getXmppConnection();
3354        final int mode = conversation.getMode();
3355        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3356        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3357            return;
3358        }
3359        if (account.getStatus() == Account.State.DISABLED) {
3360            showSnackbar(
3361                    R.string.this_account_is_disabled,
3362                    R.string.enable,
3363                    this.mEnableAccountListener);
3364        } else if (conversation.isBlocked()) {
3365            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3366        } else if (contact != null
3367                && !contact.showInRoster()
3368                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3369            showSnackbar(
3370                    R.string.contact_added_you,
3371                    R.string.add_back,
3372                    this.mAddBackClickListener,
3373                    this.mLongPressBlockListener);
3374        } else if (contact != null
3375                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3376            showSnackbar(
3377                    R.string.contact_asks_for_presence_subscription,
3378                    R.string.allow,
3379                    this.mAllowPresenceSubscription,
3380                    this.mLongPressBlockListener);
3381        } else if (mode == Conversation.MODE_MULTI
3382                && !conversation.getMucOptions().online()
3383                && account.getStatus() == Account.State.ONLINE) {
3384            switch (conversation.getMucOptions().getError()) {
3385                case NICK_IN_USE:
3386                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3387                    break;
3388                case NO_RESPONSE:
3389                    showSnackbar(R.string.joining_conference, 0, null);
3390                    break;
3391                case SERVER_NOT_FOUND:
3392                    if (conversation.receivedMessagesCount() > 0) {
3393                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3394                    } else {
3395                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3396                    }
3397                    break;
3398                case REMOTE_SERVER_TIMEOUT:
3399                    if (conversation.receivedMessagesCount() > 0) {
3400                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3401                    } else {
3402                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3403                    }
3404                    break;
3405                case PASSWORD_REQUIRED:
3406                    showSnackbar(
3407                            R.string.conference_requires_password,
3408                            R.string.enter_password,
3409                            enterPassword);
3410                    break;
3411                case BANNED:
3412                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3413                    break;
3414                case MEMBERS_ONLY:
3415                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3416                    break;
3417                case RESOURCE_CONSTRAINT:
3418                    showSnackbar(
3419                            R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3420                    break;
3421                case KICKED:
3422                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3423                    break;
3424                case TECHNICAL_PROBLEMS:
3425                    showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3426                    break;
3427                case UNKNOWN:
3428                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3429                    break;
3430                case INVALID_NICK:
3431                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3432                case SHUTDOWN:
3433                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3434                    break;
3435                case DESTROYED:
3436                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3437                    break;
3438                case NON_ANONYMOUS:
3439                    showSnackbar(
3440                            R.string.group_chat_will_make_your_jabber_id_public,
3441                            R.string.join,
3442                            acceptJoin);
3443                    break;
3444                default:
3445                    hideSnackbar();
3446                    break;
3447            }
3448        } else if (account.hasPendingPgpIntent(conversation)) {
3449            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3450        } else if (connection != null
3451                && connection.getFeatures().blocking()
3452                && conversation.countMessages() != 0
3453                && !conversation.isBlocked()
3454                && conversation.isWithStranger()) {
3455            showSnackbar(
3456                    R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3457        } else {
3458            hideSnackbar();
3459        }
3460    }
3461
3462    @Override
3463    public void refresh() {
3464        if (this.binding == null) {
3465            Log.d(
3466                    Config.LOGTAG,
3467                    "ConversationFragment.refresh() skipped updated because view binding was null");
3468            return;
3469        }
3470        if (this.conversation != null
3471                && this.activity != null
3472                && this.activity.xmppConnectionService != null) {
3473            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3474                activity.onConversationArchived(this.conversation);
3475                return;
3476            }
3477        }
3478        this.refresh(true);
3479    }
3480
3481    private void refresh(boolean notifyConversationRead) {
3482        synchronized (this.messageList) {
3483            if (this.conversation != null) {
3484                if (messageListAdapter.hasSelection()) {
3485                    if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3486                } else {
3487                    conversation.populateWithMessages(this.messageList);
3488                    updateStatusMessages();
3489                    this.messageListAdapter.notifyDataSetChanged();
3490                }
3491                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3492                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3493                    binding.unreadCountCustomView.setUnreadCount(
3494                            conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3495                }
3496                updateSnackBar(conversation);
3497                if (activity != null) updateChatMsgHint();
3498                if (notifyConversationRead && activity != null) {
3499                    binding.messagesView.post(this::fireReadEvent);
3500                }
3501                updateSendButton();
3502                updateEditablity();
3503                conversation.refreshSessions();
3504            }
3505        }
3506    }
3507
3508    protected void messageSent() {
3509        setThread(null);
3510        conversation.setUserSelectedThread(false);
3511        mSendingPgpMessage.set(false);
3512        this.binding.textinput.setText("");
3513        if (conversation.setCorrectingMessage(null)) {
3514            this.binding.textinput.append(conversation.getDraftMessage());
3515            conversation.setDraftMessage(null);
3516        }
3517        storeNextMessage();
3518        updateChatMsgHint();
3519        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3520        final boolean prefScrollToBottom =
3521                p.getBoolean(
3522                        "scroll_to_bottom",
3523                        activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3524        if (prefScrollToBottom || scrolledToBottom()) {
3525            new Handler()
3526                    .post(
3527                            () -> {
3528                                int size = messageList.size();
3529                                this.binding.messagesView.setSelection(size - 1);
3530                            });
3531        }
3532    }
3533
3534    private boolean storeNextMessage() {
3535        return storeNextMessage(this.binding.textinput.getText().toString());
3536    }
3537
3538    private boolean storeNextMessage(String msg) {
3539        final boolean participating =
3540                conversation.getMode() == Conversational.MODE_SINGLE
3541                        || conversation.getMucOptions().participating();
3542        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3543                && participating
3544                && this.conversation.setNextMessage(msg)) {
3545            this.activity.xmppConnectionService.updateConversation(this.conversation);
3546            return true;
3547        }
3548        return false;
3549    }
3550
3551    public void doneSendingPgpMessage() {
3552        mSendingPgpMessage.set(false);
3553    }
3554
3555    public long getMaxHttpUploadSize(Conversation conversation) {
3556        final XmppConnection connection = conversation.getAccount().getXmppConnection();
3557        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3558    }
3559
3560    private boolean canWrite() {
3561        return
3562                this.conversation.getMode() == Conversation.MODE_SINGLE
3563                        || this.conversation.getMucOptions().participating()
3564                        || this.conversation.getNextCounterpart() != null;
3565    }
3566
3567    private void updateEditablity() {
3568        boolean canWrite = canWrite();
3569        this.binding.textinput.setFocusable(canWrite);
3570        this.binding.textinput.setFocusableInTouchMode(canWrite);
3571        this.binding.textSendButton.setEnabled(canWrite);
3572        this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
3573        this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
3574        this.binding.textinput.setCursorVisible(canWrite);
3575        this.binding.textinput.setEnabled(canWrite);
3576    }
3577
3578    public void updateSendButton() {
3579        boolean hasAttachments =
3580                mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3581        final Conversation c = this.conversation;
3582        final Presence.Status status;
3583        final String text =
3584                this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3585        final SendButtonAction action;
3586        if (hasAttachments) {
3587            action = SendButtonAction.TEXT;
3588        } else {
3589            action = SendButtonTool.getAction(getActivity(), c, text);
3590        }
3591        if (c.getAccount().getStatus() == Account.State.ONLINE) {
3592            if (activity != null
3593                    && activity.xmppConnectionService != null
3594                    && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3595                status = Presence.Status.OFFLINE;
3596            } else if (c.getMode() == Conversation.MODE_SINGLE) {
3597                status = c.getContact().getShownStatus();
3598            } else {
3599                status =
3600                        c.getMucOptions().online()
3601                                ? Presence.Status.ONLINE
3602                                : Presence.Status.OFFLINE;
3603            }
3604        } else {
3605            status = Presence.Status.OFFLINE;
3606        }
3607        this.binding.textSendButton.setTag(action);
3608        final Activity activity = getActivity();
3609        if (activity != null) {
3610            this.binding.textSendButton.setImageResource(
3611                    SendButtonTool.getSendButtonImageResource(activity, action, status));
3612        }
3613
3614        ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3615        if (identiconWidth < 0) identiconWidth = params.width;
3616        if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
3617            binding.conversationViewPager.setCurrentItem(0);
3618            params.width = conversation.getThread() == null ? 0 : identiconWidth;
3619        } else {
3620            params.width = identiconWidth;
3621        }
3622        if (!canWrite()) params.width = 0;
3623        binding.threadIdenticonLayout.setLayoutParams(params);
3624    }
3625
3626    protected void updateStatusMessages() {
3627        DateSeparator.addAll(this.messageList);
3628        if (showLoadMoreMessages(conversation)) {
3629            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3630        }
3631        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3632            ChatState state = conversation.getIncomingChatState();
3633            if (state == ChatState.COMPOSING) {
3634                this.messageList.add(
3635                        Message.createStatusMessage(
3636                                conversation,
3637                                getString(R.string.contact_is_typing, conversation.getName())));
3638            } else if (state == ChatState.PAUSED) {
3639                this.messageList.add(
3640                        Message.createStatusMessage(
3641                                conversation,
3642                                getString(
3643                                        R.string.contact_has_stopped_typing,
3644                                        conversation.getName())));
3645            } else {
3646                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3647                    final Message message = this.messageList.get(i);
3648                    if (message.getType() != Message.TYPE_STATUS) {
3649                        if (message.getStatus() == Message.STATUS_RECEIVED) {
3650                            return;
3651                        } else {
3652                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3653                                this.messageList.add(
3654                                        i + 1,
3655                                        Message.createStatusMessage(
3656                                                conversation,
3657                                                getString(
3658                                                        R.string.contact_has_read_up_to_this_point,
3659                                                        conversation.getName())));
3660                                return;
3661                            }
3662                        }
3663                    }
3664                }
3665            }
3666        } else {
3667            final MucOptions mucOptions = conversation.getMucOptions();
3668            final List<MucOptions.User> allUsers = mucOptions.getUsers();
3669            final Set<ReadByMarker> addedMarkers = new HashSet<>();
3670            ChatState state = ChatState.COMPOSING;
3671            List<MucOptions.User> users =
3672                    conversation.getMucOptions().getUsersWithChatState(state, 5);
3673            if (users.size() == 0) {
3674                state = ChatState.PAUSED;
3675                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3676            }
3677            if (mucOptions.isPrivateAndNonAnonymous()) {
3678                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3679                    final Set<ReadByMarker> markersForMessage =
3680                            messageList.get(i).getReadByMarkers();
3681                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
3682                    for (ReadByMarker marker : markersForMessage) {
3683                        if (!ReadByMarker.contains(marker, addedMarkers)) {
3684                            addedMarkers.add(
3685                                    marker); // may be put outside this condition. set should do
3686                                             // dedup anyway
3687                            MucOptions.User user = mucOptions.findUser(marker);
3688                            if (user != null && !users.contains(user)) {
3689                                shownMarkers.add(user);
3690                            }
3691                        }
3692                    }
3693                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3694                    final Message statusMessage;
3695                    final int size = shownMarkers.size();
3696                    if (size > 1) {
3697                        final String body;
3698                        if (size <= 4) {
3699                            body =
3700                                    getString(
3701                                            R.string.contacts_have_read_up_to_this_point,
3702                                            UIHelper.concatNames(shownMarkers));
3703                        } else if (ReadByMarker.allUsersRepresented(
3704                                allUsers, markersForMessage, markerForSender)) {
3705                            body = getString(R.string.everyone_has_read_up_to_this_point);
3706                        } else {
3707                            body =
3708                                    getString(
3709                                            R.string.contacts_and_n_more_have_read_up_to_this_point,
3710                                            UIHelper.concatNames(shownMarkers, 3),
3711                                            size - 3);
3712                        }
3713                        statusMessage = Message.createStatusMessage(conversation, body);
3714                        statusMessage.setCounterparts(shownMarkers);
3715                    } else if (size == 1) {
3716                        statusMessage =
3717                                Message.createStatusMessage(
3718                                        conversation,
3719                                        getString(
3720                                                R.string.contact_has_read_up_to_this_point,
3721                                                UIHelper.getDisplayName(shownMarkers.get(0))));
3722                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3723                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3724                    } else {
3725                        statusMessage = null;
3726                    }
3727                    if (statusMessage != null) {
3728                        this.messageList.add(i + 1, statusMessage);
3729                    }
3730                    addedMarkers.add(markerForSender);
3731                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3732                        break;
3733                    }
3734                }
3735            }
3736            if (users.size() > 0) {
3737                Message statusMessage;
3738                if (users.size() == 1) {
3739                    MucOptions.User user = users.get(0);
3740                    int id =
3741                            state == ChatState.COMPOSING
3742                                    ? R.string.contact_is_typing
3743                                    : R.string.contact_has_stopped_typing;
3744                    statusMessage =
3745                            Message.createStatusMessage(
3746                                    conversation, getString(id, UIHelper.getDisplayName(user)));
3747                    statusMessage.setTrueCounterpart(user.getRealJid());
3748                    statusMessage.setCounterpart(user.getFullJid());
3749                } else {
3750                    int id =
3751                            state == ChatState.COMPOSING
3752                                    ? R.string.contacts_are_typing
3753                                    : R.string.contacts_have_stopped_typing;
3754                    statusMessage =
3755                            Message.createStatusMessage(
3756                                    conversation, getString(id, UIHelper.concatNames(users)));
3757                    statusMessage.setCounterparts(users);
3758                }
3759                this.messageList.add(statusMessage);
3760            }
3761        }
3762    }
3763
3764    private void stopScrolling() {
3765        long now = SystemClock.uptimeMillis();
3766        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3767        binding.messagesView.dispatchTouchEvent(cancel);
3768    }
3769
3770    private boolean showLoadMoreMessages(final Conversation c) {
3771        if (activity == null || activity.xmppConnectionService == null) {
3772            return false;
3773        }
3774        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3775        final MessageArchiveService service =
3776                activity.xmppConnectionService.getMessageArchiveService();
3777        return mam
3778                && (c.getLastClearHistory().getTimestamp() != 0
3779                        || (c.countMessages() == 0
3780                                && c.messagesLoaded.get()
3781                                && c.hasMessagesLeftOnServer()
3782                                && !service.queryInProgress(c)));
3783    }
3784
3785    private boolean hasMamSupport(final Conversation c) {
3786        if (c.getMode() == Conversation.MODE_SINGLE) {
3787            final XmppConnection connection = c.getAccount().getXmppConnection();
3788            return connection != null && connection.getFeatures().mam();
3789        } else {
3790            return c.getMucOptions().mamSupport();
3791        }
3792    }
3793
3794    protected void showSnackbar(
3795            final int message, final int action, final OnClickListener clickListener) {
3796        showSnackbar(message, action, clickListener, null);
3797    }
3798
3799    protected void showSnackbar(
3800            final int message,
3801            final int action,
3802            final OnClickListener clickListener,
3803            final View.OnLongClickListener longClickListener) {
3804        this.binding.snackbar.setVisibility(View.VISIBLE);
3805        this.binding.snackbar.setOnClickListener(null);
3806        this.binding.snackbarMessage.setText(message);
3807        this.binding.snackbarMessage.setOnClickListener(null);
3808        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3809        if (action != 0) {
3810            this.binding.snackbarAction.setText(action);
3811        }
3812        this.binding.snackbarAction.setOnClickListener(clickListener);
3813        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3814    }
3815
3816    protected void hideSnackbar() {
3817        this.binding.snackbar.setVisibility(View.GONE);
3818    }
3819
3820    protected void sendMessage(Message message) {
3821        new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
3822        messageSent();
3823    }
3824
3825    protected void sendPgpMessage(final Message message) {
3826        final XmppConnectionService xmppService = activity.xmppConnectionService;
3827        final Contact contact = message.getConversation().getContact();
3828        if (!activity.hasPgp()) {
3829            activity.showInstallPgpDialog();
3830            return;
3831        }
3832        if (conversation.getAccount().getPgpSignature() == null) {
3833            activity.announcePgp(
3834                    conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3835            return;
3836        }
3837        if (!mSendingPgpMessage.compareAndSet(false, true)) {
3838            Log.d(Config.LOGTAG, "sending pgp message already in progress");
3839        }
3840        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3841            if (contact.getPgpKeyId() != 0) {
3842                xmppService
3843                        .getPgpEngine()
3844                        .hasKey(
3845                                contact,
3846                                new UiCallback<Contact>() {
3847
3848                                    @Override
3849                                    public void userInputRequired(
3850                                            PendingIntent pi, Contact contact) {
3851                                        startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3852                                    }
3853
3854                                    @Override
3855                                    public void success(Contact contact) {
3856                                        encryptTextMessage(message);
3857                                    }
3858
3859                                    @Override
3860                                    public void error(int error, Contact contact) {
3861                                        activity.runOnUiThread(
3862                                                () ->
3863                                                        Toast.makeText(
3864                                                                        activity,
3865                                                                        R.string
3866                                                                                .unable_to_connect_to_keychain,
3867                                                                        Toast.LENGTH_SHORT)
3868                                                                .show());
3869                                        mSendingPgpMessage.set(false);
3870                                    }
3871                                });
3872
3873            } else {
3874                showNoPGPKeyDialog(
3875                        false,
3876                        (dialog, which) -> {
3877                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3878                            xmppService.updateConversation(conversation);
3879                            message.setEncryption(Message.ENCRYPTION_NONE);
3880                            xmppService.sendMessage(message);
3881                            messageSent();
3882                        });
3883            }
3884        } else {
3885            if (conversation.getMucOptions().pgpKeysInUse()) {
3886                if (!conversation.getMucOptions().everybodyHasKeys()) {
3887                    Toast warning =
3888                            Toast.makeText(
3889                                    getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3890                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3891                    warning.show();
3892                }
3893                encryptTextMessage(message);
3894            } else {
3895                showNoPGPKeyDialog(
3896                        true,
3897                        (dialog, which) -> {
3898                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3899                            message.setEncryption(Message.ENCRYPTION_NONE);
3900                            xmppService.updateConversation(conversation);
3901                            xmppService.sendMessage(message);
3902                            messageSent();
3903                        });
3904            }
3905        }
3906    }
3907
3908    public void encryptTextMessage(Message message) {
3909        activity.xmppConnectionService
3910                .getPgpEngine()
3911                .encrypt(
3912                        message,
3913                        new UiCallback<Message>() {
3914
3915                            @Override
3916                            public void userInputRequired(PendingIntent pi, Message message) {
3917                                startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3918                            }
3919
3920                            @Override
3921                            public void success(Message message) {
3922                                // TODO the following two call can be made before the callback
3923                                getActivity().runOnUiThread(() -> messageSent());
3924                            }
3925
3926                            @Override
3927                            public void error(final int error, Message message) {
3928                                getActivity()
3929                                        .runOnUiThread(
3930                                                () -> {
3931                                                    doneSendingPgpMessage();
3932                                                    Toast.makeText(
3933                                                                    getActivity(),
3934                                                                    error == 0
3935                                                                            ? R.string
3936                                                                                    .unable_to_connect_to_keychain
3937                                                                            : error,
3938                                                                    Toast.LENGTH_SHORT)
3939                                                            .show();
3940                                                });
3941                            }
3942                        });
3943    }
3944
3945    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3946        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3947        builder.setIconAttribute(android.R.attr.alertDialogIcon);
3948        if (plural) {
3949            builder.setTitle(getString(R.string.no_pgp_keys));
3950            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3951        } else {
3952            builder.setTitle(getString(R.string.no_pgp_key));
3953            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3954        }
3955        builder.setNegativeButton(getString(R.string.cancel), null);
3956        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3957        builder.create().show();
3958    }
3959
3960    public void appendText(String text, final boolean doNotAppend) {
3961        if (text == null) {
3962            return;
3963        }
3964        final Editable editable = this.binding.textinput.getText();
3965        String previous = editable == null ? "" : editable.toString();
3966        if (doNotAppend && !TextUtils.isEmpty(previous)) {
3967            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3968                    .show();
3969            return;
3970        }
3971        if (UIHelper.isLastLineQuote(previous)) {
3972            text = '\n' + text;
3973        } else if (previous.length() != 0
3974                && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3975            text = " " + text;
3976        }
3977        this.binding.textinput.append(text);
3978    }
3979
3980    @Override
3981    public boolean onEnterPressed(final boolean isCtrlPressed) {
3982        if (isCtrlPressed || enterIsSend()) {
3983            sendMessage();
3984            return true;
3985        }
3986        return false;
3987    }
3988
3989    private boolean enterIsSend() {
3990        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3991        return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3992    }
3993
3994    public boolean onArrowUpCtrlPressed() {
3995        final Message lastEditableMessage =
3996                conversation == null ? null : conversation.getLastEditableMessage();
3997        if (lastEditableMessage != null) {
3998            correctMessage(lastEditableMessage);
3999            return true;
4000        } else {
4001            Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4002                    .show();
4003            return false;
4004        }
4005    }
4006
4007    @Override
4008    public void onTypingStarted() {
4009        final XmppConnectionService service =
4010                activity == null ? null : activity.xmppConnectionService;
4011        if (service == null) {
4012            return;
4013        }
4014        final Account.State status = conversation.getAccount().getStatus();
4015        if (status == Account.State.ONLINE
4016                && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4017            service.sendChatState(conversation);
4018        }
4019        runOnUiThread(this::updateSendButton);
4020    }
4021
4022    @Override
4023    public void onTypingStopped() {
4024        final XmppConnectionService service =
4025                activity == null ? null : activity.xmppConnectionService;
4026        if (service == null) {
4027            return;
4028        }
4029        final Account.State status = conversation.getAccount().getStatus();
4030        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4031            service.sendChatState(conversation);
4032        }
4033    }
4034
4035    @Override
4036    public void onTextDeleted() {
4037        final XmppConnectionService service =
4038                activity == null ? null : activity.xmppConnectionService;
4039        if (service == null) {
4040            return;
4041        }
4042        final Account.State status = conversation.getAccount().getStatus();
4043        if (status == Account.State.ONLINE
4044                && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4045            service.sendChatState(conversation);
4046        }
4047        if (storeNextMessage()) {
4048            runOnUiThread(
4049                    () -> {
4050                        if (activity == null) {
4051                            return;
4052                        }
4053                        activity.onConversationsListItemUpdated();
4054                    });
4055        }
4056        runOnUiThread(this::updateSendButton);
4057    }
4058
4059    @Override
4060    public void onTextChanged() {
4061        if (conversation != null && conversation.getCorrectingMessage() != null) {
4062            runOnUiThread(this::updateSendButton);
4063        }
4064    }
4065
4066    @Override
4067    public boolean onTabPressed(boolean repeated) {
4068        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4069            return false;
4070        }
4071        if (repeated) {
4072            completionIndex++;
4073        } else {
4074            lastCompletionLength = 0;
4075            completionIndex = 0;
4076            final String content = this.binding.textinput.getText().toString();
4077            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4078            int start =
4079                    lastCompletionCursor > 0
4080                            ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4081                            : 0;
4082            firstWord = start == 0;
4083            incomplete = content.substring(start, lastCompletionCursor);
4084        }
4085        List<String> completions = new ArrayList<>();
4086        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4087            String name = user.getNick();
4088            if (name != null && name.startsWith(incomplete)) {
4089                completions.add(name + (firstWord ? ": " : " "));
4090            }
4091        }
4092        Collections.sort(completions);
4093        if (completions.size() > completionIndex) {
4094            String completion = completions.get(completionIndex).substring(incomplete.length());
4095            this.binding
4096                    .textinput
4097                    .getEditableText()
4098                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4099            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4100            lastCompletionLength = completion.length();
4101        } else {
4102            completionIndex = -1;
4103            this.binding
4104                    .textinput
4105                    .getEditableText()
4106                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4107            lastCompletionLength = 0;
4108        }
4109        return true;
4110    }
4111
4112    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4113        try {
4114            getActivity()
4115                    .startIntentSenderForResult(
4116                            pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
4117        } catch (final SendIntentException ignored) {
4118        }
4119    }
4120
4121    @Override
4122    public void onBackendConnected() {
4123        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4124        setupEmojiSearch();
4125        String uuid = pendingConversationsUuid.pop();
4126        if (uuid != null) {
4127            if (!findAndReInitByUuidOrArchive(uuid)) {
4128                return;
4129            }
4130        } else {
4131            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4132                clearPending();
4133                activity.onConversationArchived(conversation);
4134                return;
4135            }
4136        }
4137        ActivityResult activityResult = postponedActivityResult.pop();
4138        if (activityResult != null) {
4139            handleActivityResult(activityResult);
4140        }
4141        clearPending();
4142    }
4143
4144    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4145        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4146        if (conversation == null) {
4147            clearPending();
4148            activity.onConversationArchived(null);
4149            return false;
4150        }
4151        reInit(conversation);
4152        ScrollState scrollState = pendingScrollState.pop();
4153        String lastMessageUuid = pendingLastMessageUuid.pop();
4154        List<Attachment> attachments = pendingMediaPreviews.pop();
4155        if (scrollState != null) {
4156            setScrollPosition(scrollState, lastMessageUuid);
4157        }
4158        if (attachments != null && attachments.size() > 0) {
4159            Log.d(Config.LOGTAG, "had attachments on restore");
4160            mediaPreviewAdapter.addMediaPreviews(attachments);
4161            toggleInputMethod();
4162        }
4163        return true;
4164    }
4165
4166    private void clearPending() {
4167        if (postponedActivityResult.clear()) {
4168            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4169            if (pendingTakePhotoUri.clear()) {
4170                Log.e(Config.LOGTAG, "cleared pending photo uri");
4171            }
4172        }
4173        if (pendingScrollState.clear()) {
4174            Log.e(Config.LOGTAG, "cleared scroll state");
4175        }
4176        if (pendingConversationsUuid.clear()) {
4177            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4178        }
4179        if (pendingMediaPreviews.clear()) {
4180            Log.e(Config.LOGTAG, "cleared pending media previews");
4181        }
4182    }
4183
4184    public Conversation getConversation() {
4185        return conversation;
4186    }
4187
4188    @Override
4189    public void onContactPictureLongClicked(View v, final Message message) {
4190        final String fingerprint;
4191        if (message.getEncryption() == Message.ENCRYPTION_PGP
4192                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4193            fingerprint = "pgp";
4194        } else {
4195            fingerprint = message.getFingerprint();
4196        }
4197        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4198        final Contact contact = message.getContact();
4199        if (message.getStatus() <= Message.STATUS_RECEIVED
4200                && (contact == null || !contact.isSelf())) {
4201            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4202                final Jid cp = message.getCounterpart();
4203                if (cp == null || cp.isBareJid()) {
4204                    return;
4205                }
4206                final Jid tcp = message.getTrueCounterpart();
4207                final User userByRealJid =
4208                        tcp != null
4209                                ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
4210                                : null;
4211                final User user =
4212                        userByRealJid != null
4213                                ? userByRealJid
4214                                : conversation.getMucOptions().findUserByFullJid(cp);
4215                if (user == null) return;
4216                popupMenu.inflate(R.menu.muc_details_context);
4217                final Menu menu = popupMenu.getMenu();
4218                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4219                        activity, menu, conversation, user);
4220                popupMenu.setOnMenuItemClickListener(
4221                        menuItem ->
4222                                MucDetailsContextMenuHelper.onContextItemSelected(
4223                                        menuItem, user, activity, fingerprint));
4224            } else {
4225                popupMenu.inflate(R.menu.one_on_one_context);
4226                popupMenu.setOnMenuItemClickListener(
4227                        item -> {
4228                            switch (item.getItemId()) {
4229                                case R.id.action_contact_details:
4230                                    activity.switchToContactDetails(
4231                                            message.getContact(), fingerprint);
4232                                    break;
4233                                case R.id.action_show_qr_code:
4234                                    activity.showQrCode(
4235                                            "xmpp:"
4236                                                    + message.getContact()
4237                                                            .getJid()
4238                                                            .asBareJid()
4239                                                            .toEscapedString());
4240                                    break;
4241                            }
4242                            return true;
4243                        });
4244            }
4245        } else {
4246            popupMenu.inflate(R.menu.account_context);
4247            final Menu menu = popupMenu.getMenu();
4248            menu.findItem(R.id.action_manage_accounts)
4249                    .setVisible(QuickConversationsService.isConversations());
4250            popupMenu.setOnMenuItemClickListener(
4251                    item -> {
4252                        final XmppActivity activity = this.activity;
4253                        if (activity == null) {
4254                            Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4255                            return true;
4256                        }
4257                        switch (item.getItemId()) {
4258                            case R.id.action_show_qr_code:
4259                                activity.showQrCode(conversation.getAccount().getShareableUri());
4260                                break;
4261                            case R.id.action_account_details:
4262                                activity.switchToAccount(
4263                                        message.getConversation().getAccount(), fingerprint);
4264                                break;
4265                            case R.id.action_manage_accounts:
4266                                AccountUtils.launchManageAccounts(activity);
4267                                break;
4268                        }
4269                        return true;
4270                    });
4271        }
4272        popupMenu.show();
4273    }
4274
4275    @Override
4276    public void onContactPictureClicked(Message message) {
4277        setThread(message.getThread());
4278        if (message.isPrivateMessage()) {
4279            privateMessageWith(message.getCounterpart());
4280            return;
4281        }
4282        forkNullThread(message);
4283        conversation.setUserSelectedThread(true);
4284
4285        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4286        if (received) {
4287            if (message.getConversation() instanceof Conversation
4288                    && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4289                Jid tcp = message.getTrueCounterpart();
4290                Jid user = message.getCounterpart();
4291                if (user != null && !user.isBareJid()) {
4292                    final MucOptions mucOptions =
4293                            ((Conversation) message.getConversation()).getMucOptions();
4294                    if (mucOptions.participating()
4295                            || ((Conversation) message.getConversation()).getNextCounterpart()
4296                                    != null) {
4297                        MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4298                        MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4299                        if (mucUser == null && tcpMucUser == null) {
4300                            Toast.makeText(
4301                                            getActivity(),
4302                                            activity.getString(
4303                                                    R.string.user_has_left_conference,
4304                                                    user.getResource()),
4305                                            Toast.LENGTH_SHORT)
4306                                    .show();
4307                        }
4308                        highlightInConference(mucUser == null ? (tcpMucUser == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4309                    } else {
4310                        Toast.makeText(
4311                                        getActivity(),
4312                                        R.string.you_are_not_participating,
4313                                        Toast.LENGTH_SHORT)
4314                                .show();
4315                    }
4316                }
4317            }
4318        }
4319    }
4320
4321    private Activity requireActivity() {
4322        final Activity activity = getActivity();
4323        if (activity == null) {
4324            throw new IllegalStateException("Activity not attached");
4325        }
4326        return activity;
4327    }
4328}