ConversationFragment.java

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