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 userInputRequried(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 userInputRequried(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 userInputRequried(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 || conversation.getMode() == Conversation.MODE_MULTI || FileBackend.allFilesUnderSize(getActivity(), attachments, getMaxHttpUploadSize(conversation))) {
 881            callback.onPresenceSelected();
 882        } else {
 883            activity.selectPresence(conversation, callback);
 884        }
 885    }
 886
 887    public void toggleInputMethod() {
 888        boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
 889        binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
 890        binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
 891        updateSendButton();
 892    }
 893
 894    private void handleNegativeActivityResult(int requestCode) {
 895        switch (requestCode) {
 896            case ATTACHMENT_CHOICE_TAKE_PHOTO:
 897                if (pendingTakePhotoUri.clear()) {
 898                    Log.d(Config.LOGTAG, "cleared pending photo uri after negative activity result");
 899                }
 900                break;
 901        }
 902    }
 903
 904    @Override
 905    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
 906        super.onActivityResult(requestCode, resultCode, data);
 907        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
 908        if (activity != null && activity.xmppConnectionService != null) {
 909            handleActivityResult(activityResult);
 910        } else {
 911            this.postponedActivityResult.push(activityResult);
 912        }
 913    }
 914
 915    public void unblockConversation(final Blockable conversation) {
 916        activity.xmppConnectionService.sendUnblockRequest(conversation);
 917    }
 918
 919    @Override
 920    public void onAttach(Activity activity) {
 921        super.onAttach(activity);
 922        Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
 923        if (activity instanceof ConversationsActivity) {
 924            this.activity = (ConversationsActivity) activity;
 925        } else {
 926            throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationsActivity");
 927        }
 928    }
 929
 930    @Override
 931    public void onDetach() {
 932        super.onDetach();
 933        this.activity = null; //TODO maybe not a good idea since some callbacks really need it
 934    }
 935
 936    @Override
 937    public void onCreate(Bundle savedInstanceState) {
 938        super.onCreate(savedInstanceState);
 939        setHasOptionsMenu(true);
 940    }
 941
 942    @Override
 943    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
 944        menuInflater.inflate(R.menu.fragment_conversation, menu);
 945        final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 946        final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 947        final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 948        final MenuItem menuMute = menu.findItem(R.id.action_mute);
 949        final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 950
 951
 952        if (conversation != null) {
 953            if (conversation.getMode() == Conversation.MODE_MULTI) {
 954                menuContactDetails.setVisible(false);
 955                menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
 956                menuMucDetails.setTitle(conversation.getMucOptions().isPrivateAndNonAnonymous() ? R.string.action_muc_details : R.string.channel_details);
 957            } else {
 958                menuContactDetails.setVisible(!this.conversation.withSelf());
 959                menuMucDetails.setVisible(false);
 960                final XmppConnectionService service = activity.xmppConnectionService;
 961                menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null);
 962            }
 963            if (conversation.isMuted()) {
 964                menuMute.setVisible(false);
 965            } else {
 966                menuUnmute.setVisible(false);
 967            }
 968            ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
 969            ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
 970        }
 971        super.onCreateOptionsMenu(menu, menuInflater);
 972    }
 973
 974    @Override
 975    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 976        this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
 977        binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this?
 978
 979        binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput));
 980
 981        binding.textinput.setOnEditorActionListener(mEditorActionListener);
 982        binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
 983
 984        binding.textSendButton.setOnClickListener(this.mSendButtonListener);
 985
 986        binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
 987        binding.messagesView.setOnScrollListener(mOnScrollListener);
 988        binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
 989        mediaPreviewAdapter = new MediaPreviewAdapter(this);
 990        binding.mediaPreview.setAdapter(mediaPreviewAdapter);
 991        messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
 992        messageListAdapter.setOnContactPictureClicked(this);
 993        messageListAdapter.setOnContactPictureLongClicked(this);
 994        messageListAdapter.setOnQuoteListener(this::quoteText);
 995        binding.messagesView.setAdapter(messageListAdapter);
 996
 997        registerForContextMenu(binding.messagesView);
 998
 999        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1000            this.binding.textinput.setCustomInsertionActionModeCallback(new EditMessageActionModeCallback(this.binding.textinput));
