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