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