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