ConversationFragment.java

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