1001        }
1002
1003        return binding.getRoot();
1004    }
1005
1006    private void quoteText(String text) {
1007        if (binding.textinput.isEnabled()) {
1008            binding.textinput.insertAsQuote(text);
1009            binding.textinput.requestFocus();
1010            InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1011            if (inputMethodManager != null) {
1012                inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1013            }
1014        }
1015    }
1016
1017    private void quoteMessage(Message message) {
1018        quoteText(MessageUtils.prepareQuote(message));
1019    }
1020
1021    @Override
1022    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1023        synchronized (this.messageList) {
1024            super.onCreateContextMenu(menu, v, menuInfo);
1025            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1026            this.selectedMessage = this.messageList.get(acmi.position);
1027            populateContextMenu(menu);
1028        }
1029    }
1030
1031    private void populateContextMenu(ContextMenu menu) {
1032        final Message m = this.selectedMessage;
1033        final Transferable t = m.getTransferable();
1034        Message relevantForCorrection = m;
1035        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1036            relevantForCorrection = relevantForCorrection.next();
1037        }
1038        if (m.getType() != Message.TYPE_STATUS) {
1039
1040            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1041                return;
1042            }
1043
1044            final boolean deleted = m.isDeleted();
1045            final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1046                    || m.getEncryption() == Message.ENCRYPTION_PGP;
1047            final boolean receiving = m.getStatus() == Message.STATUS_RECEIVED && (t instanceof JingleConnection || t instanceof HttpDownloadConnection);
1048            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1049            menu.setHeaderTitle(R.string.message_options);
1050            MenuItem openWith = menu.findItem(R.id.open_with);
1051            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1052            MenuItem copyLink = menu.findItem(R.id.copy_link);
1053            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1054            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1055            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1056            MenuItem shareWith = menu.findItem(R.id.share_with);
1057            MenuItem sendAgain = menu.findItem(R.id.send_again);
1058            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1059            MenuItem downloadFile = menu.findItem(R.id.download_file);
1060            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1061            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1062            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1063            final boolean showError = m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1064            if (!m.isFileOrImage() && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1065                copyMessage.setVisible(true);
1066                quoteMessage.setVisible(!showError && MessageUtils.prepareQuote(m).length() > 0);
1067                String body = m.getMergedBody().toString();
1068                if (ShareUtil.containsXmppUri(body)) {
1069                    copyLink.setTitle(R.string.copy_jabber_id);
1070                    copyLink.setVisible(true);
1071                } else if (Patterns.AUTOLINK_WEB_URL.matcher(body).find()) {
1072                    copyLink.setVisible(true);
1073                }
1074            }
1075            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1076                retryDecryption.setVisible(true);
1077            }
1078            if (!showError
1079                    && relevantForCorrection.getType() == Message.TYPE_TEXT
1080                    && !m.isGeoUri()
1081                    && relevantForCorrection.isLastCorrectableMessage()
1082                    && m.getConversation() instanceof Conversation) {
1083                correctMessage.setVisible(true);
1084            }
1085            if ((m.isFileOrImage() && !deleted && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1086                shareWith.setVisible(true);
1087            }
1088            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1089                sendAgain.setVisible(true);
1090            }
1091            if (m.hasFileOnRemoteHost()
1092                    || m.isGeoUri()
1093                    || m.treatAsDownloadable()
1094                    || t instanceof HttpDownloadConnection) {
1095                copyUrl.setVisible(true);
1096            }
1097            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1098                downloadFile.setVisible(true);
1099                downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1100            }
1101            final boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1102                    || m.getStatus() == Message.STATUS_UNSEND
1103                    || m.getStatus() == Message.STATUS_OFFERED;
1104            final boolean cancelable = (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1105            if (cancelable) {
1106                cancelTransmission.setVisible(true);
1107            }
1108            if (m.isFileOrImage() && !deleted && !cancelable) {
1109                String path = m.getRelativeFilePath();
1110                if (path == null || !path.startsWith("/") || FileBackend.isInDirectoryThatShouldNotBeScanned(getActivity(), path)) {
1111                    deleteFile.setVisible(true);
1112                    deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1113                }
1114            }
1115            if (showError) {
1116                showErrorMessage.setVisible(true);
1117            }
1118            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1119            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(),m)) || (mime != null && mime.startsWith("audio/"))) {
1120                openWith.setVisible(true);
1121            }
1122        }
1123    }
1124
1125    @Override
1126    public boolean onContextItemSelected(MenuItem item) {
1127        switch (item.getItemId()) {
1128            case R.id.share_with:
1129                ShareUtil.share(activity, selectedMessage);
1130                return true;
1131            case R.id.correct_message:
1132                correctMessage(selectedMessage);
1133                return true;
1134            case R.id.copy_message:
1135                ShareUtil.copyToClipboard(activity, selectedMessage);
1136                return true;
1137            case R.id.copy_link:
1138                ShareUtil.copyLinkToClipboard(activity, selectedMessage);
1139                return true;
1140            case R.id.quote_message:
1141                quoteMessage(selectedMessage);
1142                return true;
1143            case R.id.send_again:
1144                resendMessage(selectedMessage);
1145                return true;
1146            case R.id.copy_url:
1147                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1148                return true;
1149            case R.id.download_file:
1150                startDownloadable(selectedMessage);
1151                return true;
1152            case R.id.cancel_transmission:
1153                cancelTransmission(selectedMessage);
1154                return true;
1155            case R.id.retry_decryption:
1156                retryDecryption(selectedMessage);
1157                return true;
1158            case R.id.delete_file:
1159                deleteFile(selectedMessage);
1160                return true;
1161            case R.id.show_error_message:
1162                showErrorMessage(selectedMessage);
1163                return true;
1164            case R.id.open_with:
1165                openWith(selectedMessage);
1166                return true;
1167            default:
1168                return super.onContextItemSelected(item);
1169        }
1170    }
1171
1172    @Override
1173    public boolean onOptionsItemSelected(final MenuItem item) {
1174        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1175            return false;
1176        } else if (conversation == null) {
1177            return super.onOptionsItemSelected(item);
1178        }
1179        switch (item.getItemId()) {
1180            case R.id.encryption_choice_axolotl:
1181            case R.id.encryption_choice_pgp:
1182            case R.id.encryption_choice_none:
1183                handleEncryptionSelection(item);
1184                break;
1185            case R.id.attach_choose_picture:
1186            case R.id.attach_take_picture:
1187            case R.id.attach_record_video:
1188            case R.id.attach_choose_file:
1189            case R.id.attach_record_voice:
1190            case R.id.attach_location:
1191                handleAttachmentSelection(item);
1192                break;
1193            case R.id.action_archive:
1194                activity.xmppConnectionService.archiveConversation(conversation);
1195                break;
1196            case R.id.action_contact_details:
1197                activity.switchToContactDetails(conversation.getContact());
1198                break;
1199            case R.id.action_muc_details:
1200                Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1201                intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1202                intent.putExtra("uuid", conversation.getUuid());
1203                startActivity(intent);
1204                break;
1205            case R.id.action_invite:
1206                startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1207                break;
1208            case R.id.action_clear_history:
1209                clearHistoryDialog(conversation);
1210                break;
1211            case R.id.action_mute:
1212                muteConversationDialog(conversation);
1213                break;
1214            case R.id.action_unmute:
1215                unmuteConversation(conversation);
1216                break;
1217            case R.id.action_block:
1218            case R.id.action_unblock:
1219                final Activity activity = getActivity();
1220                if (activity instanceof XmppActivity) {
1221                    BlockContactDialog.show((XmppActivity) activity, conversation);
1222                }
1223                break;
1224            default:
1225                break;
1226        }
1227        return super.onOptionsItemSelected(item);
1228    }
1229
1230    private void handleAttachmentSelection(MenuItem item) {
1231        switch (item.getItemId()) {
1232            case R.id.attach_choose_picture:
1233                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1234                break;
1235            case R.id.attach_take_picture:
1236                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1237                break;
1238            case R.id.attach_record_video:
1239                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1240                break;
1241            case R.id.attach_choose_file:
1242                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1243                break;
1244            case R.id.attach_record_voice:
1245                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1246                break;
1247            case R.id.attach_location:
1248                attachFile(ATTACHMENT_CHOICE_LOCATION);
1249                break;
1250        }
1251    }
1252
1253    private void handleEncryptionSelection(MenuItem item) {
1254        if (conversation == null) {
1255            return;
1256        }
1257        final boolean updated;
1258        switch (item.getItemId()) {
1259            case R.id.encryption_choice_none:
1260                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1261                item.setChecked(true);
1262                break;
1263            case R.id.encryption_choice_pgp:
1264                if (activity.hasPgp()) {
1265                    if (conversation.getAccount().getPgpSignature() != null) {
1266                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1267                        item.setChecked(true);
1268                    } else {
1269                        updated = false;
1270                        activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1271                    }
1272                } else {
1273                    activity.showInstallPgpDialog();
1274                    updated = false;
1275                }
1276                break;
1277            case R.id.encryption_choice_axolotl:
1278                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1279                        + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1280                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1281                item.setChecked(true);
1282                break;
1283            default:
1284                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1285                break;
1286        }
1287        if (updated) {
1288            activity.xmppConnectionService.updateConversation(conversation);
1289        }
1290        updateChatMsgHint();
1291        getActivity().invalidateOptionsMenu();
1292        activity.refreshUi();
1293    }
1294
1295    public void attachFile(final int attachmentChoice) {
1296        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1297            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) {
1298                return;
1299            }
1300        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1301            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
1302                return;
1303            }
1304        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1305            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1306                return;
1307            }
1308        }
1309        try {
1310            activity.getPreferences().edit()
1311                    .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1312                    .apply();
1313        } catch (IllegalArgumentException e) {
1314            //just do not save
1315        }
1316        final int encryption = conversation.getNextEncryption();
1317        final int mode = conversation.getMode();
1318        if (encryption == Message.ENCRYPTION_PGP) {
1319            if (activity.hasPgp()) {
1320                if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1321                    activity.xmppConnectionService.getPgpEngine().hasKey(
1322                            conversation.getContact(),
1323                            new UiCallback<Contact>() {
1324
1325                                @Override
1326                                public void userInputRequried(PendingIntent pi, Contact contact) {
1327                                    startPendingIntent(pi, attachmentChoice);
1328                                }
1329
1330                                @Override
1331                                public void success(Contact contact) {
1332                                    selectPresenceToAttachFile(attachmentChoice);
1333                                }
1334
1335                                @Override
1336                                public void error(int error, Contact contact) {
1337                                    activity.replaceToast(getString(error));
1338                                }
1339                            });
1340                } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1341                    if (!conversation.getMucOptions().everybodyHasKeys()) {
1342                        Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1343                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1344                        warning.show();
1345                    }
1346                    selectPresenceToAttachFile(attachmentChoice);
1347                } else {
1348                    showNoPGPKeyDialog(false, (dialog, which) -> {
1349                        conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1350                        activity.xmppConnectionService.updateConversation(conversation);
1351                        selectPresenceToAttachFile(attachmentChoice);
1352                    });
1353                }
1354            } else {
1355                activity.showInstallPgpDialog();
1356            }
1357        } else {
1358            selectPresenceToAttachFile(attachmentChoice);
1359        }
1360    }
1361
1362    @Override
1363    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
1364        if (grantResults.length > 0) {
1365            if (allGranted(grantResults)) {
1366                switch (requestCode) {
1367                    case REQUEST_START_DOWNLOAD:
1368                        if (this.mPendingDownloadableMessage != null) {
1369                            startDownloadable(this.mPendingDownloadableMessage);
1370                        }
1371                        break;
1372                    case REQUEST_ADD_EDITOR_CONTENT:
1373                        if (this.mPendingEditorContent != null) {
1374                            attachEditorContentToConversation(this.mPendingEditorContent);
1375                        }
1376                        break;
1377                    case REQUEST_COMMIT_ATTACHMENTS:
1378                        commitAttachments();
1379                        break;
1380                    default:
1381                        attachFile(requestCode);
1382                        break;
1383                }
1384            } else {
1385                @StringRes int res;
1386                String firstDenied = getFirstDenied(grantResults, permissions);
1387                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1388                    res = R.string.no_microphone_permission;
1389                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1390                    res = R.string.no_camera_permission;
1391                } else {
1392                    res = R.string.no_storage_permission;
1393                }
1394                Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1395            }
1396        }
1397        if (writeGranted(grantResults, permissions)) {
1398            if (activity != null && activity.xmppConnectionService != null) {
1399                activity.xmppConnectionService.restartFileObserver();
1400            }
1401            refresh();
1402        }
1403    }
1404
1405    public void startDownloadable(Message message) {
1406        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1407            this.mPendingDownloadableMessage = message;
1408            return;
1409        }
1410        Transferable transferable = message.getTransferable();
1411        if (transferable != null) {
1412            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1413                createNewConnection(message);
1414                return;
1415            }
1416            if (!transferable.start()) {
1417                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1418                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1419            }
1420        } else if (message.treatAsDownloadable() || message.hasFileOnRemoteHost()) {
1421            createNewConnection(message);
1422        }
1423    }
1424
1425    private void createNewConnection(final Message message) {
1426        if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) {
1427            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1428            return;
1429        }
1430        activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1431    }
1432
1433    @SuppressLint("InflateParams")
1434    protected void clearHistoryDialog(final Conversation conversation) {
1435        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1436        builder.setTitle(getString(R.string.clear_conversation_history));
1437        final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1438        final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1439        builder.setView(dialogView);
1440        builder.setNegativeButton(getString(R.string.cancel), null);
1441        builder.setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
1442            this.activity.xmppConnectionService.clearConversationHistory(conversation);
1443            if (endConversationCheckBox.isChecked()) {
1444                this.activity.xmppConnectionService.archiveConversation(conversation);
1445                this.activity.onConversationArchived(conversation);
1446            } else {
1447                activity.onConversationsListItemUpdated();
1448                refresh();
1449            }
1450        });
1451        builder.create().show();
1452    }
1453
1454    protected void muteConversationDialog(final Conversation conversation) {
1455        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1456        builder.setTitle(R.string.disable_notifications);
1457        final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1458        final CharSequence[] labels = new CharSequence[durations.length];
1459        for (int i = 0; i < durations.length; ++i) {
1460            if (durations[i] == -1) {
1461                labels[i] = getString(R.string.until_further_notice);
1462            } else {
1463                labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1464            }
1465        }
1466        builder.setItems(labels, (dialog, which) -> {
1467            final long till;
1468            if (durations[which] == -1) {
1469                till = Long.MAX_VALUE;
1470            } else {
1471                till = System.currentTimeMillis() + (durations[which] * 1000);
1472            }
1473            conversation.setMutedTill(till);
1474            activity.xmppConnectionService.updateConversation(conversation);
1475            activity.onConversationsListItemUpdated();
1476            refresh();
1477            getActivity().invalidateOptionsMenu();
1478        });
1479        builder.create().show();
1480    }
1481
1482    private boolean hasPermissions(int requestCode, String... permissions) {
1483        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1484            final List<String> missingPermissions = new ArrayList<>();
1485            for (String permission : permissions) {
1486                if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1487                    continue;
1488                }
1489                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
1490                    missingPermissions.add(permission);
1491                }
1492            }
1493            if (missingPermissions.size() == 0) {
1494                return true;
1495            } else {
1496                requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1497                return false;
1498            }
1499        } else {
1500            return true;
1501        }
1502    }
1503
1504    public void unmuteConversation(final Conversation conversation) {
1505        conversation.setMutedTill(0);
1506        this.activity.xmppConnectionService.updateConversation(conversation);
1507        this.activity.onConversationsListItemUpdated();
1508        refresh();
1509        getActivity().invalidateOptionsMenu();
1510    }
1511
1512    protected void selectPresenceToAttachFile(final int attachmentChoice) {
1513        final Account account = conversation.getAccount();
1514        final PresenceSelector.OnPresenceSelected callback = () -> {
1515            Intent intent = new Intent();
1516            boolean chooser = false;
1517            switch (attachmentChoice) {
1518                case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1519                    intent.setAction(Intent.ACTION_GET_CONTENT);
1520                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1521                        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1522                    }
1523                    intent.setType("image/*");
1524                    chooser = true;
1525                    break;
1526                case ATTACHMENT_CHOICE_RECORD_VIDEO:
1527                    intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1528                    break;
1529                case ATTACHMENT_CHOICE_TAKE_PHOTO:
1530                    final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1531                    pendingTakePhotoUri.push(uri);
1532                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1533                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1534                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1535                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1536                    break;
1537                case ATTACHMENT_CHOICE_CHOOSE_FILE:
1538                    chooser = true;
1539                    intent.setType("*/*");
1540                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1541                        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1542                    }
1543                    intent.addCategory(Intent.CATEGORY_OPENABLE);
1544                    intent.setAction(Intent.ACTION_GET_CONTENT);
1545                    break;
1546                case ATTACHMENT_CHOICE_RECORD_VOICE:
1547                    intent = new Intent(getActivity(), RecordingActivity.class);
1548                    break;
1549                case ATTACHMENT_CHOICE_LOCATION:
1550                    intent = GeoHelper.getFetchIntent(activity);
1551                    break;
1552            }
1553            if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1554                if (chooser) {
1555                    startActivityForResult(
1556                            Intent.createChooser(intent, getString(R.string.perform_action_with)),
1557                            attachmentChoice);
1558                } else {
1559                    startActivityForResult(intent, attachmentChoice);
1560                }
1561            }
1562        };
1563        if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1564            callback.onPresenceSelected();
1565        } else {
1566            activity.selectPresence(conversation, callback);
1567        }
1568    }
1569
1570    @Override
1571    public void onResume() {
1572        super.onResume();
1573        binding.messagesView.post(this::fireReadEvent);
1574    }
1575
1576    private void fireReadEvent() {
1577        if (activity != null && this.conversation != null) {
1578            String uuid = getLastVisibleMessageUuid();
1579            if (uuid != null) {
1580                activity.onConversationRead(this.conversation, uuid);
1581            }
1582        }
1583    }
1584
1585    private String getLastVisibleMessageUuid() {
1586        if (binding == null) {
1587            return null;
1588        }
1589        synchronized (this.messageList) {
1590            int pos = binding.messagesView.getLastVisiblePosition();
1591            if (pos >= 0) {
1592                Message message = null;
1593                for (int i = pos; i >= 0; --i) {
1594                    try {
1595                        message = (Message) binding.messagesView.getItemAtPosition(i);
1596                    } catch (IndexOutOfBoundsException e) {
1597                        //should not happen if we synchronize properly. however if that fails we just gonna try item -1
1598                        continue;
1599                    }
1600                    if (message.getType() != Message.TYPE_STATUS) {
1601                        break;
1602                    }
1603                }
1604                if (message != null) {
1605                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
1606                        message = message.next();
1607                    }
1608                    return message.getUuid();
1609                }
1610            }
1611        }
1612        return null;
1613    }
1614
1615    private void openWith(final Message message) {
1616        if (message.isGeoUri()) {
1617            GeoHelper.view(getActivity(),message);
1618        } else {
1619            final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1620            ViewUtil.view(activity, file);
1621        }
1622    }
1623
1624    private void showErrorMessage(final Message message) {
1625        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1626        builder.setTitle(R.string.error_message);
1627        final String errorMessage = message.getErrorMessage();
1628        final String[] errorMessageParts = errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
1629        final String displayError;
1630        if (errorMessageParts.length == 2) {
1631            displayError = errorMessageParts[1];
1632        } else {
1633            displayError = errorMessage;
1634        }
1635        builder.setMessage(displayError);
1636        builder.setNegativeButton(R.string.copy_to_clipboard, (dialog, which) -> {
1637            activity.copyTextToClipboard(displayError,R.string.error_message);
1638            Toast.makeText(activity,R.string.error_message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1639        });
1640        builder.setPositiveButton(R.string.confirm, null);
1641        builder.create().show();
1642    }
1643
1644
1645    private void deleteFile(final Message message) {
1646        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1647        builder.setNegativeButton(R.string.cancel, null);
1648        builder.setTitle(R.string.delete_file_dialog);
1649        builder.setMessage(R.string.delete_file_dialog_msg);
1650        builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
1651            if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1652                message.setDeleted(true);
1653                activity.xmppConnectionService.updateMessage(message, false);
1654                activity.onConversationsListItemUpdated();
1655                refresh();
1656            }
1657        });
1658        builder.create().show();
1659
1660    }
1661
1662    private void resendMessage(final Message message) {
1663        if (message.isFileOrImage()) {
1664            if (!(message.getConversation() instanceof Conversation)) {
1665                return;
1666            }
1667            final Conversation conversation = (Conversation) message.getConversation();
1668            final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1669            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
1670                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1671                if (!message.hasFileOnRemoteHost()
1672                        && xmppConnection != null
1673                        && conversation.getMode() == Conversational.MODE_SINGLE
1674                        && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1675                    activity.selectPresence(conversation, () -> {
1676                        message.setCounterpart(conversation.getNextCounterpart());
1677                        activity.xmppConnectionService.resendFailedMessages(message);
1678                        new Handler().post(() -> {
1679                            int size = messageList.size();
1680                            this.binding.messagesView.setSelection(size - 1);
1681                        });
1682                    });
1683                    return;
1684                }
1685            } else if (!Compatibility.hasStoragePermission(getActivity())) {
1686                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
1687                return;
1688            } else {
1689                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1690                message.setDeleted(true);
1691                activity.xmppConnectionService.updateMessage(message, false);
1692                activity.onConversationsListItemUpdated();
1693                refresh();
1694                return;
1695            }
1696        }
1697        activity.xmppConnectionService.resendFailedMessages(message);
1698        new Handler().post(() -> {
1699            int size = messageList.size();
1700            this.binding.messagesView.setSelection(size - 1);
1701        });
1702    }
1703
1704    private void cancelTransmission(Message message) {
1705        Transferable transferable = message.getTransferable();
1706        if (transferable != null) {
1707            transferable.cancel();
1708        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1709            activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
1710        }
1711    }
1712
1713    private void retryDecryption(Message message) {
1714        message.setEncryption(Message.ENCRYPTION_PGP);
1715        activity.onConversationsListItemUpdated();
1716        refresh();
1717        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1718    }
1719
1720    public void privateMessageWith(final Jid counterpart) {
1721        if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1722            activity.xmppConnectionService.sendChatState(conversation);
1723        }
1724        this.binding.textinput.setText("");
1725        this.conversation.setNextCounterpart(counterpart);
1726        updateChatMsgHint();
1727        updateSendButton();
1728        updateEditablity();
1729    }
1730
1731    private void correctMessage(Message message) {
1732        while (message.mergeable(message.next())) {
1733            message = message.next();
1734        }
1735        this.conversation.setCorrectingMessage(message);
1736        final Editable editable = binding.textinput.getText();
1737        this.conversation.setDraftMessage(editable.toString());
1738        this.binding.textinput.setText("");
1739        this.binding.textinput.append(message.getBody());
1740
1741    }
1742
1743    private void highlightInConference(String nick) {
1744        final Editable editable = this.binding.textinput.getText();
1745        String oldString = editable.toString().trim();
1746        final int pos = this.binding.textinput.getSelectionStart();
1747        if (oldString.isEmpty() || pos == 0) {
1748            editable.insert(0, nick + ": ");
1749        } else {
1750            final char before = editable.charAt(pos - 1);
1751            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1752            if (before == '\n') {
1753                editable.insert(pos, nick + ": ");
1754            } else {
1755                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1756                    if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1757                        editable.insert(pos - 2, ", " + nick);
1758                        return;
1759                    }
1760                }
1761                editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1762                if (Character.isWhitespace(after)) {
1763                    this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1764                }
1765            }
1766        }
1767    }
1768
1769    @Override
1770    public void startActivityForResult(Intent intent, int requestCode) {
1771        final Activity activity = getActivity();
1772        if (activity instanceof ConversationsActivity) {
1773            ((ConversationsActivity) activity).clearPendingViewIntent();
1774        }
1775        super.startActivityForResult(intent, requestCode);
1776    }
1777
1778    @Override
1779    public void onSaveInstanceState(Bundle outState) {
1780        super.onSaveInstanceState(outState);
1781        if (conversation != null) {
1782            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1783            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1784            final Uri uri = pendingTakePhotoUri.peek();
1785            if (uri != null) {
1786                outState.putString(STATE_PHOTO_URI, uri.toString());
1787            }
1788            final ScrollState scrollState = getScrollPosition();
1789            if (scrollState != null) {
1790                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1791            }
1792            final ArrayList<Attachment> attachments = mediaPreviewAdapter == null ? new ArrayList<>() : mediaPreviewAdapter.getAttachments();
1793            if (attachments.size() > 0) {
1794                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
1795            }
1796        }
1797    }
1798
1799    @Override
1800    public void onActivityCreated(Bundle savedInstanceState) {
1801        super.onActivityCreated(savedInstanceState);
1802        if (savedInstanceState == null) {
1803            return;
1804        }
1805        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1806        ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
1807        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1808        if (uuid != null) {
1809            QuickLoader.set(uuid);
1810            this.pendingConversationsUuid.push(uuid);
1811            if (attachments != null && attachments.size() > 0) {
1812                this.pendingMediaPreviews.push(attachments);
1813            }
1814            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1815            if (takePhotoUri != null) {
1816                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1817            }
1818            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1819        }
1820    }
1821
1822    @Override
1823    public void onStart() {
1824        super.onStart();
1825        if (this.reInitRequiredOnStart && this.conversation != null) {
1826            final Bundle extras = pendingExtras.pop();
1827            reInit(this.conversation, extras != null);
1828            if (extras != null) {
1829                processExtras(extras);
1830            }
1831        } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1832            final String uuid = pendingConversationsUuid.pop();
1833            Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1834            if (uuid != null) {
1835                findAndReInitByUuidOrArchive(uuid);
1836            }
1837        }
1838    }
1839
1840    @Override
1841    public void onStop() {
1842        super.onStop();
1843        final Activity activity = getActivity();
1844        messageListAdapter.unregisterListenerInAudioPlayer();
1845        if (activity == null || !activity.isChangingConfigurations()) {
1846            hideSoftKeyboard(activity);
1847            messageListAdapter.stopAudioPlayer();
1848        }
1849        if (this.conversation != null) {
1850            final String msg = this.binding.textinput.getText().toString();
1851            storeNextMessage(msg);
1852            updateChatState(this.conversation, msg);
1853            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1854        }
1855        this.reInitRequiredOnStart = true;
1856    }
1857
1858    private void updateChatState(final Conversation conversation, final String msg) {
1859        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1860        Account.State status = conversation.getAccount().getStatus();
1861        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1862            activity.xmppConnectionService.sendChatState(conversation);
1863        }
1864    }
1865
1866    private void saveMessageDraftStopAudioPlayer() {
1867        final Conversation previousConversation = this.conversation;
1868        if (this.activity == null || this.binding == null || previousConversation == null) {
1869            return;
1870        }
1871        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1872        final String msg = this.binding.textinput.getText().toString();
1873        storeNextMessage(msg);
1874        updateChatState(this.conversation, msg);
1875        messageListAdapter.stopAudioPlayer();
1876        mediaPreviewAdapter.clearPreviews();
1877        toggleInputMethod();
1878    }
1879
1880    public void reInit(Conversation conversation, Bundle extras) {
1881        QuickLoader.set(conversation.getUuid());
1882        this.saveMessageDraftStopAudioPlayer();
1883        this.clearPending();
1884        if (this.reInit(conversation, extras != null)) {
1885            if (extras != null) {
1886                processExtras(extras);
1887            }
1888            this.reInitRequiredOnStart = false;
1889        } else {
1890            this.reInitRequiredOnStart = true;
1891            pendingExtras.push(extras);
1892        }
1893        resetUnreadMessagesCount();
1894    }
1895
1896    private void reInit(Conversation conversation) {
1897        reInit(conversation, false);
1898    }
1899
1900    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1901        if (conversation == null) {
1902            return false;
1903        }
1904        this.conversation = conversation;
1905        //once we set the conversation all is good and it will automatically do the right thing in onStart()
1906        if (this.activity == null || this.binding == null) {
1907            return false;
1908        }
1909
1910        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1911            activity.onConversationArchived(this.conversation);
1912            return false;
1913        }
1914
1915        stopScrolling();
1916        Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1917
1918        if (this.conversation.isRead() && hasExtras) {
1919            Log.d(Config.LOGTAG, "trimming conversation");
1920            this.conversation.trim();
1921        }
1922
1923        setupIme();
1924
1925        final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1926
1927        this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1928        this.binding.textinput.setKeyboardListener(null);
1929        this.binding.textinput.setText("");
1930        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
1931        if (participating) {
1932            this.binding.textinput.append(this.conversation.getNextMessage());
1933        }
1934        this.binding.textinput.setKeyboardListener(this);
1935        messageListAdapter.updatePreferences();
1936        refresh(false);
1937        this.conversation.messagesLoaded.set(true);
1938        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1939
1940        if (hasExtras || scrolledToBottomAndNoPending) {
1941            resetUnreadMessagesCount();
1942            synchronized (this.messageList) {
1943                Log.d(Config.LOGTAG, "jump to first unread message");
1944                final Message first = conversation.getFirstUnreadMessage();
1945                final int bottom = Math.max(0, this.messageList.size() - 1);
1946                final int pos;
1947                final boolean jumpToBottom;
1948                if (first == null) {
1949                    pos = bottom;
1950                    jumpToBottom = true;
1951                } else {
1952                    int i = getIndexOf(first.getUuid(), this.messageList);
1953                    pos = i < 0 ? bottom : i;
1954                    jumpToBottom = false;
1955                }
1956                setSelection(pos, jumpToBottom);
1957            }
1958        }
1959
1960
1961        this.binding.messagesView.post(this::fireReadEvent);
1962        //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
1963        activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1964        return true;
1965    }
1966
1967    private void resetUnreadMessagesCount() {
1968        lastMessageUuid = null;
1969        hideUnreadMessagesCount();
1970    }
1971
1972    private void hideUnreadMessagesCount() {
1973        if (this.binding == null) {
1974            return;
1975        }
1976        this.binding.scrollToBottomButton.setEnabled(false);
1977        this.binding.scrollToBottomButton.hide();
1978        this.binding.unreadCountCustomView.setVisibility(View.GONE);
1979    }
1980
1981    private void setSelection(int pos, boolean jumpToBottom) {
1982        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
1983        this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
1984        this.binding.messagesView.post(this::fireReadEvent);
1985    }
1986
1987
1988    private boolean scrolledToBottom() {
1989        return this.binding != null && scrolledToBottom(this.binding.messagesView);
1990    }
1991
1992    private void processExtras(Bundle extras) {
1993        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1994        final String text = extras.getString(Intent.EXTRA_TEXT);
1995        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
1996        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
1997        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1998        final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
1999        final List<Uri> uris = extractUris(extras);
2000        if (uris != null && uris.size() > 0) {
2001            final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2002            mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
2003            toggleInputMethod();
2004            return;
2005        }
2006        if (nick != null) {
2007            if (pm) {
2008                Jid jid = conversation.getJid();
2009                try {
2010                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2011                    privateMessageWith(next);
2012                } catch (final IllegalArgumentException ignored) {
2013                    //do nothing
2014                }
2015            } else {
2016                final MucOptions mucOptions = conversation.getMucOptions();
2017                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2018                    highlightInConference(nick);
2019                }
2020            }
2021        } else {
2022            if (text != null && asQuote) {
2023                quoteText(text);
2024            } else {
2025                appendText(text, doNotAppend);
2026            }
2027        }
2028        final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2029        if (message != null) {
2030            startDownloadable(message);
2031        }
2032    }
2033
2034    private List<Uri> extractUris(Bundle extras) {
2035        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2036        if (uris != null) {
2037            return uris;
2038        }
2039        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2040        if (uri != null) {
2041            return Collections.singletonList(uri);
2042        } else {
2043            return null;
2044        }
2045    }
2046
2047    private List<Uri> cleanUris(List<Uri> uris) {
2048        Iterator<Uri> iterator = uris.iterator();
2049        while (iterator.hasNext()) {
2050            final Uri uri = iterator.next();
2051            if (FileBackend.weOwnFile(getActivity(), uri)) {
2052                iterator.remove();
2053                Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show();
2054            }
2055        }
2056        return uris;
2057    }
2058
2059    private boolean showBlockSubmenu(View view) {
2060        final Jid jid = conversation.getJid();
2061        final boolean showReject = !conversation.isWithStranger() && conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2062        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2063        popupMenu.inflate(R.menu.block);
2064        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2065        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2066        popupMenu.setOnMenuItemClickListener(menuItem -> {
2067            Blockable blockable;
2068            switch (menuItem.getItemId()) {
2069                case R.id.reject:
2070                    activity.xmppConnectionService.stopPresenceUpdatesTo(conversation.getContact());
2071                    updateSnackBar(conversation);
2072                    return true;
2073                case R.id.block_domain:
2074                    blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2075                    break;
2076                default:
2077                    blockable = conversation;
2078            }
2079            BlockContactDialog.show(activity, blockable);
2080            return true;
2081        });
2082        popupMenu.show();
2083        return true;
2084    }
2085
2086    private void updateSnackBar(final Conversation conversation) {
2087        final Account account = conversation.getAccount();
2088        final XmppConnection connection = account.getXmppConnection();
2089        final int mode = conversation.getMode();
2090        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2091        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2092            return;
2093        }
2094        if (account.getStatus() == Account.State.DISABLED) {
2095            showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2096        } else if (conversation.isBlocked()) {
2097            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2098        } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2099            showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2100        } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2101            showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2102        } else if (mode == Conversation.MODE_MULTI
2103                && !conversation.getMucOptions().online()
2104                && account.getStatus() == Account.State.ONLINE) {
2105            switch (conversation.getMucOptions().getError()) {
2106                case NICK_IN_USE:
2107                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2108                    break;
2109                case NO_RESPONSE:
2110                    showSnackbar(R.string.joining_conference, 0, null);
2111                    break;
2112                case SERVER_NOT_FOUND:
2113                    if (conversation.receivedMessagesCount() > 0) {
2114                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2115                    } else {
2116                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2117                    }
2118                    break;
2119                case REMOTE_SERVER_TIMEOUT:
2120                    if (conversation.receivedMessagesCount() > 0) {
2121                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2122                    } else {
2123                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2124                    }
2125                    break;
2126                case PASSWORD_REQUIRED:
2127                    showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2128                    break;
2129                case BANNED:
2130                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2131                    break;
2132                case MEMBERS_ONLY:
2133                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2134                    break;
2135                case RESOURCE_CONSTRAINT:
2136                    showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2137                    break;
2138                case KICKED:
2139                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2140                    break;
2141                case UNKNOWN:
2142                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2143                    break;
2144                case INVALID_NICK:
2145                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2146                case SHUTDOWN:
2147                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2148                    break;
2149                case DESTROYED:
2150                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2151                    break;
2152                case NON_ANONYMOUS:
2153                    showSnackbar(R.string.group_chat_will_make_your_jabber_id_public, R.string.join, acceptJoin);
2154                    break;
2155                default:
2156                    hideSnackbar();
2157                    break;
2158            }
2159        } else if (account.hasPendingPgpIntent(conversation)) {
2160            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2161        } else if (connection != null
2162                && connection.getFeatures().blocking()
2163                && conversation.countMessages() != 0
2164                && !conversation.isBlocked()
2165                && conversation.isWithStranger()) {
2166            showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2167        } else {
2168            hideSnackbar();
2169        }
2170    }
2171
2172    @Override
2173    public void refresh() {
2174        if (this.binding == null) {
2175            Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2176            return;
2177        }
2178        if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2179            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2180                activity.onConversationArchived(this.conversation);
2181                return;
2182            }
2183        }
2184        this.refresh(true);
2185    }
2186
2187    private void refresh(boolean notifyConversationRead) {
2188        synchronized (this.messageList) {
2189            if (this.conversation != null) {
2190                conversation.populateWithMessages(this.messageList);
2191                updateSnackBar(conversation);
2192                updateStatusMessages();
2193                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2194                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2195                    binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2196                }
2197                this.messageListAdapter.notifyDataSetChanged();
2198                updateChatMsgHint();
2199                if (notifyConversationRead && activity != null) {
2200                    binding.messagesView.post(this::fireReadEvent);
2201                }
2202                updateSendButton();
2203                updateEditablity();
2204                activity.invalidateOptionsMenu();
2205            }
2206        }
2207    }
2208
2209    protected void messageSent() {
2210        mSendingPgpMessage.set(false);
2211        this.binding.textinput.setText("");
2212        if (conversation.setCorrectingMessage(null)) {
2213            this.binding.textinput.append(conversation.getDraftMessage());
2214            conversation.setDraftMessage(null);
2215        }
2216        storeNextMessage();
2217        updateChatMsgHint();
2218        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2219        final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2220        if (prefScrollToBottom || scrolledToBottom()) {
2221            new Handler().post(() -> {
2222                int size = messageList.size();
2223                this.binding.messagesView.setSelection(size - 1);
2224            });
2225        }
2226    }
2227
2228    private boolean storeNextMessage() {
2229        return storeNextMessage(this.binding.textinput.getText().toString());
2230    }
2231
2232    private boolean storeNextMessage(String msg) {
2233        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2234        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
2235            this.activity.xmppConnectionService.updateConversation(this.conversation);
2236            return true;
2237        }
2238        return false;
2239    }
2240
2241    public void doneSendingPgpMessage() {
2242        mSendingPgpMessage.set(false);
2243    }
2244
2245    public long getMaxHttpUploadSize(Conversation conversation) {
2246        final XmppConnection connection = conversation.getAccount().getXmppConnection();
2247        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2248    }
2249
2250    private void updateEditablity() {
2251        boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2252        this.binding.textinput.setFocusable(canWrite);
2253        this.binding.textinput.setFocusableInTouchMode(canWrite);
2254        this.binding.textSendButton.setEnabled(canWrite);
2255        this.binding.textinput.setCursorVisible(canWrite);
2256        this.binding.textinput.setEnabled(canWrite);
2257    }
2258
2259    public void updateSendButton() {
2260        boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2261        boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2262        final Conversation c = this.conversation;
2263        final Presence.Status status;
2264        final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2265        final SendButtonAction action;
2266        if (hasAttachments) {
2267            action = SendButtonAction.TEXT;
2268        } else {
2269            action = SendButtonTool.getAction(getActivity(), c, text);
2270        }
2271        if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2272            if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2273                status = Presence.Status.OFFLINE;
2274            } else if (c.getMode() == Conversation.MODE_SINGLE) {
2275                status = c.getContact().getShownStatus();
2276            } else {
2277                status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2278            }
2279        } else {
2280            status = Presence.Status.OFFLINE;
2281        }
2282        this.binding.textSendButton.setTag(action);
2283        this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2284    }
2285
2286    protected void updateDateSeparators() {
2287        synchronized (this.messageList) {
2288            DateSeparator.addAll(this.messageList);
2289        }
2290    }
2291
2292    protected void updateStatusMessages() {
2293        updateDateSeparators();
2294        synchronized (this.messageList) {
2295            if (showLoadMoreMessages(conversation)) {
2296                this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2297            }
2298            if (conversation.getMode() == Conversation.MODE_SINGLE) {
2299                ChatState state = conversation.getIncomingChatState();
2300                if (state == ChatState.COMPOSING) {
2301                    this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2302                } else if (state == ChatState.PAUSED) {
2303                    this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2304                } else {
2305                    for (int i = this.messageList.size() - 1; i >= 0; --i) {
2306                        final Message message = this.messageList.get(i);
2307                        if (message.getType() != Message.TYPE_STATUS) {
2308                            if (message.getStatus() == Message.STATUS_RECEIVED) {
2309                                return;
2310                            } else {
2311                                if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
2312                                    this.messageList.add(i + 1,
2313                                            Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2314                                    return;
2315                                }
2316                            }
2317                        }
2318                    }
2319                }
2320            } else {
2321                final MucOptions mucOptions = conversation.getMucOptions();
2322                final List<MucOptions.User> allUsers = mucOptions.getUsers();
2323                final Set<ReadByMarker> addedMarkers = new HashSet<>();
2324                ChatState state = ChatState.COMPOSING;
2325                List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2326                if (users.size() == 0) {
2327                    state = ChatState.PAUSED;
2328                    users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2329                }
2330                if (mucOptions.isPrivateAndNonAnonymous()) {
2331                    for (int i = this.messageList.size() - 1; i >= 0; --i) {
2332                        final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2333                        final List<MucOptions.User> shownMarkers = new ArrayList<>();
2334                        for (ReadByMarker marker : markersForMessage) {
2335                            if (!ReadByMarker.contains(marker, addedMarkers)) {
2336                                addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2337                                MucOptions.User user = mucOptions.findUser(marker);
2338                                if (user != null && !users.contains(user)) {
2339                                    shownMarkers.add(user);
2340                                }
2341                            }
2342                        }
2343                        final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2344                        final Message statusMessage;
2345                        final int size = shownMarkers.size();
2346                        if (size > 1) {
2347                            final String body;
2348                            if (size <= 4) {
2349                                body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2350                            } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
2351                                body = getString(R.string.everyone_has_read_up_to_this_point);
2352                            } else {
2353                                body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2354                            }
2355                            statusMessage = Message.createStatusMessage(conversation, body);
2356                            statusMessage.setCounterparts(shownMarkers);
2357                        } else if (size == 1) {
2358                            statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2359                            statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2360                            statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2361                        } else {
2362                            statusMessage = null;
2363                        }
2364                        if (statusMessage != null) {
2365                            this.messageList.add(i + 1, statusMessage);
2366                        }
2367                        addedMarkers.add(markerForSender);
2368                        if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2369                            break;
2370                        }
2371                    }
2372                }
2373                if (users.size() > 0) {
2374                    Message statusMessage;
2375                    if (users.size() == 1) {
2376                        MucOptions.User user = users.get(0);
2377                        int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2378                        statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2379                        statusMessage.setTrueCounterpart(user.getRealJid());
2380                        statusMessage.setCounterpart(user.getFullJid());
2381                    } else {
2382                        int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2383                        statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2384                        statusMessage.setCounterparts(users);
2385                    }
2386                    this.messageList.add(statusMessage);
2387                }
2388
2389            }
2390        }
2391    }
2392
2393    private void stopScrolling() {
2394        long now = SystemClock.uptimeMillis();
2395        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2396        binding.messagesView.dispatchTouchEvent(cancel);
2397    }
2398
2399    private boolean showLoadMoreMessages(final Conversation c) {
2400        if (activity == null || activity.xmppConnectionService == null) {
2401            return false;
2402        }
2403        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2404        final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2405        return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2406    }
2407
2408    private boolean hasMamSupport(final Conversation c) {
2409        if (c.getMode() == Conversation.MODE_SINGLE) {
2410            final XmppConnection connection = c.getAccount().getXmppConnection();
2411            return connection != null && connection.getFeatures().mam();
2412        } else {
2413            return c.getMucOptions().mamSupport();
2414        }
2415    }
2416
2417    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2418        showSnackbar(message, action, clickListener, null);
2419    }
2420
2421    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2422        this.binding.snackbar.setVisibility(View.VISIBLE);
2423        this.binding.snackbar.setOnClickListener(null);
2424        this.binding.snackbarMessage.setText(message);
2425        this.binding.snackbarMessage.setOnClickListener(null);
2426        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2427        if (action != 0) {
2428            this.binding.snackbarAction.setText(action);
2429        }
2430        this.binding.snackbarAction.setOnClickListener(clickListener);
2431        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2432    }
2433
2434    protected void hideSnackbar() {
2435        this.binding.snackbar.setVisibility(View.GONE);
2436    }
2437
2438    protected void sendMessage(Message message) {
2439        activity.xmppConnectionService.sendMessage(message);
2440        messageSent();
2441    }
2442
2443    protected void sendPgpMessage(final Message message) {
2444        final XmppConnectionService xmppService = activity.xmppConnectionService;
2445        final Contact contact = message.getConversation().getContact();
2446        if (!activity.hasPgp()) {
2447            activity.showInstallPgpDialog();
2448            return;
2449        }
2450        if (conversation.getAccount().getPgpSignature() == null) {
2451            activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2452            return;
2453        }
2454        if (!mSendingPgpMessage.compareAndSet(false, true)) {
2455            Log.d(Config.LOGTAG, "sending pgp message already in progress");
2456        }
2457        if (conversation.getMode() == Conversation.MODE_SINGLE) {
2458            if (contact.getPgpKeyId() != 0) {
2459                xmppService.getPgpEngine().hasKey(contact,
2460                        new UiCallback<Contact>() {
2461
2462                            @Override
2463                            public void userInputRequried(PendingIntent pi, Contact contact) {
2464                                startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2465                            }
2466
2467                            @Override
2468                            public void success(Contact contact) {
2469                                encryptTextMessage(message);
2470                            }
2471
2472                            @Override
2473                            public void error(int error, Contact contact) {
2474                                activity.runOnUiThread(() -> Toast.makeText(activity,
2475                                        R.string.unable_to_connect_to_keychain,
2476                                        Toast.LENGTH_SHORT
2477                                ).show());
2478                                mSendingPgpMessage.set(false);
2479                            }
2480                        });
2481
2482            } else {
2483                showNoPGPKeyDialog(false, (dialog, which) -> {
2484                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2485                    xmppService.updateConversation(conversation);
2486                    message.setEncryption(Message.ENCRYPTION_NONE);
2487                    xmppService.sendMessage(message);
2488                    messageSent();
2489                });
2490            }
2491        } else {
2492            if (conversation.getMucOptions().pgpKeysInUse()) {
2493                if (!conversation.getMucOptions().everybodyHasKeys()) {
2494                    Toast warning = Toast
2495                            .makeText(getActivity(),
2496                                    R.string.missing_public_keys,
2497                                    Toast.LENGTH_LONG);
2498                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2499                    warning.show();
2500                }
2501                encryptTextMessage(message);
2502            } else {
2503                showNoPGPKeyDialog(true, (dialog, which) -> {
2504                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2505                    message.setEncryption(Message.ENCRYPTION_NONE);
2506                    xmppService.updateConversation(conversation);
2507                    xmppService.sendMessage(message);
2508                    messageSent();
2509                });
2510            }
2511        }
2512    }
2513
2514    public void encryptTextMessage(Message message) {
2515        activity.xmppConnectionService.getPgpEngine().encrypt(message,
2516                new UiCallback<Message>() {
2517
2518                    @Override
2519                    public void userInputRequried(PendingIntent pi, Message message) {
2520                        startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2521                    }
2522
2523                    @Override
2524                    public void success(Message message) {
2525                        //TODO the following two call can be made before the callback
2526                        getActivity().runOnUiThread(() -> messageSent());
2527                    }
2528
2529                    @Override
2530                    public void error(final int error, Message message) {
2531                        getActivity().runOnUiThread(() -> {
2532                            doneSendingPgpMessage();
2533                            Toast.makeText(getActivity(), error == 0 ? R.string.unable_to_connect_to_keychain : error, Toast.LENGTH_SHORT).show();
2534                        });
2535
2536                    }
2537                });
2538    }
2539
2540    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2541        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2542        builder.setIconAttribute(android.R.attr.alertDialogIcon);
2543        if (plural) {
2544            builder.setTitle(getString(R.string.no_pgp_keys));
2545            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2546        } else {
2547            builder.setTitle(getString(R.string.no_pgp_key));
2548            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2549        }
2550        builder.setNegativeButton(getString(R.string.cancel), null);
2551        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2552        builder.create().show();
2553    }
2554
2555    public void appendText(String text, final boolean doNotAppend) {
2556        if (text == null) {
2557            return;
2558        }
2559        final Editable editable = this.binding.textinput.getText();
2560        String previous = editable == null ? "" : editable.toString();
2561        if (doNotAppend && !TextUtils.isEmpty(previous)) {
2562            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG).show();
2563            return;
2564        }
2565        if (UIHelper.isLastLineQuote(previous)) {
2566            text = '\n' + text;
2567        } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2568            text = " " + text;
2569        }
2570        this.binding.textinput.append(text);
2571    }
2572
2573    @Override
2574    public boolean onEnterPressed() {
2575        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2576        final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2577        if (enterIsSend) {
2578            sendMessage();
2579            return true;
2580        } else {
2581            return false;
2582        }
2583    }
2584
2585    @Override
2586    public void onTypingStarted() {
2587        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2588        if (service == null) {
2589            return;
2590        }
2591        Account.State status = conversation.getAccount().getStatus();
2592        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2593            service.sendChatState(conversation);
2594        }
2595        runOnUiThread(this::updateSendButton);
2596    }
2597
2598    @Override
2599    public void onTypingStopped() {
2600        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2601        if (service == null) {
2602            return;
2603        }
2604        Account.State status = conversation.getAccount().getStatus();
2605        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2606            service.sendChatState(conversation);
2607        }
2608    }
2609
2610    @Override
2611    public void onTextDeleted() {
2612        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2613        if (service == null) {
2614            return;
2615        }
2616        Account.State status = conversation.getAccount().getStatus();
2617        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2618            service.sendChatState(conversation);
2619        }
2620        if (storeNextMessage()) {
2621            runOnUiThread(() -> activity.onConversationsListItemUpdated());
2622        }
2623        runOnUiThread(this::updateSendButton);
2624    }
2625
2626    @Override
2627    public void onTextChanged() {
2628        if (conversation != null && conversation.getCorrectingMessage() != null) {
2629            runOnUiThread(this::updateSendButton);
2630        }
2631    }
2632
2633    @Override
2634    public boolean onTabPressed(boolean repeated) {
2635        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2636            return false;
2637        }
2638        if (repeated) {
2639            completionIndex++;
2640        } else {
2641            lastCompletionLength = 0;
2642            completionIndex = 0;
2643            final String content = this.binding.textinput.getText().toString();
2644            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2645            int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2646            firstWord = start == 0;
2647            incomplete = content.substring(start, lastCompletionCursor);
2648        }
2649        List<String> completions = new ArrayList<>();
2650        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2651            String name = user.getName();
2652            if (name != null && name.startsWith(incomplete)) {
2653                completions.add(name + (firstWord ? ": " : " "));
2654            }
2655        }
2656        Collections.sort(completions);
2657        if (completions.size() > completionIndex) {
2658            String completion = completions.get(completionIndex).substring(incomplete.length());
2659            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2660            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2661            lastCompletionLength = completion.length();
2662        } else {
2663            completionIndex = -1;
2664            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2665            lastCompletionLength = 0;
2666        }
2667        return true;
2668    }
2669
2670    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2671        try {
2672            getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2673        } catch (final SendIntentException ignored) {
2674        }
2675    }
2676
2677    @Override
2678    public void onBackendConnected() {
2679        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2680        String uuid = pendingConversationsUuid.pop();
2681        if (uuid != null) {
2682            if (!findAndReInitByUuidOrArchive(uuid)) {
2683                return;
2684            }
2685        } else {
2686            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2687                clearPending();
2688                activity.onConversationArchived(conversation);
2689                return;
2690            }
2691        }
2692        ActivityResult activityResult = postponedActivityResult.pop();
2693        if (activityResult != null) {
2694            handleActivityResult(activityResult);
2695        }
2696        clearPending();
2697    }
2698
2699    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2700        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2701        if (conversation == null) {
2702            clearPending();
2703            activity.onConversationArchived(null);
2704            return false;
2705        }
2706        reInit(conversation);
2707        ScrollState scrollState = pendingScrollState.pop();
2708        String lastMessageUuid = pendingLastMessageUuid.pop();
2709        List<Attachment> attachments = pendingMediaPreviews.pop();
2710        if (scrollState != null) {
2711            setScrollPosition(scrollState, lastMessageUuid);
2712        }
2713        if (attachments != null && attachments.size() > 0) {
2714            Log.d(Config.LOGTAG, "had attachments on restore");
2715            mediaPreviewAdapter.addMediaPreviews(attachments);
2716            toggleInputMethod();
2717        }
2718        return true;
2719    }
2720
2721    private void clearPending() {
2722        if (postponedActivityResult.clear()) {
2723            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2724        }
2725        if (pendingScrollState.clear()) {
2726            Log.e(Config.LOGTAG, "cleared scroll state");
2727        }
2728        if (pendingTakePhotoUri.clear()) {
2729            Log.e(Config.LOGTAG, "cleared pending photo uri");
2730        }
2731        if (pendingConversationsUuid.clear()) {
2732            Log.e(Config.LOGTAG,"cleared pending conversations uuid");
2733        }
2734        if (pendingMediaPreviews.clear()) {
2735            Log.e(Config.LOGTAG,"cleared pending media previews");
2736        }
2737    }
2738
2739    public Conversation getConversation() {
2740        return conversation;
2741    }
2742
2743    @Override
2744    public void onContactPictureLongClicked(View v, final Message message) {
2745        final String fingerprint;
2746        if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2747            fingerprint = "pgp";
2748        } else {
2749            fingerprint = message.getFingerprint();
2750        }
2751        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
2752        final Contact contact = message.getContact();
2753        if (message.getStatus() <= Message.STATUS_RECEIVED && (contact == null  || !contact.isSelf())) {
2754            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
2755                final Jid cp = message.getCounterpart();
2756                if (cp == null || cp.isBareJid()) {
2757                    return;
2758                }
2759                final Jid tcp = message.getTrueCounterpart();
2760                final User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp) : null;
2761                final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp);
2762                popupMenu.inflate(R.menu.muc_details_context);
2763                final Menu menu = popupMenu.getMenu();
2764                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user);
2765                popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, activity, fingerprint));
2766            } else {
2767                popupMenu.inflate(R.menu.one_on_one_context);
2768                popupMenu.setOnMenuItemClickListener(item -> {
2769                    switch (item.getItemId()) {
2770                        case R.id.action_contact_details:
2771                            activity.switchToContactDetails(message.getContact(), fingerprint);
2772                            break;
2773                        case R.id.action_show_qr_code:
2774                            activity.showQrCode("xmpp:" + message.getContact().getJid().asBareJid().toEscapedString());
2775                            break;
2776                    }
2777                    return true;
2778                });
2779            }
2780        } else {
2781            popupMenu.inflate(R.menu.account_context);
2782            final Menu menu = popupMenu.getMenu();
2783            menu.findItem(R.id.action_manage_accounts).setVisible(QuickConversationsService.isConversations());
2784            popupMenu.setOnMenuItemClickListener(item -> {
2785                switch (item.getItemId()) {
2786                    case R.id.action_show_qr_code:
2787                        activity.showQrCode(conversation.getAccount().getShareableUri());
2788                        break;
2789                    case R.id.action_account_details:
2790                        activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2791                        break;
2792                    case R.id.action_manage_accounts:
2793                        AccountUtils.launchManageAccounts(activity);
2794                        break;
2795                }
2796                return true;
2797            });
2798        }
2799        popupMenu.show();
2800    }
2801
2802    @Override
2803    public void onContactPictureClicked(Message message) {
2804        String fingerprint;
2805        if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2806            fingerprint = "pgp";
2807        } else {
2808            fingerprint = message.getFingerprint();
2809        }
2810        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
2811        if (received) {
2812            if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
2813                Jid tcp = message.getTrueCounterpart();
2814                Jid user = message.getCounterpart();
2815                if (user != null && !user.isBareJid()) {
2816                    final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions();
2817                    if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) {
2818                        if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) {
2819                            Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
2820                        }
2821                        highlightInConference(user.getResource());
2822                    } else {
2823                        Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
2824                    }
2825                }
2826                return;
2827            } else {
2828                if (!message.getContact().isSelf()) {
2829                    activity.switchToContactDetails(message.getContact(), fingerprint);
2830                    return;
2831                }
2832            }
2833        }
2834        activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2835    }
2836}