ConversationFragment.java

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