ConversationFragment.java

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