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.Context;
  20import android.content.DialogInterface;
  21import android.content.Intent;
  22import android.content.IntentSender.SendIntentException;
  23import android.os.Bundle;
  24import android.os.Handler;
  25import android.os.SystemClock;
  26import android.support.v13.view.inputmethod.InputConnectionCompat;
  27import android.support.v13.view.inputmethod.InputContentInfoCompat;
  28import android.text.Editable;
  29import android.util.Log;
  30import android.view.ContextMenu;
  31import android.view.ContextMenu.ContextMenuInfo;
  32import android.view.Gravity;
  33import android.view.LayoutInflater;
  34import android.view.Menu;
  35import android.view.MenuInflater;
  36import android.view.MenuItem;
  37import android.view.MotionEvent;
  38import android.view.View;
  39import android.view.View.OnClickListener;
  40import android.view.ViewGroup;
  41import android.view.inputmethod.EditorInfo;
  42import android.view.inputmethod.InputMethodManager;
  43import android.widget.AbsListView;
  44import android.widget.AbsListView.OnScrollListener;
  45import android.widget.AdapterView;
  46import android.widget.AdapterView.AdapterContextMenuInfo;
  47import android.widget.CheckBox;
  48import android.widget.ListView;
  49import android.widget.PopupMenu;
  50import android.widget.TextView.OnEditorActionListener;
  51import android.widget.Toast;
  52
  53import java.util.ArrayList;
  54import java.util.Arrays;
  55import java.util.Collections;
  56import java.util.HashSet;
  57import java.util.Iterator;
  58import java.util.List;
  59import java.util.Set;
  60import java.util.UUID;
  61import java.util.concurrent.atomic.AtomicBoolean;
  62
  63import eu.siacs.conversations.Config;
  64import eu.siacs.conversations.R;
  65import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  66import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  67import eu.siacs.conversations.databinding.FragmentConversationBinding;
  68import eu.siacs.conversations.entities.Account;
  69import eu.siacs.conversations.entities.Blockable;
  70import eu.siacs.conversations.entities.Contact;
  71import eu.siacs.conversations.entities.Conversation;
  72import eu.siacs.conversations.entities.DownloadableFile;
  73import eu.siacs.conversations.entities.Message;
  74import eu.siacs.conversations.entities.MucOptions;
  75import eu.siacs.conversations.entities.Presence;
  76import eu.siacs.conversations.entities.ReadByMarker;
  77import eu.siacs.conversations.entities.Transferable;
  78import eu.siacs.conversations.entities.TransferablePlaceholder;
  79import eu.siacs.conversations.http.HttpDownloadConnection;
  80import eu.siacs.conversations.persistance.FileBackend;
  81import eu.siacs.conversations.services.MessageArchiveService;
  82import eu.siacs.conversations.services.XmppConnectionService;
  83import eu.siacs.conversations.ui.adapter.MessageAdapter;
  84import eu.siacs.conversations.ui.util.ActivityResult;
  85import eu.siacs.conversations.ui.util.AttachmentTool;
  86import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
  87import eu.siacs.conversations.ui.util.DateSeparator;
  88import eu.siacs.conversations.ui.util.ListViewUtils;
  89import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  90import eu.siacs.conversations.ui.util.PendingItem;
  91import eu.siacs.conversations.ui.util.PresenceSelector;
  92import eu.siacs.conversations.ui.util.ScrollState;
  93import eu.siacs.conversations.ui.util.SendButtonAction;
  94import eu.siacs.conversations.ui.util.SendButtonTool;
  95import eu.siacs.conversations.ui.util.ShareUtil;
  96import eu.siacs.conversations.ui.widget.EditMessage;
  97import eu.siacs.conversations.utils.GeoHelper;
  98import eu.siacs.conversations.utils.MessageUtils;
  99import eu.siacs.conversations.utils.NickValidityChecker;
 100import eu.siacs.conversations.utils.Patterns;
 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				attachEditorContentToConversation(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 attachEditorContentToConversation(Uri uri) {
 652		this.attachFileToConversation(conversation, uri, null);
 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				final 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				final 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				final String type = data == null ? null : 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 copyLink = menu.findItem(R.id.copy_link);
1056			MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1057			MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1058			MenuItem correctMessage = menu.findItem(R.id.correct_message);
1059			MenuItem shareWith = menu.findItem(R.id.share_with);
1060			MenuItem sendAgain = menu.findItem(R.id.send_again);
1061			MenuItem copyUrl = menu.findItem(R.id.copy_url);
1062			MenuItem downloadFile = menu.findItem(R.id.download_file);
1063			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1064			MenuItem deleteFile = menu.findItem(R.id.delete_file);
1065			MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1066			if (!m.isFileOrImage() && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1067				copyMessage.setVisible(true);
1068				quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
1069				String body = m.getMergedBody().toString();
1070				if (ShareUtil.containsXmppUri(body)) {
1071					copyLink.setTitle(R.string.copy_jabber_id);
1072					copyLink.setVisible(true);
1073				} else if (Patterns.AUTOLINK_WEB_URL.matcher(body).find()) {
1074					copyLink.setVisible(true);
1075				}
1076			}
1077			if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1078				retryDecryption.setVisible(true);
1079			}
1080			if (relevantForCorrection.getType() == Message.TYPE_TEXT
1081					&& relevantForCorrection.isLastCorrectableMessage()
1082					&& m.getConversation() instanceof Conversation
1083					&& (((Conversation) m.getConversation()).getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
1084				correctMessage.setVisible(true);
1085			}
1086			if ((m.isFileOrImage() && !deleted && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1087				shareWith.setVisible(true);
1088			}
1089			if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1090				sendAgain.setVisible(true);
1091			}
1092			if (m.hasFileOnRemoteHost()
1093					|| m.isGeoUri()
1094					|| m.treatAsDownloadable()
1095					|| (t != null && t instanceof HttpDownloadConnection)) {
1096				copyUrl.setVisible(true);
1097			}
1098			if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1099				downloadFile.setVisible(true);
1100				downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1101			}
1102			boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1103					|| m.getStatus() == Message.STATUS_UNSEND
1104					|| m.getStatus() == Message.STATUS_OFFERED;
1105			if ((t != null && !deleted) || waitingOfferedSending && m.needsUploading()) {
1106				cancelTransmission.setVisible(true);
1107			}
1108			if (m.isFileOrImage() && !deleted) {
1109				String path = m.getRelativeFilePath();
1110				if (path == null || !path.startsWith("/") || FileBackend.isInDirectoryThatShouldNotBeScanned(getActivity(), path) ) {
1111					deleteFile.setVisible(true);
1112					deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1113				}
1114			}
1115			if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
1116				showErrorMessage.setVisible(true);
1117			}
1118		}
1119	}
1120
1121	@Override
1122	public boolean onContextItemSelected(MenuItem item) {
1123		switch (item.getItemId()) {
1124			case R.id.share_with:
1125				ShareUtil.share(activity, selectedMessage);
1126				return true;
1127			case R.id.correct_message:
1128				correctMessage(selectedMessage);
1129				return true;
1130			case R.id.copy_message:
1131				ShareUtil.copyToClipboard(activity, selectedMessage);
1132				return true;
1133			case R.id.copy_link:
1134				ShareUtil.copyLinkToClipboard(activity, selectedMessage);
1135				return true;
1136			case R.id.quote_message:
1137				quoteMessage(selectedMessage);
1138				return true;
1139			case R.id.send_again:
1140				resendMessage(selectedMessage);
1141				return true;
1142			case R.id.copy_url:
1143				ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1144				return true;
1145			case R.id.download_file:
1146				startDownloadable(selectedMessage);
1147				return true;
1148			case R.id.cancel_transmission:
1149				cancelTransmission(selectedMessage);
1150				return true;
1151			case R.id.retry_decryption:
1152				retryDecryption(selectedMessage);
1153				return true;
1154			case R.id.delete_file:
1155				deleteFile(selectedMessage);
1156				return true;
1157			case R.id.show_error_message:
1158				showErrorMessage(selectedMessage);
1159				return true;
1160			default:
1161				return super.onContextItemSelected(item);
1162		}
1163	}
1164
1165	@Override
1166	public boolean onOptionsItemSelected(final MenuItem item) {
1167		if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1168			return false;
1169		} else if (conversation == null) {
1170			return super.onOptionsItemSelected(item);
1171		}
1172		switch (item.getItemId()) {
1173			case R.id.encryption_choice_axolotl:
1174			case R.id.encryption_choice_pgp:
1175			case R.id.encryption_choice_none:
1176				handleEncryptionSelection(item);
1177				break;
1178			case R.id.attach_choose_picture:
1179			case R.id.attach_take_picture:
1180			case R.id.attach_record_video:
1181			case R.id.attach_choose_file:
1182			case R.id.attach_record_voice:
1183			case R.id.attach_location:
1184				handleAttachmentSelection(item);
1185				break;
1186			case R.id.action_archive:
1187				activity.xmppConnectionService.archiveConversation(conversation);
1188				break;
1189			case R.id.action_contact_details:
1190				activity.switchToContactDetails(conversation.getContact());
1191				break;
1192			case R.id.action_muc_details:
1193				Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1194				intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1195				intent.putExtra("uuid", conversation.getUuid());
1196				startActivity(intent);
1197				break;
1198			case R.id.action_invite:
1199				startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1200				break;
1201			case R.id.action_clear_history:
1202				clearHistoryDialog(conversation);
1203				break;
1204			case R.id.action_mute:
1205				muteConversationDialog(conversation);
1206				break;
1207			case R.id.action_unmute:
1208				unmuteConversation(conversation);
1209				break;
1210			case R.id.action_block:
1211			case R.id.action_unblock:
1212				final Activity activity = getActivity();
1213				if (activity instanceof XmppActivity) {
1214					BlockContactDialog.show((XmppActivity) activity, conversation);
1215				}
1216				break;
1217			default:
1218				break;
1219		}
1220		return super.onOptionsItemSelected(item);
1221	}
1222
1223	private void handleAttachmentSelection(MenuItem item) {
1224		switch (item.getItemId()) {
1225			case R.id.attach_choose_picture:
1226				attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1227				break;
1228			case R.id.attach_take_picture:
1229				attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1230				break;
1231			case R.id.attach_record_video:
1232				attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1233				break;
1234			case R.id.attach_choose_file:
1235				attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1236				break;
1237			case R.id.attach_record_voice:
1238				attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1239				break;
1240			case R.id.attach_location:
1241				attachFile(ATTACHMENT_CHOICE_LOCATION);
1242				break;
1243		}
1244	}
1245
1246	private void handleEncryptionSelection(MenuItem item) {
1247		if (conversation == null) {
1248			return;
1249		}
1250		switch (item.getItemId()) {
1251			case R.id.encryption_choice_none:
1252				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1253				item.setChecked(true);
1254				break;
1255			case R.id.encryption_choice_pgp:
1256				if (activity.hasPgp()) {
1257					if (conversation.getAccount().getPgpSignature() != null) {
1258						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1259						item.setChecked(true);
1260					} else {
1261						activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1262					}
1263				} else {
1264					activity.showInstallPgpDialog();
1265				}
1266				break;
1267			case R.id.encryption_choice_axolotl:
1268				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1269						+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
1270				conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1271				item.setChecked(true);
1272				break;
1273			default:
1274				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1275				break;
1276		}
1277		activity.xmppConnectionService.updateConversation(conversation);
1278		updateChatMsgHint();
1279		getActivity().invalidateOptionsMenu();
1280		activity.refreshUi();
1281	}
1282
1283	public void attachFile(final int attachmentChoice) {
1284		if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1285			if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) {
1286				return;
1287			}
1288		} else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1289			if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
1290				return;
1291			}
1292		} else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1293			if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1294				return;
1295			}
1296		}
1297		try {
1298			activity.getPreferences().edit()
1299					.putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1300					.apply();
1301		} catch (IllegalArgumentException e) {
1302			//just do not save
1303		}
1304		final int encryption = conversation.getNextEncryption();
1305		final int mode = conversation.getMode();
1306		if (encryption == Message.ENCRYPTION_PGP) {
1307			if (activity.hasPgp()) {
1308				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1309					activity.xmppConnectionService.getPgpEngine().hasKey(
1310							conversation.getContact(),
1311							new UiCallback<Contact>() {
1312
1313								@Override
1314								public void userInputRequried(PendingIntent pi, Contact contact) {
1315									startPendingIntent(pi, attachmentChoice);
1316								}
1317
1318								@Override
1319								public void success(Contact contact) {
1320									selectPresenceToAttachFile(attachmentChoice);
1321								}
1322
1323								@Override
1324								public void error(int error, Contact contact) {
1325									activity.replaceToast(getString(error));
1326								}
1327							});
1328				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1329					if (!conversation.getMucOptions().everybodyHasKeys()) {
1330						Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1331						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1332						warning.show();
1333					}
1334					selectPresenceToAttachFile(attachmentChoice);
1335				} else {
1336					showNoPGPKeyDialog(false, (dialog, which) -> {
1337						conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1338						activity.xmppConnectionService.updateConversation(conversation);
1339						selectPresenceToAttachFile(attachmentChoice);
1340					});
1341				}
1342			} else {
1343				activity.showInstallPgpDialog();
1344			}
1345		} else {
1346			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1347				selectPresenceToAttachFile(attachmentChoice);
1348			}
1349		}
1350	}
1351
1352	@Override
1353	public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
1354		if (grantResults.length > 0)
1355			if (allGranted(grantResults)) {
1356				if (requestCode == REQUEST_START_DOWNLOAD) {
1357					if (this.mPendingDownloadableMessage != null) {
1358						startDownloadable(this.mPendingDownloadableMessage);
1359					}
1360				} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1361					if (this.mPendingEditorContent != null) {
1362						attachEditorContentToConversation(this.mPendingEditorContent);
1363					}
1364				} else {
1365					attachFile(requestCode);
1366				}
1367			} else {
1368				@StringRes int res;
1369				String firstDenied = getFirstDenied(grantResults, permissions);
1370				if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1371					res = R.string.no_microphone_permission;
1372				} else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1373					res = R.string.no_camera_permission;
1374				} else {
1375					res = R.string.no_storage_permission;
1376				}
1377				Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1378			}
1379	}
1380
1381	public void startDownloadable(Message message) {
1382		if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1383			this.mPendingDownloadableMessage = message;
1384			return;
1385		}
1386		Transferable transferable = message.getTransferable();
1387		if (transferable != null) {
1388			if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1389				createNewConnection(message);
1390				return;
1391			}
1392			if (!transferable.start()) {
1393				Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1394				Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1395			}
1396		} else if (message.treatAsDownloadable()) {
1397			createNewConnection(message);
1398		}
1399	}
1400
1401	private void createNewConnection(final Message message) {
1402		if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) {
1403			Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1404			return;
1405		}
1406		activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1407	}
1408
1409	@SuppressLint("InflateParams")
1410	protected void clearHistoryDialog(final Conversation conversation) {
1411		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1412		builder.setTitle(getString(R.string.clear_conversation_history));
1413		final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1414		final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1415		builder.setView(dialogView);
1416		builder.setNegativeButton(getString(R.string.cancel), null);
1417		builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1418			this.activity.xmppConnectionService.clearConversationHistory(conversation);
1419			if (endConversationCheckBox.isChecked()) {
1420				this.activity.xmppConnectionService.archiveConversation(conversation);
1421				this.activity.onConversationArchived(conversation);
1422			} else {
1423				activity.onConversationsListItemUpdated();
1424				refresh();
1425			}
1426		});
1427		builder.create().show();
1428	}
1429
1430	protected void muteConversationDialog(final Conversation conversation) {
1431		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1432		builder.setTitle(R.string.disable_notifications);
1433		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1434		final CharSequence[] labels = new CharSequence[durations.length];
1435		for (int i = 0; i < durations.length; ++i) {
1436			if (durations[i] == -1) {
1437				labels[i] = getString(R.string.until_further_notice);
1438			} else {
1439				labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1440			}
1441		}
1442		builder.setItems(labels, (dialog, which) -> {
1443			final long till;
1444			if (durations[which] == -1) {
1445				till = Long.MAX_VALUE;
1446			} else {
1447				till = System.currentTimeMillis() + (durations[which] * 1000);
1448			}
1449			conversation.setMutedTill(till);
1450			activity.xmppConnectionService.updateConversation(conversation);
1451			activity.onConversationsListItemUpdated();
1452			refresh();
1453			getActivity().invalidateOptionsMenu();
1454		});
1455		builder.create().show();
1456	}
1457
1458	private boolean hasPermissions(int requestCode, String... permissions) {
1459		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1460			final List<String> missingPermissions = new ArrayList<>();
1461			for(String permission : permissions) {
1462				if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1463					continue;
1464				}
1465				if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
1466					missingPermissions.add(permission);
1467				}
1468			}
1469			if (missingPermissions.size() == 0) {
1470				return true;
1471			} else {
1472				requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1473				return false;
1474			}
1475		} else {
1476			return true;
1477		}
1478	}
1479
1480	public void unmuteConversation(final Conversation conversation) {
1481		conversation.setMutedTill(0);
1482		this.activity.xmppConnectionService.updateConversation(conversation);
1483		this.activity.onConversationsListItemUpdated();
1484		refresh();
1485		getActivity().invalidateOptionsMenu();
1486	}
1487
1488	protected void selectPresenceToAttachFile(final int attachmentChoice) {
1489		final Account account = conversation.getAccount();
1490		final PresenceSelector.OnPresenceSelected callback = () -> {
1491			Intent intent = new Intent();
1492			boolean chooser = false;
1493			switch (attachmentChoice) {
1494				case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1495					intent.setAction(Intent.ACTION_GET_CONTENT);
1496					intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1497					intent.setType("image/*");
1498					chooser = true;
1499					break;
1500				case ATTACHMENT_CHOICE_RECORD_VIDEO:
1501					intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1502					break;
1503				case ATTACHMENT_CHOICE_TAKE_PHOTO:
1504					final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1505					pendingTakePhotoUri.push(uri);
1506					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1507					intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1508					intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1509					intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1510					break;
1511				case ATTACHMENT_CHOICE_CHOOSE_FILE:
1512					chooser = true;
1513					intent.setType("*/*");
1514					intent.addCategory(Intent.CATEGORY_OPENABLE);
1515					intent.setAction(Intent.ACTION_GET_CONTENT);
1516					break;
1517				case ATTACHMENT_CHOICE_RECORD_VOICE:
1518					intent = new Intent(getActivity(), RecordingActivity.class);
1519					break;
1520				case ATTACHMENT_CHOICE_LOCATION:
1521					intent = GeoHelper.getFetchIntent(activity);
1522					break;
1523			}
1524			if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1525				if (chooser) {
1526					startActivityForResult(
1527							Intent.createChooser(intent, getString(R.string.perform_action_with)),
1528							attachmentChoice);
1529				} else {
1530					startActivityForResult(intent, attachmentChoice);
1531				}
1532			}
1533		};
1534		if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1535			conversation.setNextCounterpart(null);
1536			callback.onPresenceSelected();
1537		} else {
1538			activity.selectPresence(conversation, callback);
1539		}
1540	}
1541
1542	@Override
1543	public void onResume() {
1544		super.onResume();
1545		binding.messagesView.post(this::fireReadEvent);
1546	}
1547
1548	private void fireReadEvent() {
1549		if (activity != null && this.conversation != null) {
1550			String uuid = getLastVisibleMessageUuid();
1551			if (uuid != null) {
1552				activity.onConversationRead(this.conversation, uuid);
1553			}
1554		}
1555	}
1556
1557	private String getLastVisibleMessageUuid() {
1558		if (binding == null) {
1559			return null;
1560		}
1561		synchronized (this.messageList) {
1562			int pos = binding.messagesView.getLastVisiblePosition();
1563			if (pos >= 0) {
1564				Message message = null;
1565				for (int i = pos; i >= 0; --i) {
1566					try {
1567						message = (Message) binding.messagesView.getItemAtPosition(i);
1568					} catch (IndexOutOfBoundsException e) {
1569						//should not happen if we synchronize properly. however if that fails we just gonna try item -1
1570						continue;
1571					}
1572					if (message.getType() != Message.TYPE_STATUS) {
1573						break;
1574					}
1575				}
1576				if (message != null) {
1577					while (message.next() != null && message.next().wasMergedIntoPrevious()) {
1578						message = message.next();
1579					}
1580					return message.getUuid();
1581				}
1582			}
1583		}
1584		return null;
1585	}
1586
1587	private void showErrorMessage(final Message message) {
1588		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1589		builder.setTitle(R.string.error_message);
1590		builder.setMessage(message.getErrorMessage());
1591		builder.setPositiveButton(R.string.confirm, null);
1592		builder.create().show();
1593	}
1594
1595
1596	private void deleteFile(Message message) {
1597		if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1598			message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1599			activity.onConversationsListItemUpdated();
1600			refresh();
1601		}
1602	}
1603
1604	private void resendMessage(final Message message) {
1605		if (message.isFileOrImage()) {
1606			if (!(message.getConversation() instanceof Conversation)) {
1607				return;
1608			}
1609			final Conversation conversation = (Conversation) message.getConversation();
1610			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1611			if (file.exists()) {
1612				final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1613				if (!message.hasFileOnRemoteHost()
1614						&& xmppConnection != null
1615						&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1616					activity.selectPresence(conversation, () -> {
1617						message.setCounterpart(conversation.getNextCounterpart());
1618						activity.xmppConnectionService.resendFailedMessages(message);
1619						new Handler().post(() -> {
1620							int size = messageList.size();
1621							this.binding.messagesView.setSelection(size - 1);
1622						});
1623					});
1624					return;
1625				}
1626			} else {
1627				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1628				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1629				activity.onConversationsListItemUpdated();
1630				refresh();
1631				return;
1632			}
1633		}
1634		activity.xmppConnectionService.resendFailedMessages(message);
1635		new Handler().post(() -> {
1636			int size = messageList.size();
1637			this.binding.messagesView.setSelection(size - 1);
1638		});
1639	}
1640
1641	private void cancelTransmission(Message message) {
1642		Transferable transferable = message.getTransferable();
1643		if (transferable != null) {
1644			transferable.cancel();
1645		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
1646			activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1647		}
1648	}
1649
1650	private void retryDecryption(Message message) {
1651		message.setEncryption(Message.ENCRYPTION_PGP);
1652		activity.onConversationsListItemUpdated();
1653		refresh();
1654		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1655	}
1656
1657	private void privateMessageWith(final Jid counterpart) {
1658		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1659			activity.xmppConnectionService.sendChatState(conversation);
1660		}
1661		this.binding.textinput.setText("");
1662		this.conversation.setNextCounterpart(counterpart);
1663		updateChatMsgHint();
1664		updateSendButton();
1665		updateEditablity();
1666	}
1667
1668	private void correctMessage(Message message) {
1669		while (message.mergeable(message.next())) {
1670			message = message.next();
1671		}
1672		this.conversation.setCorrectingMessage(message);
1673		final Editable editable = binding.textinput.getText();
1674		this.conversation.setDraftMessage(editable.toString());
1675		this.binding.textinput.setText("");
1676		this.binding.textinput.append(message.getBody());
1677
1678	}
1679
1680	private void highlightInConference(String nick) {
1681		final Editable editable = this.binding.textinput.getText();
1682		String oldString = editable.toString().trim();
1683		final int pos = this.binding.textinput.getSelectionStart();
1684		if (oldString.isEmpty() || pos == 0) {
1685			editable.insert(0, nick + ": ");
1686		} else {
1687			final char before = editable.charAt(pos - 1);
1688			final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1689			if (before == '\n') {
1690				editable.insert(pos, nick + ": ");
1691			} else {
1692				if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1693					if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1694						editable.insert(pos - 2, ", " + nick);
1695						return;
1696					}
1697				}
1698				editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1699				if (Character.isWhitespace(after)) {
1700					this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1701				}
1702			}
1703		}
1704	}
1705
1706	@Override
1707	public void onSaveInstanceState(Bundle outState) {
1708		super.onSaveInstanceState(outState);
1709		if (conversation != null) {
1710			outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1711			outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1712			final Uri uri = pendingTakePhotoUri.peek();
1713			if (uri != null) {
1714				outState.putString(STATE_PHOTO_URI, uri.toString());
1715			}
1716			final ScrollState scrollState = getScrollPosition();
1717			if (scrollState != null) {
1718				outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1719			}
1720		}
1721	}
1722
1723	@Override
1724	public void onActivityCreated(Bundle savedInstanceState) {
1725		super.onActivityCreated(savedInstanceState);
1726		if (savedInstanceState == null) {
1727			return;
1728		}
1729		String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1730		pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1731		if (uuid != null) {
1732			QuickLoader.set(uuid);
1733			this.pendingConversationsUuid.push(uuid);
1734			String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1735			if (takePhotoUri != null) {
1736				pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1737			}
1738			pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1739		}
1740	}
1741
1742	@Override
1743	public void onStart() {
1744		super.onStart();
1745		if (this.reInitRequiredOnStart && this.conversation != null) {
1746			final Bundle extras = pendingExtras.pop();
1747			reInit(this.conversation, extras != null);
1748			if (extras != null) {
1749				processExtras(extras);
1750			}
1751		} else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1752			final String uuid = pendingConversationsUuid.pop();
1753			Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1754			if (uuid != null) {
1755				findAndReInitByUuidOrArchive(uuid);
1756			}
1757		}
1758	}
1759
1760	@Override
1761	public void onStop() {
1762		super.onStop();
1763		final Activity activity = getActivity();
1764		if (activity == null || !activity.isChangingConfigurations()) {
1765			hideSoftKeyboard(activity);
1766			messageListAdapter.stopAudioPlayer();
1767		}
1768		if (this.conversation != null) {
1769			final String msg = this.binding.textinput.getText().toString();
1770			if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && this.conversation.setNextMessage(msg)) {
1771				this.activity.xmppConnectionService.updateConversation(this.conversation);
1772			}
1773			updateChatState(this.conversation, msg);
1774			this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1775		}
1776		this.reInitRequiredOnStart = true;
1777	}
1778
1779	private void updateChatState(final Conversation conversation, final String msg) {
1780		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1781		Account.State status = conversation.getAccount().getStatus();
1782		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1783			activity.xmppConnectionService.sendChatState(conversation);
1784		}
1785	}
1786
1787	private void saveMessageDraftStopAudioPlayer() {
1788		final Conversation previousConversation = this.conversation;
1789		if (this.activity == null || this.binding == null || previousConversation == null) {
1790			return;
1791		}
1792		Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1793		final String msg = this.binding.textinput.getText().toString();
1794		if (previousConversation.setNextMessage(msg)) {
1795			activity.xmppConnectionService.updateConversation(previousConversation);
1796		}
1797		updateChatState(this.conversation, msg);
1798		messageListAdapter.stopAudioPlayer();
1799	}
1800
1801	public void reInit(Conversation conversation, Bundle extras) {
1802		QuickLoader.set(conversation.getUuid());
1803		this.saveMessageDraftStopAudioPlayer();
1804		if (this.reInit(conversation, extras != null)) {
1805			if (extras != null) {
1806				processExtras(extras);
1807			}
1808			this.reInitRequiredOnStart = false;
1809		} else {
1810			this.reInitRequiredOnStart = true;
1811			pendingExtras.push(extras);
1812		}
1813		resetUnreadMessagesCount();
1814	}
1815
1816	private void reInit(Conversation conversation) {
1817		reInit(conversation, false);
1818	}
1819
1820	private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1821		if (conversation == null) {
1822			return false;
1823		}
1824		this.conversation = conversation;
1825		//once we set the conversation all is good and it will automatically do the right thing in onStart()
1826		if (this.activity == null || this.binding == null) {
1827			return false;
1828		}
1829
1830		if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1831			activity.onConversationArchived(this.conversation);
1832			return false;
1833		}
1834
1835		stopScrolling();
1836		Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1837
1838		if (this.conversation.isRead() && hasExtras) {
1839			Log.d(Config.LOGTAG, "trimming conversation");
1840			this.conversation.trim();
1841		}
1842
1843		setupIme();
1844
1845		final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1846
1847		this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1848		this.binding.textinput.setKeyboardListener(null);
1849		this.binding.textinput.setText("");
1850		this.binding.textinput.append(this.conversation.getNextMessage());
1851		this.binding.textinput.setKeyboardListener(this);
1852		messageListAdapter.updatePreferences();
1853		refresh(false);
1854		this.conversation.messagesLoaded.set(true);
1855		Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1856
1857		if (hasExtras || scrolledToBottomAndNoPending) {
1858			resetUnreadMessagesCount();
1859			synchronized (this.messageList) {
1860				Log.d(Config.LOGTAG, "jump to first unread message");
1861				final Message first = conversation.getFirstUnreadMessage();
1862				final int bottom = Math.max(0, this.messageList.size() - 1);
1863				final int pos;
1864				final boolean jumpToBottom;
1865				if (first == null) {
1866					pos = bottom;
1867					jumpToBottom = true;
1868				} else {
1869					int i = getIndexOf(first.getUuid(), this.messageList);
1870					pos = i < 0 ? bottom : i;
1871					jumpToBottom = false;
1872				}
1873				setSelection(pos, jumpToBottom);
1874			}
1875		}
1876
1877
1878		this.binding.messagesView.post(this::fireReadEvent);
1879		//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
1880		activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1881		return true;
1882	}
1883
1884	private void resetUnreadMessagesCount() {
1885		lastMessageUuid = null;
1886		hideUnreadMessagesCount();
1887	}
1888
1889	private void hideUnreadMessagesCount() {
1890		if (this.binding == null) {
1891			return;
1892		}
1893		this.binding.scrollToBottomButton.setEnabled(false);
1894		this.binding.scrollToBottomButton.setVisibility(View.GONE);
1895		this.binding.unreadCountCustomView.setVisibility(View.GONE);
1896	}
1897
1898	private void setSelection(int pos, boolean jumpToBottom) {
1899		ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
1900		this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
1901		this.binding.messagesView.post(this::fireReadEvent);
1902	}
1903
1904
1905	private boolean scrolledToBottom() {
1906		return this.binding != null && scrolledToBottom(this.binding.messagesView);
1907	}
1908
1909	private void processExtras(Bundle extras) {
1910		final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1911		final String text = extras.getString(ConversationsActivity.EXTRA_TEXT);
1912		final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
1913		final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
1914		final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1915		if (nick != null) {
1916			if (pm) {
1917				Jid jid = conversation.getJid();
1918				try {
1919					Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
1920					privateMessageWith(next);
1921				} catch (final IllegalArgumentException ignored) {
1922					//do nothing
1923				}
1924			} else {
1925				final MucOptions mucOptions = conversation.getMucOptions();
1926				if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
1927					highlightInConference(nick);
1928				}
1929			}
1930		} else {
1931			if (text != null && asQuote) {
1932				quoteText(text);
1933			} else {
1934				appendText(text);
1935			}
1936		}
1937		final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
1938		if (message != null) {
1939			startDownloadable(message);
1940		}
1941	}
1942
1943	private boolean showBlockSubmenu(View view) {
1944		final Jid jid = conversation.getJid();
1945		if (jid.getLocal() == null) {
1946			BlockContactDialog.show(activity, conversation);
1947		} else {
1948			PopupMenu popupMenu = new PopupMenu(getActivity(), view);
1949			popupMenu.inflate(R.menu.block);
1950			popupMenu.setOnMenuItemClickListener(menuItem -> {
1951				Blockable blockable;
1952				switch (menuItem.getItemId()) {
1953					case R.id.block_domain:
1954						blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
1955						break;
1956					default:
1957						blockable = conversation;
1958				}
1959				BlockContactDialog.show(activity, blockable);
1960				return true;
1961			});
1962			popupMenu.show();
1963		}
1964		return true;
1965	}
1966
1967	private void updateSnackBar(final Conversation conversation) {
1968		final Account account = conversation.getAccount();
1969		final XmppConnection connection = account.getXmppConnection();
1970		final int mode = conversation.getMode();
1971		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1972		if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
1973			return;
1974		}
1975		if (account.getStatus() == Account.State.DISABLED) {
1976			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1977		} else if (conversation.isBlocked()) {
1978			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1979		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1980			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1981		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1982			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1983		} else if (mode == Conversation.MODE_MULTI
1984				&& !conversation.getMucOptions().online()
1985				&& account.getStatus() == Account.State.ONLINE) {
1986			switch (conversation.getMucOptions().getError()) {
1987				case NICK_IN_USE:
1988					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1989					break;
1990				case NO_RESPONSE:
1991					showSnackbar(R.string.joining_conference, 0, null);
1992					break;
1993				case SERVER_NOT_FOUND:
1994					if (conversation.receivedMessagesCount() > 0) {
1995						showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
1996					} else {
1997						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1998					}
1999					break;
2000				case PASSWORD_REQUIRED:
2001					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2002					break;
2003				case BANNED:
2004					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2005					break;
2006				case MEMBERS_ONLY:
2007					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2008					break;
2009				case KICKED:
2010					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2011					break;
2012				case UNKNOWN:
2013					showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2014					break;
2015				case INVALID_NICK:
2016					showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2017				case SHUTDOWN:
2018					showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2019					break;
2020				default:
2021					hideSnackbar();
2022					break;
2023			}
2024		} else if (account.hasPendingPgpIntent(conversation)) {
2025			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2026		} else if (connection != null
2027				&& connection.getFeatures().blocking()
2028				&& conversation.countMessages() != 0
2029				&& !conversation.isBlocked()
2030				&& conversation.isWithStranger()) {
2031			showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2032		} else {
2033			hideSnackbar();
2034		}
2035	}
2036
2037	@Override
2038	public void refresh() {
2039		if (this.binding == null) {
2040			Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2041			return;
2042		}
2043		if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2044			if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2045				activity.onConversationArchived(this.conversation);
2046				return;
2047			}
2048		}
2049		this.refresh(true);
2050	}
2051
2052	private void refresh(boolean notifyConversationRead) {
2053		synchronized (this.messageList) {
2054			if (this.conversation != null) {
2055				conversation.populateWithMessages(this.messageList);
2056				updateSnackBar(conversation);
2057				updateStatusMessages();
2058				if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2059					binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2060					binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2061				}
2062				this.messageListAdapter.notifyDataSetChanged();
2063				updateChatMsgHint();
2064				if (notifyConversationRead && activity != null) {
2065					binding.messagesView.post(this::fireReadEvent);
2066				}
2067				updateSendButton();
2068				updateEditablity();
2069			}
2070		}
2071	}
2072
2073	protected void messageSent() {
2074		mSendingPgpMessage.set(false);
2075		this.binding.textinput.setText("");
2076		if (conversation.setCorrectingMessage(null)) {
2077			this.binding.textinput.append(conversation.getDraftMessage());
2078			conversation.setDraftMessage(null);
2079		}
2080		if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
2081			activity.xmppConnectionService.updateConversation(conversation);
2082		}
2083		updateChatMsgHint();
2084		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2085		final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2086		if (prefScrollToBottom || scrolledToBottom()) {
2087			new Handler().post(() -> {
2088				int size = messageList.size();
2089				this.binding.messagesView.setSelection(size - 1);
2090			});
2091		}
2092	}
2093
2094	public void doneSendingPgpMessage() {
2095		mSendingPgpMessage.set(false);
2096	}
2097
2098	public long getMaxHttpUploadSize(Conversation conversation) {
2099		final XmppConnection connection = conversation.getAccount().getXmppConnection();
2100		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2101	}
2102
2103	private void updateEditablity() {
2104		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2105		this.binding.textinput.setFocusable(canWrite);
2106		this.binding.textinput.setFocusableInTouchMode(canWrite);
2107		this.binding.textSendButton.setEnabled(canWrite);
2108		this.binding.textinput.setCursorVisible(canWrite);
2109	}
2110
2111	public void updateSendButton() {
2112		boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2113		final Conversation c = this.conversation;
2114		final Presence.Status status;
2115		final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2116		final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
2117		if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2118			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2119				status = Presence.Status.OFFLINE;
2120			} else if (c.getMode() == Conversation.MODE_SINGLE) {
2121				status = c.getContact().getShownStatus();
2122			} else {
2123				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2124			}
2125		} else {
2126			status = Presence.Status.OFFLINE;
2127		}
2128		this.binding.textSendButton.setTag(action);
2129		this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2130	}
2131
2132	protected void updateDateSeparators() {
2133		synchronized (this.messageList) {
2134			DateSeparator.addAll(this.messageList);
2135		}
2136	}
2137
2138	protected void updateStatusMessages() {
2139		updateDateSeparators();
2140		synchronized (this.messageList) {
2141			if (showLoadMoreMessages(conversation)) {
2142				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2143			}
2144			if (conversation.getMode() == Conversation.MODE_SINGLE) {
2145				ChatState state = conversation.getIncomingChatState();
2146				if (state == ChatState.COMPOSING) {
2147					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2148				} else if (state == ChatState.PAUSED) {
2149					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2150				} else {
2151					for (int i = this.messageList.size() - 1; i >= 0; --i) {
2152						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
2153							return;
2154						} else {
2155							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
2156								this.messageList.add(i + 1,
2157										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2158								return;
2159							}
2160						}
2161					}
2162				}
2163			} else {
2164				final MucOptions mucOptions = conversation.getMucOptions();
2165				final List<MucOptions.User> allUsers = mucOptions.getUsers();
2166				final Set<ReadByMarker> addedMarkers = new HashSet<>();
2167				ChatState state = ChatState.COMPOSING;
2168				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2169				if (users.size() == 0) {
2170					state = ChatState.PAUSED;
2171					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2172				}
2173				if (mucOptions.isPrivateAndNonAnonymous()) {
2174					for (int i = this.messageList.size() - 1; i >= 0; --i) {
2175						final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2176						final List<MucOptions.User> shownMarkers = new ArrayList<>();
2177						for (ReadByMarker marker : markersForMessage) {
2178							if (!ReadByMarker.contains(marker, addedMarkers)) {
2179								addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2180								MucOptions.User user = mucOptions.findUser(marker);
2181								if (user != null && !users.contains(user)) {
2182									shownMarkers.add(user);
2183								}
2184							}
2185						}
2186						final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2187						final Message statusMessage;
2188						final int size = shownMarkers.size();
2189						if (size > 1) {
2190							final String body;
2191							if (size <= 4) {
2192								body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2193							} else {
2194								body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2195							}
2196							statusMessage = Message.createStatusMessage(conversation, body);
2197							statusMessage.setCounterparts(shownMarkers);
2198						} else if (size == 1) {
2199							statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2200							statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2201							statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2202						} else {
2203							statusMessage = null;
2204						}
2205						if (statusMessage != null) {
2206							this.messageList.add(i + 1, statusMessage);
2207						}
2208						addedMarkers.add(markerForSender);
2209						if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2210							break;
2211						}
2212					}
2213				}
2214				if (users.size() > 0) {
2215					Message statusMessage;
2216					if (users.size() == 1) {
2217						MucOptions.User user = users.get(0);
2218						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2219						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2220						statusMessage.setTrueCounterpart(user.getRealJid());
2221						statusMessage.setCounterpart(user.getFullJid());
2222					} else {
2223						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2224						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2225						statusMessage.setCounterparts(users);
2226					}
2227					this.messageList.add(statusMessage);
2228				}
2229
2230			}
2231		}
2232	}
2233
2234	private void stopScrolling() {
2235		long now = SystemClock.uptimeMillis();
2236		MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2237		binding.messagesView.dispatchTouchEvent(cancel);
2238	}
2239
2240	private boolean showLoadMoreMessages(final Conversation c) {
2241		if (activity == null || activity.xmppConnectionService == null) {
2242			return false;
2243		}
2244		final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2245		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2246		return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2247	}
2248
2249	private boolean hasMamSupport(final Conversation c) {
2250		if (c.getMode() == Conversation.MODE_SINGLE) {
2251			final XmppConnection connection = c.getAccount().getXmppConnection();
2252			return connection != null && connection.getFeatures().mam();
2253		} else {
2254			return c.getMucOptions().mamSupport();
2255		}
2256	}
2257
2258	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2259		showSnackbar(message, action, clickListener, null);
2260	}
2261
2262	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2263		this.binding.snackbar.setVisibility(View.VISIBLE);
2264		this.binding.snackbar.setOnClickListener(null);
2265		this.binding.snackbarMessage.setText(message);
2266		this.binding.snackbarMessage.setOnClickListener(null);
2267		this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2268		if (action != 0) {
2269			this.binding.snackbarAction.setText(action);
2270		}
2271		this.binding.snackbarAction.setOnClickListener(clickListener);
2272		this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2273	}
2274
2275	protected void hideSnackbar() {
2276		this.binding.snackbar.setVisibility(View.GONE);
2277	}
2278
2279	protected void sendMessage(Message message) {
2280		activity.xmppConnectionService.sendMessage(message);
2281		messageSent();
2282	}
2283
2284	protected void sendPgpMessage(final Message message) {
2285		final XmppConnectionService xmppService = activity.xmppConnectionService;
2286		final Contact contact = message.getConversation().getContact();
2287		if (!activity.hasPgp()) {
2288			activity.showInstallPgpDialog();
2289			return;
2290		}
2291		if (conversation.getAccount().getPgpSignature() == null) {
2292			activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2293			return;
2294		}
2295		if (!mSendingPgpMessage.compareAndSet(false, true)) {
2296			Log.d(Config.LOGTAG, "sending pgp message already in progress");
2297		}
2298		if (conversation.getMode() == Conversation.MODE_SINGLE) {
2299			if (contact.getPgpKeyId() != 0) {
2300				xmppService.getPgpEngine().hasKey(contact,
2301						new UiCallback<Contact>() {
2302
2303							@Override
2304							public void userInputRequried(PendingIntent pi, Contact contact) {
2305								startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2306							}
2307
2308							@Override
2309							public void success(Contact contact) {
2310								encryptTextMessage(message);
2311							}
2312
2313							@Override
2314							public void error(int error, Contact contact) {
2315								activity.runOnUiThread(() -> Toast.makeText(activity,
2316										R.string.unable_to_connect_to_keychain,
2317										Toast.LENGTH_SHORT
2318								).show());
2319								mSendingPgpMessage.set(false);
2320							}
2321						});
2322
2323			} else {
2324				showNoPGPKeyDialog(false, (dialog, which) -> {
2325					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2326					xmppService.updateConversation(conversation);
2327					message.setEncryption(Message.ENCRYPTION_NONE);
2328					xmppService.sendMessage(message);
2329					messageSent();
2330				});
2331			}
2332		} else {
2333			if (conversation.getMucOptions().pgpKeysInUse()) {
2334				if (!conversation.getMucOptions().everybodyHasKeys()) {
2335					Toast warning = Toast
2336							.makeText(getActivity(),
2337									R.string.missing_public_keys,
2338									Toast.LENGTH_LONG);
2339					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2340					warning.show();
2341				}
2342				encryptTextMessage(message);
2343			} else {
2344				showNoPGPKeyDialog(true, (dialog, which) -> {
2345					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2346					message.setEncryption(Message.ENCRYPTION_NONE);
2347					xmppService.updateConversation(conversation);
2348					xmppService.sendMessage(message);
2349					messageSent();
2350				});
2351			}
2352		}
2353	}
2354
2355	public void encryptTextMessage(Message message) {
2356		activity.xmppConnectionService.getPgpEngine().encrypt(message,
2357				new UiCallback<Message>() {
2358
2359					@Override
2360					public void userInputRequried(PendingIntent pi, Message message) {
2361						startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2362					}
2363
2364					@Override
2365					public void success(Message message) {
2366						//TODO the following two call can be made before the callback
2367						getActivity().runOnUiThread(() -> messageSent());
2368					}
2369
2370					@Override
2371					public void error(final int error, Message message) {
2372						getActivity().runOnUiThread(() -> {
2373							doneSendingPgpMessage();
2374							Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2375						});
2376
2377					}
2378				});
2379	}
2380
2381	public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2382		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2383		builder.setIconAttribute(android.R.attr.alertDialogIcon);
2384		if (plural) {
2385			builder.setTitle(getString(R.string.no_pgp_keys));
2386			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2387		} else {
2388			builder.setTitle(getString(R.string.no_pgp_key));
2389			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2390		}
2391		builder.setNegativeButton(getString(R.string.cancel), null);
2392		builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2393		builder.create().show();
2394	}
2395
2396	public void appendText(String text) {
2397		if (text == null) {
2398			return;
2399		}
2400		String previous = this.binding.textinput.getText().toString();
2401		if (UIHelper.isLastLineQuote(previous)) {
2402			text = '\n' + text;
2403		} else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2404			text = " " + text;
2405		}
2406		this.binding.textinput.append(text);
2407	}
2408
2409	@Override
2410	public boolean onEnterPressed() {
2411		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2412		final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2413		if (enterIsSend) {
2414			sendMessage();
2415			return true;
2416		} else {
2417			return false;
2418		}
2419	}
2420
2421	@Override
2422	public void onTypingStarted() {
2423		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2424		if (service == null) {
2425			return;
2426		}
2427		Account.State status = conversation.getAccount().getStatus();
2428		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2429			service.sendChatState(conversation);
2430		}
2431		updateSendButton();
2432	}
2433
2434	@Override
2435	public void onTypingStopped() {
2436		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2437		if (service == null) {
2438			return;
2439		}
2440		Account.State status = conversation.getAccount().getStatus();
2441		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2442			service.sendChatState(conversation);
2443		}
2444	}
2445
2446	@Override
2447	public void onTextDeleted() {
2448		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2449		if (service == null) {
2450			return;
2451		}
2452		Account.State status = conversation.getAccount().getStatus();
2453		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2454			service.sendChatState(conversation);
2455		}
2456		updateSendButton();
2457	}
2458
2459	@Override
2460	public void onTextChanged() {
2461		if (conversation != null && conversation.getCorrectingMessage() != null) {
2462			updateSendButton();
2463		}
2464	}
2465
2466	@Override
2467	public boolean onTabPressed(boolean repeated) {
2468		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2469			return false;
2470		}
2471		if (repeated) {
2472			completionIndex++;
2473		} else {
2474			lastCompletionLength = 0;
2475			completionIndex = 0;
2476			final String content = this.binding.textinput.getText().toString();
2477			lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2478			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2479			firstWord = start == 0;
2480			incomplete = content.substring(start, lastCompletionCursor);
2481		}
2482		List<String> completions = new ArrayList<>();
2483		for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2484			String name = user.getName();
2485			if (name != null && name.startsWith(incomplete)) {
2486				completions.add(name + (firstWord ? ": " : " "));
2487			}
2488		}
2489		Collections.sort(completions);
2490		if (completions.size() > completionIndex) {
2491			String completion = completions.get(completionIndex).substring(incomplete.length());
2492			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2493			this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2494			lastCompletionLength = completion.length();
2495		} else {
2496			completionIndex = -1;
2497			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2498			lastCompletionLength = 0;
2499		}
2500		return true;
2501	}
2502
2503	private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2504		try {
2505			getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2506		} catch (final SendIntentException ignored) {
2507		}
2508	}
2509
2510	@Override
2511	public void onBackendConnected() {
2512		Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2513		String uuid = pendingConversationsUuid.pop();
2514		if (uuid != null) {
2515			if (!findAndReInitByUuidOrArchive(uuid)) {
2516				return;
2517			}
2518		} else {
2519			if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2520				clearPending();
2521				activity.onConversationArchived(conversation);
2522				return;
2523			}
2524		}
2525		ActivityResult activityResult = postponedActivityResult.pop();
2526		if (activityResult != null) {
2527			handleActivityResult(activityResult);
2528		}
2529		clearPending();
2530	}
2531
2532	private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2533		Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2534		if (conversation == null) {
2535			clearPending();
2536			activity.onConversationArchived(null);
2537			return false;
2538		}
2539		reInit(conversation);
2540		ScrollState scrollState = pendingScrollState.pop();
2541		String lastMessageUuid = pendingLastMessageUuid.pop();
2542		if (scrollState != null) {
2543			setScrollPosition(scrollState, lastMessageUuid);
2544		}
2545		return true;
2546	}
2547
2548	private void clearPending() {
2549		if (postponedActivityResult.pop() != null) {
2550			Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2551		}
2552		pendingScrollState.pop();
2553		if (pendingTakePhotoUri.pop() != null) {
2554			Log.e(Config.LOGTAG, "cleared pending photo uri");
2555		}
2556	}
2557
2558	public Conversation getConversation() {
2559		return conversation;
2560	}
2561}