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