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