ConversationFragment.java

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