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