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