ConversationFragment.java

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