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