ConversationFragment.java

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