ConversationFragment.java

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