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