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