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