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