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