ConversationFragment.java

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