ConversationFragment.java

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