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