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