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