ConversationFragment.java

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