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