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().toString());
 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    }
1317
1318    private void checkPermissionAndTriggerAudioCall() {
1319        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1320            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1321            return;
1322        }
1323        if (hasPermissions(REQUEST_START_AUDIO_CALL, Manifest.permission.RECORD_AUDIO)) {
1324            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1325        }
1326    }
1327
1328    private void checkPermissionAndTriggerVideoCall() {
1329        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1330            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1331            return;
1332        }
1333        if (hasPermissions(REQUEST_START_VIDEO_CALL, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)) {
1334            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1335        }
1336    }
1337
1338
1339    private void triggerRtpSession(final String action) {
1340        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
1341            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG).show();
1342            return;
1343        }
1344        final Contact contact = conversation.getContact();
1345        final Intent intent = new Intent(activity, RtpSessionActivity.class);
1346        intent.setAction(action);
1347        intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, contact.getAccount().getJid().toEscapedString());
1348        intent.putExtra(RtpSessionActivity.EXTRA_WITH, contact.getJid().asBareJid().toEscapedString());
1349        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1350        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
1351        startActivity(intent);
1352    }
1353
1354    private void handleAttachmentSelection(MenuItem item) {
1355        switch (item.getItemId()) {
1356            case R.id.attach_choose_picture:
1357                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1358                break;
1359            case R.id.attach_take_picture:
1360                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1361                break;
1362            case R.id.attach_record_video:
1363                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1364                break;
1365            case R.id.attach_choose_file:
1366                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1367                break;
1368            case R.id.attach_record_voice:
1369                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1370                break;
1371            case R.id.attach_location:
1372                attachFile(ATTACHMENT_CHOICE_LOCATION);
1373                break;
1374        }
1375    }
1376
1377    private void handleEncryptionSelection(MenuItem item) {
1378        if (conversation == null) {
1379            return;
1380        }
1381        final boolean updated;
1382        switch (item.getItemId()) {
1383            case R.id.encryption_choice_none:
1384                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1385                item.setChecked(true);
1386                break;
1387            case R.id.encryption_choice_pgp:
1388                if (activity.hasPgp()) {
1389                    if (conversation.getAccount().getPgpSignature() != null) {
1390                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1391                        item.setChecked(true);
1392                    } else {
1393                        updated = false;
1394                        activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1395                    }
1396                } else {
1397                    activity.showInstallPgpDialog();
1398                    updated = false;
1399                }
1400                break;
1401            case R.id.encryption_choice_axolotl:
1402                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1403                        + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1404                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1405                item.setChecked(true);
1406                break;
1407            default:
1408                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1409                break;
1410        }
1411        if (updated) {
1412            activity.xmppConnectionService.updateConversation(conversation);
1413        }
1414        updateChatMsgHint();
1415        getActivity().invalidateOptionsMenu();
1416        activity.refreshUi();
1417    }
1418
1419    public void attachFile(final int attachmentChoice) {
1420        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1421            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) {
1422                return;
1423            }
1424        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1425            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
1426                return;
1427            }
1428        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1429            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1430                return;
1431            }
1432        }
1433        try {
1434            activity.getPreferences().edit()
1435                    .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1436                    .apply();
1437        } catch (IllegalArgumentException e) {
1438            //just do not save
1439        }
1440        final int encryption = conversation.getNextEncryption();
1441        final int mode = conversation.getMode();
1442        if (encryption == Message.ENCRYPTION_PGP) {
1443            if (activity.hasPgp()) {
1444                if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1445                    activity.xmppConnectionService.getPgpEngine().hasKey(
1446                            conversation.getContact(),
1447                            new UiCallback<Contact>() {
1448
1449                                @Override
1450                                public void userInputRequired(PendingIntent pi, Contact contact) {
1451                                    startPendingIntent(pi, attachmentChoice);
1452                                }
1453
1454                                @Override
1455                                public void success(Contact contact) {
1456                                    invokeAttachFileIntent(attachmentChoice);
1457                                }
1458
1459                                @Override
1460                                public void error(int error, Contact contact) {
1461                                    activity.replaceToast(getString(error));
1462                                }
1463                            });
1464                } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1465                    if (!conversation.getMucOptions().everybodyHasKeys()) {
1466                        Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1467                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1468                        warning.show();
1469                    }
1470                    invokeAttachFileIntent(attachmentChoice);
1471                } else {
1472                    showNoPGPKeyDialog(false, (dialog, which) -> {
1473                        conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1474                        activity.xmppConnectionService.updateConversation(conversation);
1475                        invokeAttachFileIntent(attachmentChoice);
1476                    });
1477                }
1478            } else {
1479                activity.showInstallPgpDialog();
1480            }
1481        } else {
1482            invokeAttachFileIntent(attachmentChoice);
1483        }
1484    }
1485
1486    @Override
1487    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1488        if (grantResults.length > 0) {
1489            if (allGranted(grantResults)) {
1490                switch (requestCode) {
1491                    case REQUEST_START_DOWNLOAD:
1492                        if (this.mPendingDownloadableMessage != null) {
1493                            startDownloadable(this.mPendingDownloadableMessage);
1494                        }
1495                        break;
1496                    case REQUEST_ADD_EDITOR_CONTENT:
1497                        if (this.mPendingEditorContent != null) {
1498                            attachEditorContentToConversation(this.mPendingEditorContent);
1499                        }
1500                        break;
1501                    case REQUEST_COMMIT_ATTACHMENTS:
1502                        commitAttachments();
1503                        break;
1504                    case REQUEST_START_AUDIO_CALL:
1505                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1506                        break;
1507                    case REQUEST_START_VIDEO_CALL:
1508                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1509                        break;
1510                    default:
1511                        attachFile(requestCode);
1512                        break;
1513                }
1514            } else {
1515                @StringRes int res;
1516                String firstDenied = getFirstDenied(grantResults, permissions);
1517                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1518                    res = R.string.no_microphone_permission;
1519                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1520                    res = R.string.no_camera_permission;
1521                } else {
1522                    res = R.string.no_storage_permission;
1523                }
1524                Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1525            }
1526        }
1527        if (writeGranted(grantResults, permissions)) {
1528            if (activity != null && activity.xmppConnectionService != null) {
1529                activity.xmppConnectionService.restartFileObserver();
1530            }
1531            refresh();
1532        }
1533    }
1534
1535    public void startDownloadable(Message message) {
1536        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1537            this.mPendingDownloadableMessage = message;
1538            return;
1539        }
1540        Transferable transferable = message.getTransferable();
1541        if (transferable != null) {
1542            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1543                createNewConnection(message);
1544                return;
1545            }
1546            if (!transferable.start()) {
1547                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1548                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1549            }
1550        } else if (message.treatAsDownloadable() || message.hasFileOnRemoteHost() || MessageUtils.unInitiatedButKnownSize(message)) {
1551            createNewConnection(message);
1552        } else {
1553            Log.d(Config.LOGTAG, message.getConversation().getAccount() + ": unable to start downloadable");
1554        }
1555    }
1556
1557    private void createNewConnection(final Message message) {
1558        if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) {
1559            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1560            return;
1561        }
1562        activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1563    }
1564
1565    @SuppressLint("InflateParams")
1566    protected void clearHistoryDialog(final Conversation conversation) {
1567        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1568        builder.setTitle(getString(R.string.clear_conversation_history));
1569        final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1570        final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1571        builder.setView(dialogView);
1572        builder.setNegativeButton(getString(R.string.cancel), null);
1573        builder.setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
1574            this.activity.xmppConnectionService.clearConversationHistory(conversation);
1575            if (endConversationCheckBox.isChecked()) {
1576                this.activity.xmppConnectionService.archiveConversation(conversation);
1577                this.activity.onConversationArchived(conversation);
1578            } else {
1579                activity.onConversationsListItemUpdated();
1580                refresh();
1581            }
1582        });
1583        builder.create().show();
1584    }
1585
1586    protected void muteConversationDialog(final Conversation conversation) {
1587        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1588        builder.setTitle(R.string.disable_notifications);
1589        final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1590        final CharSequence[] labels = new CharSequence[durations.length];
1591        for (int i = 0; i < durations.length; ++i) {
1592            if (durations[i] == -1) {
1593                labels[i] = getString(R.string.until_further_notice);
1594            } else {
1595                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
1596            }
1597        }
1598        builder.setItems(labels, (dialog, which) -> {
1599            final long till;
1600            if (durations[which] == -1) {
1601                till = Long.MAX_VALUE;
1602            } else {
1603                till = System.currentTimeMillis() + (durations[which] * 1000);
1604            }
1605            conversation.setMutedTill(till);
1606            activity.xmppConnectionService.updateConversation(conversation);
1607            activity.onConversationsListItemUpdated();
1608            refresh();
1609            getActivity().invalidateOptionsMenu();
1610        });
1611        builder.create().show();
1612    }
1613
1614    private boolean hasPermissions(int requestCode, String... permissions) {
1615        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1616            final List<String> missingPermissions = new ArrayList<>();
1617            for (String permission : permissions) {
1618                if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1619                    continue;
1620                }
1621                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
1622                    missingPermissions.add(permission);
1623                }
1624            }
1625            if (missingPermissions.size() == 0) {
1626                return true;
1627            } else {
1628                requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1629                return false;
1630            }
1631        } else {
1632            return true;
1633        }
1634    }
1635
1636    public void unmuteConversation(final Conversation conversation) {
1637        conversation.setMutedTill(0);
1638        this.activity.xmppConnectionService.updateConversation(conversation);
1639        this.activity.onConversationsListItemUpdated();
1640        refresh();
1641        getActivity().invalidateOptionsMenu();
1642    }
1643
1644
1645    protected void invokeAttachFileIntent(final int attachmentChoice) {
1646        Intent intent = new Intent();
1647        boolean chooser = false;
1648        switch (attachmentChoice) {
1649            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1650                intent.setAction(Intent.ACTION_GET_CONTENT);
1651                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1652                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1653                }
1654                intent.setType("image/*");
1655                chooser = true;
1656                break;
1657            case ATTACHMENT_CHOICE_RECORD_VIDEO:
1658                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1659                break;
1660            case ATTACHMENT_CHOICE_TAKE_PHOTO:
1661                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1662                pendingTakePhotoUri.push(uri);
1663                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1664                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1665                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1666                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1667                break;
1668            case ATTACHMENT_CHOICE_CHOOSE_FILE:
1669                chooser = true;
1670                intent.setType("*/*");
1671                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1672                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1673                }
1674                intent.addCategory(Intent.CATEGORY_OPENABLE);
1675                intent.setAction(Intent.ACTION_GET_CONTENT);
1676                break;
1677            case ATTACHMENT_CHOICE_RECORD_VOICE:
1678                intent = new Intent(getActivity(), RecordingActivity.class);
1679                break;
1680            case ATTACHMENT_CHOICE_LOCATION:
1681                intent = GeoHelper.getFetchIntent(activity);
1682                break;
1683        }
1684        final Context context = getActivity();
1685        if (context != null && intent.resolveActivity(context.getPackageManager()) != null) {
1686            if (chooser) {
1687                startActivityForResult(
1688                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
1689                        attachmentChoice);
1690            } else {
1691                startActivityForResult(intent, attachmentChoice);
1692            }
1693        }
1694    }
1695
1696    @Override
1697    public void onResume() {
1698        super.onResume();
1699        binding.messagesView.post(this::fireReadEvent);
1700    }
1701
1702    private void fireReadEvent() {
1703        if (activity != null && this.conversation != null) {
1704            String uuid = getLastVisibleMessageUuid();
1705            if (uuid != null) {
1706                activity.onConversationRead(this.conversation, uuid);
1707            }
1708        }
1709    }
1710
1711    private String getLastVisibleMessageUuid() {
1712        if (binding == null) {
1713            return null;
1714        }
1715        synchronized (this.messageList) {
1716            int pos = binding.messagesView.getLastVisiblePosition();
1717            if (pos >= 0) {
1718                Message message = null;
1719                for (int i = pos; i >= 0; --i) {
1720                    try {
1721                        message = (Message) binding.messagesView.getItemAtPosition(i);
1722                    } catch (IndexOutOfBoundsException e) {
1723                        //should not happen if we synchronize properly. however if that fails we just gonna try item -1
1724                        continue;
1725                    }
1726                    if (message.getType() != Message.TYPE_STATUS) {
1727                        break;
1728                    }
1729                }
1730                if (message != null) {
1731                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
1732                        message = message.next();
1733                    }
1734                    return message.getUuid();
1735                }
1736            }
1737        }
1738        return null;
1739    }
1740
1741    private void openWith(final Message message) {
1742        if (message.isGeoUri()) {
1743            GeoHelper.view(getActivity(), message);
1744        } else {
1745            final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1746            ViewUtil.view(activity, file);
1747        }
1748    }
1749
1750    private void showErrorMessage(final Message message) {
1751        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1752        builder.setTitle(R.string.error_message);
1753        final String errorMessage = message.getErrorMessage();
1754        final String[] errorMessageParts = errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
1755        final String displayError;
1756        if (errorMessageParts.length == 2) {
1757            displayError = errorMessageParts[1];
1758        } else {
1759            displayError = errorMessage;
1760        }
1761        builder.setMessage(displayError);
1762        builder.setNegativeButton(R.string.copy_to_clipboard, (dialog, which) -> {
1763            activity.copyTextToClipboard(displayError, R.string.error_message);
1764            Toast.makeText(activity, R.string.error_message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1765        });
1766        builder.setPositiveButton(R.string.confirm, null);
1767        builder.create().show();
1768    }
1769
1770
1771    private void deleteFile(final Message message) {
1772        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1773        builder.setNegativeButton(R.string.cancel, null);
1774        builder.setTitle(R.string.delete_file_dialog);
1775        builder.setMessage(R.string.delete_file_dialog_msg);
1776        builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
1777            if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1778                message.setDeleted(true);
1779                activity.xmppConnectionService.evictPreview(message.getUuid());
1780                activity.xmppConnectionService.updateMessage(message, false);
1781                activity.onConversationsListItemUpdated();
1782                refresh();
1783            }
1784        });
1785        builder.create().show();
1786
1787    }
1788
1789    private void resendMessage(final Message message) {
1790        if (message.isFileOrImage()) {
1791            if (!(message.getConversation() instanceof Conversation)) {
1792                return;
1793            }
1794            final Conversation conversation = (Conversation) message.getConversation();
1795            final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1796            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
1797                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1798                if (!message.hasFileOnRemoteHost()
1799                        && xmppConnection != null
1800                        && conversation.getMode() == Conversational.MODE_SINGLE
1801                        && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1802                    activity.selectPresence(conversation, () -> {
1803                        message.setCounterpart(conversation.getNextCounterpart());
1804                        activity.xmppConnectionService.resendFailedMessages(message);
1805                        new Handler().post(() -> {
1806                            int size = messageList.size();
1807                            this.binding.messagesView.setSelection(size - 1);
1808                        });
1809                    });
1810                    return;
1811                }
1812            } else if (!Compatibility.hasStoragePermission(getActivity())) {
1813                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
1814                return;
1815            } else {
1816                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1817                message.setDeleted(true);
1818                activity.xmppConnectionService.updateMessage(message, false);
1819                activity.onConversationsListItemUpdated();
1820                refresh();
1821                return;
1822            }
1823        }
1824        activity.xmppConnectionService.resendFailedMessages(message);
1825        new Handler().post(() -> {
1826            int size = messageList.size();
1827            this.binding.messagesView.setSelection(size - 1);
1828        });
1829    }
1830
1831    private void cancelTransmission(Message message) {
1832        Transferable transferable = message.getTransferable();
1833        if (transferable != null) {
1834            transferable.cancel();
1835        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1836            activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
1837        }
1838    }
1839
1840    private void retryDecryption(Message message) {
1841        message.setEncryption(Message.ENCRYPTION_PGP);
1842        activity.onConversationsListItemUpdated();
1843        refresh();
1844        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1845    }
1846
1847    public void privateMessageWith(final Jid counterpart) {
1848        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1849            activity.xmppConnectionService.sendChatState(conversation);
1850        }
1851        this.binding.textinput.setText("");
1852        this.conversation.setNextCounterpart(counterpart);
1853        updateChatMsgHint();
1854        updateSendButton();
1855        updateEditablity();
1856    }
1857
1858    private void correctMessage(Message message) {
1859        while (message.mergeable(message.next())) {
1860            message = message.next();
1861        }
1862        this.conversation.setCorrectingMessage(message);
1863        final Editable editable = binding.textinput.getText();
1864        this.conversation.setDraftMessage(editable.toString());
1865        this.binding.textinput.setText("");
1866        this.binding.textinput.append(message.getBody());
1867
1868    }
1869
1870    private void highlightInConference(String nick) {
1871        final Editable editable = this.binding.textinput.getText();
1872        String oldString = editable.toString().trim();
1873        final int pos = this.binding.textinput.getSelectionStart();
1874        if (oldString.isEmpty() || pos == 0) {
1875            editable.insert(0, nick + ": ");
1876        } else {
1877            final char before = editable.charAt(pos - 1);
1878            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1879            if (before == '\n') {
1880                editable.insert(pos, nick + ": ");
1881            } else {
1882                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1883                    if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1884                        editable.insert(pos - 2, ", " + nick);
1885                        return;
1886                    }
1887                }
1888                editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1889                if (Character.isWhitespace(after)) {
1890                    this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1891                }
1892            }
1893        }
1894    }
1895
1896    @Override
1897    public void startActivityForResult(Intent intent, int requestCode) {
1898        final Activity activity = getActivity();
1899        if (activity instanceof ConversationsActivity) {
1900            ((ConversationsActivity) activity).clearPendingViewIntent();
1901        }
1902        super.startActivityForResult(intent, requestCode);
1903    }
1904
1905    @Override
1906    public void onSaveInstanceState(Bundle outState) {
1907        super.onSaveInstanceState(outState);
1908        if (conversation != null) {
1909            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1910            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1911            final Uri uri = pendingTakePhotoUri.peek();
1912            if (uri != null) {
1913                outState.putString(STATE_PHOTO_URI, uri.toString());
1914            }
1915            final ScrollState scrollState = getScrollPosition();
1916            if (scrollState != null) {
1917                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1918            }
1919            final ArrayList<Attachment> attachments = mediaPreviewAdapter == null ? new ArrayList<>() : mediaPreviewAdapter.getAttachments();
1920            if (attachments.size() > 0) {
1921                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
1922            }
1923        }
1924    }
1925
1926    @Override
1927    public void onActivityCreated(Bundle savedInstanceState) {
1928        super.onActivityCreated(savedInstanceState);
1929        if (savedInstanceState == null) {
1930            return;
1931        }
1932        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1933        ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
1934        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1935        if (uuid != null) {
1936            QuickLoader.set(uuid);
1937            this.pendingConversationsUuid.push(uuid);
1938            if (attachments != null && attachments.size() > 0) {
1939                this.pendingMediaPreviews.push(attachments);
1940            }
1941            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1942            if (takePhotoUri != null) {
1943                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1944            }
1945            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1946        }
1947    }
1948
1949    @Override
1950    public void onStart() {
1951        super.onStart();
1952        if (this.reInitRequiredOnStart && this.conversation != null) {
1953            final Bundle extras = pendingExtras.pop();
1954            reInit(this.conversation, extras != null);
1955            if (extras != null) {
1956                processExtras(extras);
1957            }
1958        } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1959            final String uuid = pendingConversationsUuid.pop();
1960            Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1961            if (uuid != null) {
1962                findAndReInitByUuidOrArchive(uuid);
1963            }
1964        }
1965    }
1966
1967    @Override
1968    public void onStop() {
1969        super.onStop();
1970        final Activity activity = getActivity();
1971        messageListAdapter.unregisterListenerInAudioPlayer();
1972        if (activity == null || !activity.isChangingConfigurations()) {
1973            hideSoftKeyboard(activity);
1974            messageListAdapter.stopAudioPlayer();
1975        }
1976        if (this.conversation != null) {
1977            final String msg = this.binding.textinput.getText().toString();
1978            storeNextMessage(msg);
1979            updateChatState(this.conversation, msg);
1980            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1981        }
1982        this.reInitRequiredOnStart = true;
1983    }
1984
1985    private void updateChatState(final Conversation conversation, final String msg) {
1986        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
1987        Account.State status = conversation.getAccount().getStatus();
1988        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1989            activity.xmppConnectionService.sendChatState(conversation);
1990        }
1991    }
1992
1993    private void saveMessageDraftStopAudioPlayer() {
1994        final Conversation previousConversation = this.conversation;
1995        if (this.activity == null || this.binding == null || previousConversation == null) {
1996            return;
1997        }
1998        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1999        final String msg = this.binding.textinput.getText().toString();
2000        storeNextMessage(msg);
2001        updateChatState(this.conversation, msg);
2002        messageListAdapter.stopAudioPlayer();
2003        mediaPreviewAdapter.clearPreviews();
2004        toggleInputMethod();
2005    }
2006
2007    public void reInit(Conversation conversation, Bundle extras) {
2008        QuickLoader.set(conversation.getUuid());
2009        this.saveMessageDraftStopAudioPlayer();
2010        this.clearPending();
2011        if (this.reInit(conversation, extras != null)) {
2012            if (extras != null) {
2013                processExtras(extras);
2014            }
2015            this.reInitRequiredOnStart = false;
2016        } else {
2017            this.reInitRequiredOnStart = true;
2018            pendingExtras.push(extras);
2019        }
2020        resetUnreadMessagesCount();
2021    }
2022
2023    private void reInit(Conversation conversation) {
2024        reInit(conversation, false);
2025    }
2026
2027    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2028        if (conversation == null) {
2029            return false;
2030        }
2031        this.conversation = conversation;
2032        //once we set the conversation all is good and it will automatically do the right thing in onStart()
2033        if (this.activity == null || this.binding == null) {
2034            return false;
2035        }
2036
2037        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2038            activity.onConversationArchived(this.conversation);
2039            return false;
2040        }
2041
2042        stopScrolling();
2043        Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
2044
2045        if (this.conversation.isRead() && hasExtras) {
2046            Log.d(Config.LOGTAG, "trimming conversation");
2047            this.conversation.trim();
2048        }
2049
2050        setupIme();
2051
2052        final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
2053
2054        this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
2055        this.binding.textinput.setKeyboardListener(null);
2056        this.binding.textinput.setText("");
2057        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2058        if (participating) {
2059            this.binding.textinput.append(this.conversation.getNextMessage());
2060        }
2061        this.binding.textinput.setKeyboardListener(this);
2062        messageListAdapter.updatePreferences();
2063        refresh(false);
2064        this.conversation.messagesLoaded.set(true);
2065        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
2066
2067        if (hasExtras || scrolledToBottomAndNoPending) {
2068            resetUnreadMessagesCount();
2069            synchronized (this.messageList) {
2070                Log.d(Config.LOGTAG, "jump to first unread message");
2071                final Message first = conversation.getFirstUnreadMessage();
2072                final int bottom = Math.max(0, this.messageList.size() - 1);
2073                final int pos;
2074                final boolean jumpToBottom;
2075                if (first == null) {
2076                    pos = bottom;
2077                    jumpToBottom = true;
2078                } else {
2079                    int i = getIndexOf(first.getUuid(), this.messageList);
2080                    pos = i < 0 ? bottom : i;
2081                    jumpToBottom = false;
2082                }
2083                setSelection(pos, jumpToBottom);
2084            }
2085        }
2086
2087
2088        this.binding.messagesView.post(this::fireReadEvent);
2089        //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
2090        activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
2091        return true;
2092    }
2093
2094    private void resetUnreadMessagesCount() {
2095        lastMessageUuid = null;
2096        hideUnreadMessagesCount();
2097    }
2098
2099    private void hideUnreadMessagesCount() {
2100        if (this.binding == null) {
2101            return;
2102        }
2103        this.binding.scrollToBottomButton.setEnabled(false);
2104        this.binding.scrollToBottomButton.hide();
2105        this.binding.unreadCountCustomView.setVisibility(View.GONE);
2106    }
2107
2108    private void setSelection(int pos, boolean jumpToBottom) {
2109        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2110        this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2111        this.binding.messagesView.post(this::fireReadEvent);
2112    }
2113
2114
2115    private boolean scrolledToBottom() {
2116        return this.binding != null && scrolledToBottom(this.binding.messagesView);
2117    }
2118
2119    private void processExtras(Bundle extras) {
2120        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2121        final String text = extras.getString(Intent.EXTRA_TEXT);
2122        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2123        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2124        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2125        final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2126        final List<Uri> uris = extractUris(extras);
2127        if (uris != null && uris.size() > 0) {
2128            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2129                mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2130            } else {
2131                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2132                mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
2133            }
2134            toggleInputMethod();
2135            return;
2136        }
2137        if (nick != null) {
2138            if (pm) {
2139                Jid jid = conversation.getJid();
2140                try {
2141                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2142                    privateMessageWith(next);
2143                } catch (final IllegalArgumentException ignored) {
2144                    //do nothing
2145                }
2146            } else {
2147                final MucOptions mucOptions = conversation.getMucOptions();
2148                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2149                    highlightInConference(nick);
2150                }
2151            }
2152        } else {
2153            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
2154                mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2155                toggleInputMethod();
2156                return;
2157            } else if (text != null && asQuote) {
2158                quoteText(text);
2159            } else {
2160                appendText(text, doNotAppend);
2161            }
2162        }
2163        final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2164        if (message != null) {
2165            startDownloadable(message);
2166        }
2167    }
2168
2169    private List<Uri> extractUris(Bundle extras) {
2170        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2171        if (uris != null) {
2172            return uris;
2173        }
2174        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2175        if (uri != null) {
2176            return Collections.singletonList(uri);
2177        } else {
2178            return null;
2179        }
2180    }
2181
2182    private List<Uri> cleanUris(List<Uri> uris) {
2183        Iterator<Uri> iterator = uris.iterator();
2184        while (iterator.hasNext()) {
2185            final Uri uri = iterator.next();
2186            if (FileBackend.weOwnFile(getActivity(), uri)) {
2187                iterator.remove();
2188                Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show();
2189            }
2190        }
2191        return uris;
2192    }
2193
2194    private boolean showBlockSubmenu(View view) {
2195        final Jid jid = conversation.getJid();
2196        final boolean showReject = !conversation.isWithStranger() && conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2197        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2198        popupMenu.inflate(R.menu.block);
2199        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2200        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2201        popupMenu.setOnMenuItemClickListener(menuItem -> {
2202            Blockable blockable;
2203            switch (menuItem.getItemId()) {
2204                case R.id.reject:
2205                    activity.xmppConnectionService.stopPresenceUpdatesTo(conversation.getContact());
2206                    updateSnackBar(conversation);
2207                    return true;
2208                case R.id.block_domain:
2209                    blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2210                    break;
2211                default:
2212                    blockable = conversation;
2213            }
2214            BlockContactDialog.show(activity, blockable);
2215            return true;
2216        });
2217        popupMenu.show();
2218        return true;
2219    }
2220
2221    private void updateSnackBar(final Conversation conversation) {
2222        final Account account = conversation.getAccount();
2223        final XmppConnection connection = account.getXmppConnection();
2224        final int mode = conversation.getMode();
2225        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2226        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2227            return;
2228        }
2229        if (account.getStatus() == Account.State.DISABLED) {
2230            showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2231        } else if (conversation.isBlocked()) {
2232            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2233        } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2234            showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2235        } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2236            showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2237        } else if (mode == Conversation.MODE_MULTI
2238                && !conversation.getMucOptions().online()
2239                && account.getStatus() == Account.State.ONLINE) {
2240            switch (conversation.getMucOptions().getError()) {
2241                case NICK_IN_USE:
2242                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2243                    break;
2244                case NO_RESPONSE:
2245                    showSnackbar(R.string.joining_conference, 0, null);
2246                    break;
2247                case SERVER_NOT_FOUND:
2248                    if (conversation.receivedMessagesCount() > 0) {
2249                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2250                    } else {
2251                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2252                    }
2253                    break;
2254                case REMOTE_SERVER_TIMEOUT:
2255                    if (conversation.receivedMessagesCount() > 0) {
2256                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2257                    } else {
2258                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2259                    }
2260                    break;
2261                case PASSWORD_REQUIRED:
2262                    showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2263                    break;
2264                case BANNED:
2265                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2266                    break;
2267                case MEMBERS_ONLY:
2268                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2269                    break;
2270                case RESOURCE_CONSTRAINT:
2271                    showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2272                    break;
2273                case KICKED:
2274                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2275                    break;
2276                case UNKNOWN:
2277                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2278                    break;
2279                case INVALID_NICK:
2280                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2281                case SHUTDOWN:
2282                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2283                    break;
2284                case DESTROYED:
2285                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2286                    break;
2287                case NON_ANONYMOUS:
2288                    showSnackbar(R.string.group_chat_will_make_your_jabber_id_public, R.string.join, acceptJoin);
2289                    break;
2290                default:
2291                    hideSnackbar();
2292                    break;
2293            }
2294        } else if (account.hasPendingPgpIntent(conversation)) {
2295            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2296        } else if (connection != null
2297                && connection.getFeatures().blocking()
2298                && conversation.countMessages() != 0
2299                && !conversation.isBlocked()
2300                && conversation.isWithStranger()) {
2301            showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2302        } else {
2303            hideSnackbar();
2304        }
2305    }
2306
2307    @Override
2308    public void refresh() {
2309        if (this.binding == null) {
2310            Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2311            return;
2312        }
2313        if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2314            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2315                activity.onConversationArchived(this.conversation);
2316                return;
2317            }
2318        }
2319        this.refresh(true);
2320    }
2321
2322    private void refresh(boolean notifyConversationRead) {
2323        synchronized (this.messageList) {
2324            if (this.conversation != null) {
2325                conversation.populateWithMessages(this.messageList);
2326                updateSnackBar(conversation);
2327                updateStatusMessages();
2328                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2329                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2330                    binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2331                }
2332                this.messageListAdapter.notifyDataSetChanged();
2333                updateChatMsgHint();
2334                if (notifyConversationRead && activity != null) {
2335                    binding.messagesView.post(this::fireReadEvent);
2336                }
2337                updateSendButton();
2338                updateEditablity();
2339                activity.invalidateOptionsMenu();
2340            }
2341        }
2342    }
2343
2344    protected void messageSent() {
2345        mSendingPgpMessage.set(false);
2346        this.binding.textinput.setText("");
2347        if (conversation.setCorrectingMessage(null)) {
2348            this.binding.textinput.append(conversation.getDraftMessage());
2349            conversation.setDraftMessage(null);
2350        }
2351        storeNextMessage();
2352        updateChatMsgHint();
2353        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2354        final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2355        if (prefScrollToBottom || scrolledToBottom()) {
2356            new Handler().post(() -> {
2357                int size = messageList.size();
2358                this.binding.messagesView.setSelection(size - 1);
2359            });
2360        }
2361    }
2362
2363    private boolean storeNextMessage() {
2364        return storeNextMessage(this.binding.textinput.getText().toString());
2365    }
2366
2367    private boolean storeNextMessage(String msg) {
2368        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2369        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
2370            this.activity.xmppConnectionService.updateConversation(this.conversation);
2371            return true;
2372        }
2373        return false;
2374    }
2375
2376    public void doneSendingPgpMessage() {
2377        mSendingPgpMessage.set(false);
2378    }
2379
2380    public long getMaxHttpUploadSize(Conversation conversation) {
2381        final XmppConnection connection = conversation.getAccount().getXmppConnection();
2382        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2383    }
2384
2385    private void updateEditablity() {
2386        boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2387        this.binding.textinput.setFocusable(canWrite);
2388        this.binding.textinput.setFocusableInTouchMode(canWrite);
2389        this.binding.textSendButton.setEnabled(canWrite);
2390        this.binding.textinput.setCursorVisible(canWrite);
2391        this.binding.textinput.setEnabled(canWrite);
2392    }
2393
2394    public void updateSendButton() {
2395        boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2396        final Conversation c = this.conversation;
2397        final Presence.Status status;
2398        final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2399        final SendButtonAction action;
2400        if (hasAttachments) {
2401            action = SendButtonAction.TEXT;
2402        } else {
2403            action = SendButtonTool.getAction(getActivity(), c, text);
2404        }
2405        if (c.getAccount().getStatus() == Account.State.ONLINE) {
2406            if (activity != null && activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2407                status = Presence.Status.OFFLINE;
2408            } else if (c.getMode() == Conversation.MODE_SINGLE) {
2409                status = c.getContact().getShownStatus();
2410            } else {
2411                status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2412            }
2413        } else {
2414            status = Presence.Status.OFFLINE;
2415        }
2416        this.binding.textSendButton.setTag(action);
2417        final Activity activity = getActivity();
2418        if (activity != null) {
2419            this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(activity, action, status));
2420        }
2421    }
2422
2423    protected void updateStatusMessages() {
2424        DateSeparator.addAll(this.messageList);
2425        if (showLoadMoreMessages(conversation)) {
2426            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2427        }
2428        if (conversation.getMode() == Conversation.MODE_SINGLE) {
2429            ChatState state = conversation.getIncomingChatState();
2430            if (state == ChatState.COMPOSING) {
2431                this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2432            } else if (state == ChatState.PAUSED) {
2433                this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2434            } else {
2435                for (int i = this.messageList.size() - 1; i >= 0; --i) {
2436                    final Message message = this.messageList.get(i);
2437                    if (message.getType() != Message.TYPE_STATUS) {
2438                        if (message.getStatus() == Message.STATUS_RECEIVED) {
2439                            return;
2440                        } else {
2441                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
2442                                this.messageList.add(i + 1,
2443                                        Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2444                                return;
2445                            }
2446                        }
2447                    }
2448                }
2449            }
2450        } else {
2451            final MucOptions mucOptions = conversation.getMucOptions();
2452            final List<MucOptions.User> allUsers = mucOptions.getUsers();
2453            final Set<ReadByMarker> addedMarkers = new HashSet<>();
2454            ChatState state = ChatState.COMPOSING;
2455            List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2456            if (users.size() == 0) {
2457                state = ChatState.PAUSED;
2458                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2459            }
2460            if (mucOptions.isPrivateAndNonAnonymous()) {
2461                for (int i = this.messageList.size() - 1; i >= 0; --i) {
2462                    final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2463                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
2464                    for (ReadByMarker marker : markersForMessage) {
2465                        if (!ReadByMarker.contains(marker, addedMarkers)) {
2466                            addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2467                            MucOptions.User user = mucOptions.findUser(marker);
2468                            if (user != null && !users.contains(user)) {
2469                                shownMarkers.add(user);
2470                            }
2471                        }
2472                    }
2473                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2474                    final Message statusMessage;
2475                    final int size = shownMarkers.size();
2476                    if (size > 1) {
2477                        final String body;
2478                        if (size <= 4) {
2479                            body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2480                        } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
2481                            body = getString(R.string.everyone_has_read_up_to_this_point);
2482                        } else {
2483                            body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2484                        }
2485                        statusMessage = Message.createStatusMessage(conversation, body);
2486                        statusMessage.setCounterparts(shownMarkers);
2487                    } else if (size == 1) {
2488                        statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2489                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2490                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2491                    } else {
2492                        statusMessage = null;
2493                    }
2494                    if (statusMessage != null) {
2495                        this.messageList.add(i + 1, statusMessage);
2496                    }
2497                    addedMarkers.add(markerForSender);
2498                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2499                        break;
2500                    }
2501                }
2502            }
2503            if (users.size() > 0) {
2504                Message statusMessage;
2505                if (users.size() == 1) {
2506                    MucOptions.User user = users.get(0);
2507                    int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2508                    statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2509                    statusMessage.setTrueCounterpart(user.getRealJid());
2510                    statusMessage.setCounterpart(user.getFullJid());
2511                } else {
2512                    int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2513                    statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2514                    statusMessage.setCounterparts(users);
2515                }
2516                this.messageList.add(statusMessage);
2517            }
2518
2519        }
2520    }
2521
2522    private void stopScrolling() {
2523        long now = SystemClock.uptimeMillis();
2524        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2525        binding.messagesView.dispatchTouchEvent(cancel);
2526    }
2527
2528    private boolean showLoadMoreMessages(final Conversation c) {
2529        if (activity == null || activity.xmppConnectionService == null) {
2530            return false;
2531        }
2532        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2533        final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2534        return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2535    }
2536
2537    private boolean hasMamSupport(final Conversation c) {
2538        if (c.getMode() == Conversation.MODE_SINGLE) {
2539            final XmppConnection connection = c.getAccount().getXmppConnection();
2540            return connection != null && connection.getFeatures().mam();
2541        } else {
2542            return c.getMucOptions().mamSupport();
2543        }
2544    }
2545
2546    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2547        showSnackbar(message, action, clickListener, null);
2548    }
2549
2550    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2551        this.binding.snackbar.setVisibility(View.VISIBLE);
2552        this.binding.snackbar.setOnClickListener(null);
2553        this.binding.snackbarMessage.setText(message);
2554        this.binding.snackbarMessage.setOnClickListener(null);
2555        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2556        if (action != 0) {
2557            this.binding.snackbarAction.setText(action);
2558        }
2559        this.binding.snackbarAction.setOnClickListener(clickListener);
2560        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2561    }
2562
2563    protected void hideSnackbar() {
2564        this.binding.snackbar.setVisibility(View.GONE);
2565    }
2566
2567    protected void sendMessage(Message message) {
2568        activity.xmppConnectionService.sendMessage(message);
2569        messageSent();
2570    }
2571
2572    protected void sendPgpMessage(final Message message) {
2573        final XmppConnectionService xmppService = activity.xmppConnectionService;
2574        final Contact contact = message.getConversation().getContact();
2575        if (!activity.hasPgp()) {
2576            activity.showInstallPgpDialog();
2577            return;
2578        }
2579        if (conversation.getAccount().getPgpSignature() == null) {
2580            activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2581            return;
2582        }
2583        if (!mSendingPgpMessage.compareAndSet(false, true)) {
2584            Log.d(Config.LOGTAG, "sending pgp message already in progress");
2585        }
2586        if (conversation.getMode() == Conversation.MODE_SINGLE) {
2587            if (contact.getPgpKeyId() != 0) {
2588                xmppService.getPgpEngine().hasKey(contact,
2589                        new UiCallback<Contact>() {
2590
2591                            @Override
2592                            public void userInputRequired(PendingIntent pi, Contact contact) {
2593                                startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2594                            }
2595
2596                            @Override
2597                            public void success(Contact contact) {
2598                                encryptTextMessage(message);
2599                            }
2600
2601                            @Override
2602                            public void error(int error, Contact contact) {
2603                                activity.runOnUiThread(() -> Toast.makeText(activity,
2604                                        R.string.unable_to_connect_to_keychain,
2605                                        Toast.LENGTH_SHORT
2606                                ).show());
2607                                mSendingPgpMessage.set(false);
2608                            }
2609                        });
2610
2611            } else {
2612                showNoPGPKeyDialog(false, (dialog, which) -> {
2613                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2614                    xmppService.updateConversation(conversation);
2615                    message.setEncryption(Message.ENCRYPTION_NONE);
2616                    xmppService.sendMessage(message);
2617                    messageSent();
2618                });
2619            }
2620        } else {
2621            if (conversation.getMucOptions().pgpKeysInUse()) {
2622                if (!conversation.getMucOptions().everybodyHasKeys()) {
2623                    Toast warning = Toast
2624                            .makeText(getActivity(),
2625                                    R.string.missing_public_keys,
2626                                    Toast.LENGTH_LONG);
2627                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2628                    warning.show();
2629                }
2630                encryptTextMessage(message);
2631            } else {
2632                showNoPGPKeyDialog(true, (dialog, which) -> {
2633                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2634                    message.setEncryption(Message.ENCRYPTION_NONE);
2635                    xmppService.updateConversation(conversation);
2636                    xmppService.sendMessage(message);
2637                    messageSent();
2638                });
2639            }
2640        }
2641    }
2642
2643    public void encryptTextMessage(Message message) {
2644        activity.xmppConnectionService.getPgpEngine().encrypt(message,
2645                new UiCallback<Message>() {
2646
2647                    @Override
2648                    public void userInputRequired(PendingIntent pi, Message message) {
2649                        startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2650                    }
2651
2652                    @Override
2653                    public void success(Message message) {
2654                        //TODO the following two call can be made before the callback
2655                        getActivity().runOnUiThread(() -> messageSent());
2656                    }
2657
2658                    @Override
2659                    public void error(final int error, Message message) {
2660                        getActivity().runOnUiThread(() -> {
2661                            doneSendingPgpMessage();
2662                            Toast.makeText(getActivity(), error == 0 ? R.string.unable_to_connect_to_keychain : error, Toast.LENGTH_SHORT).show();
2663                        });
2664
2665                    }
2666                });
2667    }
2668
2669    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2670        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2671        builder.setIconAttribute(android.R.attr.alertDialogIcon);
2672        if (plural) {
2673            builder.setTitle(getString(R.string.no_pgp_keys));
2674            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2675        } else {
2676            builder.setTitle(getString(R.string.no_pgp_key));
2677            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2678        }
2679        builder.setNegativeButton(getString(R.string.cancel), null);
2680        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2681        builder.create().show();
2682    }
2683
2684    public void appendText(String text, final boolean doNotAppend) {
2685        if (text == null) {
2686            return;
2687        }
2688        final Editable editable = this.binding.textinput.getText();
2689        String previous = editable == null ? "" : editable.toString();
2690        if (doNotAppend && !TextUtils.isEmpty(previous)) {
2691            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG).show();
2692            return;
2693        }
2694        if (UIHelper.isLastLineQuote(previous)) {
2695            text = '\n' + text;
2696        } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2697            text = " " + text;
2698        }
2699        this.binding.textinput.append(text);
2700    }
2701
2702    @Override
2703    public boolean onEnterPressed() {
2704        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2705        final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2706        if (enterIsSend) {
2707            sendMessage();
2708            return true;
2709        } else {
2710            return false;
2711        }
2712    }
2713
2714    @Override
2715    public void onTypingStarted() {
2716        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2717        if (service == null) {
2718            return;
2719        }
2720        Account.State status = conversation.getAccount().getStatus();
2721        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2722            service.sendChatState(conversation);
2723        }
2724        runOnUiThread(this::updateSendButton);
2725    }
2726
2727    @Override
2728    public void onTypingStopped() {
2729        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2730        if (service == null) {
2731            return;
2732        }
2733        Account.State status = conversation.getAccount().getStatus();
2734        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2735            service.sendChatState(conversation);
2736        }
2737    }
2738
2739    @Override
2740    public void onTextDeleted() {
2741        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2742        if (service == null) {
2743            return;
2744        }
2745        Account.State status = conversation.getAccount().getStatus();
2746        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2747            service.sendChatState(conversation);
2748        }
2749        if (storeNextMessage()) {
2750            runOnUiThread(() -> {
2751                if (activity == null) {
2752                    return;
2753                }
2754                activity.onConversationsListItemUpdated();
2755            });
2756        }
2757        runOnUiThread(this::updateSendButton);
2758    }
2759
2760    @Override
2761    public void onTextChanged() {
2762        if (conversation != null && conversation.getCorrectingMessage() != null) {
2763            runOnUiThread(this::updateSendButton);
2764        }
2765    }
2766
2767    @Override
2768    public boolean onTabPressed(boolean repeated) {
2769        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2770            return false;
2771        }
2772        if (repeated) {
2773            completionIndex++;
2774        } else {
2775            lastCompletionLength = 0;
2776            completionIndex = 0;
2777            final String content = this.binding.textinput.getText().toString();
2778            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2779            int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2780            firstWord = start == 0;
2781            incomplete = content.substring(start, lastCompletionCursor);
2782        }
2783        List<String> completions = new ArrayList<>();
2784        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2785            String name = user.getName();
2786            if (name != null && name.startsWith(incomplete)) {
2787                completions.add(name + (firstWord ? ": " : " "));
2788            }
2789        }
2790        Collections.sort(completions);
2791        if (completions.size() > completionIndex) {
2792            String completion = completions.get(completionIndex).substring(incomplete.length());
2793            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2794            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2795            lastCompletionLength = completion.length();
2796        } else {
2797            completionIndex = -1;
2798            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2799            lastCompletionLength = 0;
2800        }
2801        return true;
2802    }
2803
2804    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2805        try {
2806            getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2807        } catch (final SendIntentException ignored) {
2808        }
2809    }
2810
2811    @Override
2812    public void onBackendConnected() {
2813        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2814        String uuid = pendingConversationsUuid.pop();
2815        if (uuid != null) {
2816            if (!findAndReInitByUuidOrArchive(uuid)) {
2817                return;
2818            }
2819        } else {
2820            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2821                clearPending();
2822                activity.onConversationArchived(conversation);
2823                return;
2824            }
2825        }
2826        ActivityResult activityResult = postponedActivityResult.pop();
2827        if (activityResult != null) {
2828            handleActivityResult(activityResult);
2829        }
2830        clearPending();
2831    }
2832
2833    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2834        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2835        if (conversation == null) {
2836            clearPending();
2837            activity.onConversationArchived(null);
2838            return false;
2839        }
2840        reInit(conversation);
2841        ScrollState scrollState = pendingScrollState.pop();
2842        String lastMessageUuid = pendingLastMessageUuid.pop();
2843        List<Attachment> attachments = pendingMediaPreviews.pop();
2844        if (scrollState != null) {
2845            setScrollPosition(scrollState, lastMessageUuid);
2846        }
2847        if (attachments != null && attachments.size() > 0) {
2848            Log.d(Config.LOGTAG, "had attachments on restore");
2849            mediaPreviewAdapter.addMediaPreviews(attachments);
2850            toggleInputMethod();
2851        }
2852        return true;
2853    }
2854
2855    private void clearPending() {
2856        if (postponedActivityResult.clear()) {
2857            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2858        }
2859        if (pendingScrollState.clear()) {
2860            Log.e(Config.LOGTAG, "cleared scroll state");
2861        }
2862        if (pendingTakePhotoUri.clear()) {
2863            Log.e(Config.LOGTAG, "cleared pending photo uri");
2864        }
2865        if (pendingConversationsUuid.clear()) {
2866            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
2867        }
2868        if (pendingMediaPreviews.clear()) {
2869            Log.e(Config.LOGTAG, "cleared pending media previews");
2870        }
2871    }
2872
2873    public Conversation getConversation() {
2874        return conversation;
2875    }
2876
2877    @Override
2878    public void onContactPictureLongClicked(View v, final Message message) {
2879        final String fingerprint;
2880        if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2881            fingerprint = "pgp";
2882        } else {
2883            fingerprint = message.getFingerprint();
2884        }
2885        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
2886        final Contact contact = message.getContact();
2887        if (message.getStatus() <= Message.STATUS_RECEIVED && (contact == null || !contact.isSelf())) {
2888            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
2889                final Jid cp = message.getCounterpart();
2890                if (cp == null || cp.isBareJid()) {
2891                    return;
2892                }
2893                final Jid tcp = message.getTrueCounterpart();
2894                final User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp) : null;
2895                final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp);
2896                popupMenu.inflate(R.menu.muc_details_context);
2897                final Menu menu = popupMenu.getMenu();
2898                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user);
2899                popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, activity, fingerprint));
2900            } else {
2901                popupMenu.inflate(R.menu.one_on_one_context);
2902                popupMenu.setOnMenuItemClickListener(item -> {
2903                    switch (item.getItemId()) {
2904                        case R.id.action_contact_details:
2905                            activity.switchToContactDetails(message.getContact(), fingerprint);
2906                            break;
2907                        case R.id.action_show_qr_code:
2908                            activity.showQrCode("xmpp:" + message.getContact().getJid().asBareJid().toEscapedString());
2909                            break;
2910                    }
2911                    return true;
2912                });
2913            }
2914        } else {
2915            popupMenu.inflate(R.menu.account_context);
2916            final Menu menu = popupMenu.getMenu();
2917            menu.findItem(R.id.action_manage_accounts).setVisible(QuickConversationsService.isConversations());
2918            popupMenu.setOnMenuItemClickListener(item -> {
2919                switch (item.getItemId()) {
2920                    case R.id.action_show_qr_code:
2921                        activity.showQrCode(conversation.getAccount().getShareableUri());
2922                        break;
2923                    case R.id.action_account_details:
2924                        activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2925                        break;
2926                    case R.id.action_manage_accounts:
2927                        AccountUtils.launchManageAccounts(activity);
2928                        break;
2929                }
2930                return true;
2931            });
2932        }
2933        popupMenu.show();
2934    }
2935
2936    @Override
2937    public void onContactPictureClicked(Message message) {
2938        String fingerprint;
2939        if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2940            fingerprint = "pgp";
2941        } else {
2942            fingerprint = message.getFingerprint();
2943        }
2944        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
2945        if (received) {
2946            if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
2947                Jid tcp = message.getTrueCounterpart();
2948                Jid user = message.getCounterpart();
2949                if (user != null && !user.isBareJid()) {
2950                    final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions();
2951                    if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) {
2952                        if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) {
2953                            Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
2954                        }
2955                        highlightInConference(user.getResource());
2956                    } else {
2957                        Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
2958                    }
2959                }
2960                return;
2961            } else {
2962                if (!message.getContact().isSelf()) {
2963                    activity.switchToContactDetails(message.getContact(), fingerprint);
2964                    return;
2965                }
2966            }
2967        }
2968        activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2969    }
2970}