ConversationFragment.java

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