ConversationFragment.java

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