ConversationFragment.java

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