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