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