ConversationFragment.java

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