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