ConversationFragment.java

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