ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.app.Activity;
   6import android.content.SharedPreferences;
   7import android.content.pm.PackageManager;
   8import android.databinding.DataBindingUtil;
   9import android.net.Uri;
  10import android.os.Build;
  11import android.preference.PreferenceManager;
  12import android.provider.MediaStore;
  13import android.support.annotation.IdRes;
  14import android.support.annotation.NonNull;
  15import android.support.annotation.StringRes;
  16import android.support.v7.app.AlertDialog;
  17import android.app.Fragment;
  18import android.app.PendingIntent;
  19import android.content.ActivityNotFoundException;
  20import android.content.Context;
  21import android.content.DialogInterface;
  22import android.content.Intent;
  23import android.content.IntentSender.SendIntentException;
  24import android.os.Bundle;
  25import android.os.Handler;
  26import android.os.SystemClock;
  27import android.support.v13.view.inputmethod.InputConnectionCompat;
  28import android.support.v13.view.inputmethod.InputContentInfoCompat;
  29import android.text.Editable;
  30import android.util.Log;
  31import android.view.ContextMenu;
  32import android.view.ContextMenu.ContextMenuInfo;
  33import android.view.Gravity;
  34import android.view.LayoutInflater;
  35import android.view.Menu;
  36import android.view.MenuInflater;
  37import android.view.MenuItem;
  38import android.view.MotionEvent;
  39import android.view.View;
  40import android.view.View.OnClickListener;
  41import android.view.ViewGroup;
  42import android.view.inputmethod.EditorInfo;
  43import android.view.inputmethod.InputMethodManager;
  44import android.widget.AbsListView;
  45import android.widget.AbsListView.OnScrollListener;
  46import android.widget.AdapterView;
  47import android.widget.AdapterView.AdapterContextMenuInfo;
  48import android.widget.CheckBox;
  49import android.widget.ListView;
  50import android.widget.PopupMenu;
  51import android.widget.TextView.OnEditorActionListener;
  52import android.widget.Toast;
  53
  54import java.util.ArrayList;
  55import java.util.Arrays;
  56import java.util.Collections;
  57import java.util.HashSet;
  58import java.util.Iterator;
  59import java.util.List;
  60import java.util.Set;
  61import java.util.UUID;
  62import java.util.concurrent.atomic.AtomicBoolean;
  63
  64import eu.siacs.conversations.Config;
  65import eu.siacs.conversations.R;
  66import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  67import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  68import eu.siacs.conversations.databinding.FragmentConversationBinding;
  69import eu.siacs.conversations.entities.Account;
  70import eu.siacs.conversations.entities.Blockable;
  71import eu.siacs.conversations.entities.Contact;
  72import eu.siacs.conversations.entities.Conversation;
  73import eu.siacs.conversations.entities.DownloadableFile;
  74import eu.siacs.conversations.entities.Message;
  75import eu.siacs.conversations.entities.MucOptions;
  76import eu.siacs.conversations.entities.Presence;
  77import eu.siacs.conversations.entities.ReadByMarker;
  78import eu.siacs.conversations.entities.Transferable;
  79import eu.siacs.conversations.entities.TransferablePlaceholder;
  80import eu.siacs.conversations.http.HttpDownloadConnection;
  81import eu.siacs.conversations.persistance.FileBackend;
  82import eu.siacs.conversations.services.MessageArchiveService;
  83import eu.siacs.conversations.services.XmppConnectionService;
  84import eu.siacs.conversations.ui.adapter.MessageAdapter;
  85import eu.siacs.conversations.ui.util.ActivityResult;
  86import eu.siacs.conversations.ui.util.AttachmentTool;
  87import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
  88import eu.siacs.conversations.ui.util.PendingItem;
  89import eu.siacs.conversations.ui.util.PresenceSelector;
  90import eu.siacs.conversations.ui.util.ScrollState;
  91import eu.siacs.conversations.ui.util.SendButtonAction;
  92import eu.siacs.conversations.ui.util.SendButtonTool;
  93import eu.siacs.conversations.ui.widget.EditMessage;
  94import eu.siacs.conversations.utils.MessageUtils;
  95import eu.siacs.conversations.utils.NickValidityChecker;
  96import eu.siacs.conversations.utils.StylingHelper;
  97import eu.siacs.conversations.utils.TimeframeUtils;
  98import eu.siacs.conversations.utils.UIHelper;
  99import eu.siacs.conversations.xmpp.XmppConnection;
 100import eu.siacs.conversations.xmpp.chatstate.ChatState;
 101import rocks.xmpp.addr.Jid;
 102
 103import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
 104import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
 105
 106
 107public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener {
 108
 109
 110	public static final int REQUEST_SEND_MESSAGE = 0x0201;
 111	public static final int REQUEST_DECRYPT_PGP = 0x0202;
 112	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
 113	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
 114	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
 115	public static final int REQUEST_START_DOWNLOAD = 0x0210;
 116	public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
 117	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
 118	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
 119	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
 120	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
 121	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
 122	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
 123	public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
 124
 125	public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
 126	public static final String STATE_CONVERSATION_UUID = ConversationFragment.class.getName() + ".uuid";
 127	public static final String STATE_SCROLL_POSITION = ConversationFragment.class.getName() + ".scroll_position";
 128	public static final String STATE_PHOTO_URI = ConversationFragment.class.getName() + ".take_photo_uri";
 129
 130
 131	final protected List<Message> messageList = new ArrayList<>();
 132	private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
 133	private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
 134	private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
 135	private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
 136	private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
 137	private final PendingItem<Message> pendingMessage = new PendingItem<>();
 138	public Uri mPendingEditorContent = null;
 139	protected MessageAdapter messageListAdapter;
 140	private Conversation conversation;
 141	private FragmentConversationBinding binding;
 142	private Toast messageLoaderToast;
 143	private ConversationsActivity activity;
 144	private boolean reInitRequiredOnStart = true;
 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.xmppConnectionService.archiveConversation(conversation);
 160			activity.onConversationArchived(conversation);
 161		}
 162	};
 163	private OnClickListener joinMuc = new OnClickListener() {
 164
 165		@Override
 166		public void onClick(View v) {
 167			activity.xmppConnectionService.joinMuc(conversation);
 168		}
 169	};
 170	private OnClickListener enterPassword = new OnClickListener() {
 171
 172		@Override
 173		public void onClick(View v) {
 174			MucOptions muc = conversation.getMucOptions();
 175			String password = muc.getPassword();
 176			if (password == null) {
 177				password = "";
 178			}
 179			activity.quickPasswordEdit(password, value -> {
 180				activity.xmppConnectionService.providePasswordForMuc(conversation, value);
 181				return null;
 182			});
 183		}
 184	};
 185	private OnScrollListener mOnScrollListener = new OnScrollListener() {
 186
 187		@Override
 188		public void onScrollStateChanged(AbsListView view, int scrollState) {
 189			// TODO Auto-generated method stub
 190
 191		}
 192
 193		@Override
 194		public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
 195			synchronized (ConversationFragment.this.messageList) {
 196				if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true, false) && messageList.size() > 0) {
 197					long timestamp;
 198					if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
 199						timestamp = messageList.get(1).getTimeSent();
 200					} else {
 201						timestamp = messageList.get(0).getTimeSent();
 202					}
 203					activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
 204						@Override
 205						public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
 206							if (ConversationFragment.this.conversation != conversation) {
 207								conversation.messagesLoaded.set(true);
 208								return;
 209							}
 210							runOnUiThread(() -> {
 211								final int oldPosition = binding.messagesView.getFirstVisiblePosition();
 212								Message message = null;
 213								int childPos;
 214								for (childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
 215									message = messageList.get(oldPosition + childPos);
 216									if (message.getType() != Message.TYPE_STATUS) {
 217										break;
 218									}
 219								}
 220								final String uuid = message != null ? message.getUuid() : null;
 221								View v = binding.messagesView.getChildAt(childPos);
 222								final int pxOffset = (v == null) ? 0 : v.getTop();
 223								ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
 224								try {
 225									updateStatusMessages();
 226								} catch (IllegalStateException e) {
 227									Log.d(Config.LOGTAG, "caught illegal state exception while updating status messages");
 228								}
 229								messageListAdapter.notifyDataSetChanged();
 230								int pos = Math.max(getIndexOf(uuid, messageList), 0);
 231								binding.messagesView.setSelectionFromTop(pos, pxOffset);
 232								if (messageLoaderToast != null) {
 233									messageLoaderToast.cancel();
 234								}
 235								conversation.messagesLoaded.set(true);
 236							});
 237						}
 238
 239						@Override
 240						public void informUser(final int resId) {
 241
 242							runOnUiThread(() -> {
 243								if (messageLoaderToast != null) {
 244									messageLoaderToast.cancel();
 245								}
 246								if (ConversationFragment.this.conversation != conversation) {
 247									return;
 248								}
 249								messageLoaderToast = Toast.makeText(view.getContext(), resId, Toast.LENGTH_LONG);
 250								messageLoaderToast.show();
 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 (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, true);
 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	protected OnClickListener clickToDecryptListener = new OnClickListener() {
 330
 331		@Override
 332		public void onClick(View v) {
 333			PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
 334			if (pendingIntent != null) {
 335				try {
 336					getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(),
 337							REQUEST_DECRYPT_PGP,
 338							null,
 339							0,
 340							0,
 341							0);
 342				} catch (SendIntentException e) {
 343					Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
 344					conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
 345				}
 346			}
 347			updateSnackBar(conversation);
 348		}
 349	};
 350	private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
 351	private OnEditorActionListener mEditorActionListener = (v, actionId, event) -> {
 352		if (actionId == EditorInfo.IME_ACTION_SEND) {
 353			InputMethodManager imm = (InputMethodManager) v.getContext()
 354					.getSystemService(Context.INPUT_METHOD_SERVICE);
 355			if (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) {
 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					sendAxolotlMessage(message);
 658				}
 659				break;
 660			default:
 661				sendPlainTextMessage(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				sendAxolotlMessage(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						if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
 881							Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
 882						}
 883						highlightInConference(user.getResource());
 884					}
 885					return;
 886				} else {
 887					if (!message.getContact().isSelf()) {
 888						String fingerprint;
 889						if (message.getEncryption() == Message.ENCRYPTION_PGP
 890								|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 891							fingerprint = "pgp";
 892						} else {
 893							fingerprint = message.getFingerprint();
 894						}
 895						activity.switchToContactDetails(message.getContact(), fingerprint);
 896						return;
 897					}
 898				}
 899			}
 900			Account account = message.getConversation().getAccount();
 901			Intent intent = new Intent(activity, EditAccountActivity.class);
 902			intent.putExtra("jid", account.getJid().asBareJid().toString());
 903			String fingerprint;
 904			if (message.getEncryption() == Message.ENCRYPTION_PGP
 905					|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 906				fingerprint = "pgp";
 907			} else {
 908				fingerprint = message.getFingerprint();
 909			}
 910			intent.putExtra("fingerprint", fingerprint);
 911			startActivity(intent);
 912		});
 913		messageListAdapter.setOnContactPictureLongClicked(message -> {
 914			if (message.getStatus() <= Message.STATUS_RECEIVED) {
 915				if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 916					final MucOptions mucOptions = conversation.getMucOptions();
 917					if (!mucOptions.allowPm()) {
 918						Toast.makeText(getActivity(), R.string.private_messages_are_disabled, Toast.LENGTH_SHORT).show();
 919						return;
 920					}
 921					Jid user = message.getCounterpart();
 922					if (user != null && !user.isBareJid()) {
 923						if (mucOptions.isUserInRoom(user)) {
 924							privateMessageWith(user);
 925						} else {
 926							Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
 927						}
 928					}
 929				}
 930			} else {
 931				activity.showQrCode(conversation.getAccount().getShareableUri());
 932			}
 933		});
 934		messageListAdapter.setOnQuoteListener(this::quoteText);
 935		binding.messagesView.setAdapter(messageListAdapter);
 936
 937		registerForContextMenu(binding.messagesView);
 938
 939		return binding.getRoot();
 940	}
 941
 942	private void quoteText(String text) {
 943		if (binding.textinput.isEnabled()) {
 944			text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
 945			Editable editable = binding.textinput.getEditableText();
 946			int position = binding.textinput.getSelectionEnd();
 947			if (position == -1) position = editable.length();
 948			if (position > 0 && editable.charAt(position - 1) != '\n') {
 949				editable.insert(position++, "\n");
 950			}
 951			editable.insert(position, text);
 952			position += text.length();
 953			editable.insert(position++, "\n");
 954			if (position < editable.length() && editable.charAt(position) != '\n') {
 955				editable.insert(position, "\n");
 956			}
 957			binding.textinput.setSelection(position);
 958			binding.textinput.requestFocus();
 959			InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
 960			if (inputMethodManager != null) {
 961				inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
 962			}
 963		}
 964	}
 965
 966	private void quoteMessage(Message message) {
 967		quoteText(MessageUtils.prepareQuote(message));
 968	}
 969
 970	@Override
 971	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
 972		synchronized (this.messageList) {
 973			super.onCreateContextMenu(menu, v, menuInfo);
 974			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
 975			this.selectedMessage = this.messageList.get(acmi.position);
 976			populateContextMenu(menu);
 977		}
 978	}
 979
 980	private void populateContextMenu(ContextMenu menu) {
 981		final Message m = this.selectedMessage;
 982		final Transferable t = m.getTransferable();
 983		Message relevantForCorrection = m;
 984		while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
 985			relevantForCorrection = relevantForCorrection.next();
 986		}
 987		if (m.getType() != Message.TYPE_STATUS) {
 988			final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
 989					&& m.getType() != Message.TYPE_PRIVATE
 990					&& t == null;
 991			final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
 992					|| m.getEncryption() == Message.ENCRYPTION_PGP;
 993			activity.getMenuInflater().inflate(R.menu.message_context, menu);
 994			menu.setHeaderTitle(R.string.message_options);
 995			MenuItem copyMessage = menu.findItem(R.id.copy_message);
 996			MenuItem quoteMessage = menu.findItem(R.id.quote_message);
 997			MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
 998			MenuItem correctMessage = menu.findItem(R.id.correct_message);
 999			MenuItem shareWith = menu.findItem(R.id.share_with);
1000			MenuItem sendAgain = menu.findItem(R.id.send_again);
1001			MenuItem copyUrl = menu.findItem(R.id.copy_url);
1002			MenuItem downloadFile = menu.findItem(R.id.download_file);
1003			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1004			MenuItem deleteFile = menu.findItem(R.id.delete_file);
1005			MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1006			if (!treatAsFile && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1007				copyMessage.setVisible(true);
1008				quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
1009			}
1010			if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1011				retryDecryption.setVisible(true);
1012			}
1013			if (relevantForCorrection.getType() == Message.TYPE_TEXT
1014					&& relevantForCorrection.isLastCorrectableMessage()
1015					&& (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
1016				correctMessage.setVisible(true);
1017			}
1018			if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1019				shareWith.setVisible(true);
1020			}
1021			if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1022				sendAgain.setVisible(true);
1023			}
1024			if (m.hasFileOnRemoteHost()
1025					|| m.isGeoUri()
1026					|| m.treatAsDownloadable()
1027					|| (t != null && t instanceof HttpDownloadConnection)) {
1028				copyUrl.setVisible(true);
1029			}
1030			if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
1031				downloadFile.setVisible(true);
1032				downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1033			}
1034			boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1035					|| m.getStatus() == Message.STATUS_UNSEND
1036					|| m.getStatus() == Message.STATUS_OFFERED;
1037			if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
1038				cancelTransmission.setVisible(true);
1039			}
1040			if (treatAsFile) {
1041				String path = m.getRelativeFilePath();
1042				if (path == null || !path.startsWith("/")) {
1043					deleteFile.setVisible(true);
1044					deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1045				}
1046			}
1047			if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
1048				showErrorMessage.setVisible(true);
1049			}
1050		}
1051	}
1052
1053	@Override
1054	public boolean onContextItemSelected(MenuItem item) {
1055		switch (item.getItemId()) {
1056			case R.id.share_with:
1057				shareWith(selectedMessage);
1058				return true;
1059			case R.id.correct_message:
1060				correctMessage(selectedMessage);
1061				return true;
1062			case R.id.copy_message:
1063				copyMessage(selectedMessage);
1064				return true;
1065			case R.id.quote_message:
1066				quoteMessage(selectedMessage);
1067				return true;
1068			case R.id.send_again:
1069				resendMessage(selectedMessage);
1070				return true;
1071			case R.id.copy_url:
1072				copyUrl(selectedMessage);
1073				return true;
1074			case R.id.download_file:
1075				startDownloadable(selectedMessage);
1076				return true;
1077			case R.id.cancel_transmission:
1078				cancelTransmission(selectedMessage);
1079				return true;
1080			case R.id.retry_decryption:
1081				retryDecryption(selectedMessage);
1082				return true;
1083			case R.id.delete_file:
1084				deleteFile(selectedMessage);
1085				return true;
1086			case R.id.show_error_message:
1087				showErrorMessage(selectedMessage);
1088				return true;
1089			default:
1090				return super.onContextItemSelected(item);
1091		}
1092	}
1093
1094	@Override
1095	public boolean onOptionsItemSelected(final MenuItem item) {
1096		if (conversation == null) {
1097			return super.onOptionsItemSelected(item);
1098		}
1099		switch (item.getItemId()) {
1100			case R.id.encryption_choice_axolotl:
1101			case R.id.encryption_choice_pgp:
1102			case R.id.encryption_choice_none:
1103				handleEncryptionSelection(item);
1104				break;
1105			case R.id.attach_choose_picture:
1106			case R.id.attach_take_picture:
1107			case R.id.attach_record_video:
1108			case R.id.attach_choose_file:
1109			case R.id.attach_record_voice:
1110			case R.id.attach_location:
1111				handleAttachmentSelection(item);
1112				break;
1113			case R.id.action_archive:
1114				activity.xmppConnectionService.archiveConversation(conversation);
1115				activity.onConversationArchived(conversation);
1116				break;
1117			case R.id.action_contact_details:
1118				activity.switchToContactDetails(conversation.getContact());
1119				break;
1120			case R.id.action_muc_details:
1121				Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1122				intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1123				intent.putExtra("uuid", conversation.getUuid());
1124				startActivity(intent);
1125				break;
1126			case R.id.action_invite:
1127				startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1128				break;
1129			case R.id.action_clear_history:
1130				clearHistoryDialog(conversation);
1131				break;
1132			case R.id.action_mute:
1133				muteConversationDialog(conversation);
1134				break;
1135			case R.id.action_unmute:
1136				unmuteConversation(conversation);
1137				break;
1138			case R.id.action_block:
1139			case R.id.action_unblock:
1140				final Activity activity = getActivity();
1141				if (activity instanceof XmppActivity) {
1142					BlockContactDialog.show((XmppActivity) activity, conversation);
1143				}
1144				break;
1145			default:
1146				break;
1147		}
1148		return super.onOptionsItemSelected(item);
1149	}
1150
1151	private void handleAttachmentSelection(MenuItem item) {
1152		switch (item.getItemId()) {
1153			case R.id.attach_choose_picture:
1154				attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1155				break;
1156			case R.id.attach_take_picture:
1157				attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1158				break;
1159			case R.id.attach_record_video:
1160				attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1161				break;
1162			case R.id.attach_choose_file:
1163				attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1164				break;
1165			case R.id.attach_record_voice:
1166				attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1167				break;
1168			case R.id.attach_location:
1169				attachFile(ATTACHMENT_CHOICE_LOCATION);
1170				break;
1171		}
1172	}
1173
1174	private void handleEncryptionSelection(MenuItem item) {
1175		if (conversation == null) {
1176			return;
1177		}
1178		switch (item.getItemId()) {
1179			case R.id.encryption_choice_none:
1180				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1181				item.setChecked(true);
1182				break;
1183			case R.id.encryption_choice_pgp:
1184				if (activity.hasPgp()) {
1185					if (conversation.getAccount().getPgpSignature() != null) {
1186						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1187						item.setChecked(true);
1188					} else {
1189						activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1190					}
1191				} else {
1192					activity.showInstallPgpDialog();
1193				}
1194				break;
1195			case R.id.encryption_choice_axolotl:
1196				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1197						+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
1198				conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1199				item.setChecked(true);
1200				break;
1201			default:
1202				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1203				break;
1204		}
1205		activity.xmppConnectionService.updateConversation(conversation);
1206		updateChatMsgHint();
1207		getActivity().invalidateOptionsMenu();
1208		activity.refreshUi();
1209	}
1210
1211	public void attachFile(final int attachmentChoice) {
1212		if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1213			if (!hasStorageAndCameraPermission(attachmentChoice)) {
1214				return;
1215			}
1216		} else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1217			if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
1218				return;
1219			}
1220		}
1221		try {
1222			activity.getPreferences().edit()
1223					.putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1224					.apply();
1225		} catch (IllegalArgumentException e) {
1226			//just do not save
1227		}
1228		final int encryption = conversation.getNextEncryption();
1229		final int mode = conversation.getMode();
1230		if (encryption == Message.ENCRYPTION_PGP) {
1231			if (activity.hasPgp()) {
1232				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1233					activity.xmppConnectionService.getPgpEngine().hasKey(
1234							conversation.getContact(),
1235							new UiCallback<Contact>() {
1236
1237								@Override
1238								public void userInputRequried(PendingIntent pi, Contact contact) {
1239									startPendingIntent(pi, attachmentChoice);
1240								}
1241
1242								@Override
1243								public void success(Contact contact) {
1244									selectPresenceToAttachFile(attachmentChoice);
1245								}
1246
1247								@Override
1248								public void error(int error, Contact contact) {
1249									activity.replaceToast(getString(error));
1250								}
1251							});
1252				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1253					if (!conversation.getMucOptions().everybodyHasKeys()) {
1254						Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1255						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1256						warning.show();
1257					}
1258					selectPresenceToAttachFile(attachmentChoice);
1259				} else {
1260					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
1261							.findFragmentByTag("conversation");
1262					if (fragment != null) {
1263						fragment.showNoPGPKeyDialog(false, (dialog, which) -> {
1264							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1265							activity.xmppConnectionService.updateConversation(conversation);
1266							selectPresenceToAttachFile(attachmentChoice);
1267						});
1268					}
1269				}
1270			} else {
1271				activity.showInstallPgpDialog();
1272			}
1273		} else {
1274			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1275				selectPresenceToAttachFile(attachmentChoice);
1276			}
1277		}
1278	}
1279
1280	@Override
1281	public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
1282		if (grantResults.length > 0)
1283			if (allGranted(grantResults)) {
1284				if (requestCode == REQUEST_START_DOWNLOAD) {
1285					if (this.mPendingDownloadableMessage != null) {
1286						startDownloadable(this.mPendingDownloadableMessage);
1287					}
1288				} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1289					if (this.mPendingEditorContent != null) {
1290						attachImageToConversation(this.mPendingEditorContent);
1291					}
1292				} else {
1293					attachFile(requestCode);
1294				}
1295			} else {
1296				@StringRes int res;
1297				if (Manifest.permission.CAMERA.equals(getFirstDenied(grantResults, permissions))) {
1298					res = R.string.no_camera_permission;
1299				} else {
1300					res = R.string.no_storage_permission;
1301				}
1302				Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1303			}
1304	}
1305
1306	public void startDownloadable(Message message) {
1307		if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(REQUEST_START_DOWNLOAD)) {
1308			this.mPendingDownloadableMessage = message;
1309			return;
1310		}
1311		Transferable transferable = message.getTransferable();
1312		if (transferable != null) {
1313			if (!transferable.start()) {
1314				Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1315			}
1316		} else if (message.treatAsDownloadable()) {
1317			activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1318		}
1319	}
1320
1321	@SuppressLint("InflateParams")
1322	protected void clearHistoryDialog(final Conversation conversation) {
1323		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1324		builder.setTitle(getString(R.string.clear_conversation_history));
1325		final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1326		final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1327		builder.setView(dialogView);
1328		builder.setNegativeButton(getString(R.string.cancel), null);
1329		builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1330			this.activity.xmppConnectionService.clearConversationHistory(conversation);
1331			if (endConversationCheckBox.isChecked()) {
1332				this.activity.xmppConnectionService.archiveConversation(conversation);
1333				this.activity.onConversationArchived(conversation);
1334			} else {
1335				activity.onConversationsListItemUpdated();
1336				refresh();
1337			}
1338		});
1339		builder.create().show();
1340	}
1341
1342	protected void muteConversationDialog(final Conversation conversation) {
1343		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1344		builder.setTitle(R.string.disable_notifications);
1345		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1346		final CharSequence[] labels = new CharSequence[durations.length];
1347		for (int i = 0; i < durations.length; ++i) {
1348			if (durations[i] == -1) {
1349				labels[i] = getString(R.string.until_further_notice);
1350			} else {
1351				labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1352			}
1353		}
1354		builder.setItems(labels, (dialog, which) -> {
1355			final long till;
1356			if (durations[which] == -1) {
1357				till = Long.MAX_VALUE;
1358			} else {
1359				till = System.currentTimeMillis() + (durations[which] * 1000);
1360			}
1361			conversation.setMutedTill(till);
1362			activity.xmppConnectionService.updateConversation(conversation);
1363			activity.onConversationsListItemUpdated();
1364			refresh();
1365			getActivity().invalidateOptionsMenu();
1366		});
1367		builder.create().show();
1368	}
1369
1370	private boolean hasStoragePermission(int requestCode) {
1371		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1372			if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1373				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1374				return false;
1375			} else {
1376				return true;
1377			}
1378		} else {
1379			return true;
1380		}
1381	}
1382
1383	private boolean hasStorageAndCameraPermission(int requestCode) {
1384		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1385			List<String> missingPermissions = new ArrayList<>();
1386			if (!Config.ONLY_INTERNAL_STORAGE && activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1387				missingPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
1388			}
1389			if (activity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
1390				missingPermissions.add(Manifest.permission.CAMERA);
1391			}
1392			if (missingPermissions.size() == 0) {
1393				return true;
1394			} else {
1395				requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1396				return false;
1397			}
1398		} else {
1399			return true;
1400		}
1401	}
1402
1403	public void unmuteConversation(final Conversation conversation) {
1404		conversation.setMutedTill(0);
1405		this.activity.xmppConnectionService.updateConversation(conversation);
1406		this.activity.onConversationsListItemUpdated();
1407		refresh();
1408		getActivity().invalidateOptionsMenu();
1409	}
1410
1411	protected void selectPresenceToAttachFile(final int attachmentChoice) {
1412		final Account account = conversation.getAccount();
1413		final PresenceSelector.OnPresenceSelected callback = () -> {
1414			Intent intent = new Intent();
1415			boolean chooser = false;
1416			String fallbackPackageId = null;
1417			switch (attachmentChoice) {
1418				case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1419					intent.setAction(Intent.ACTION_GET_CONTENT);
1420					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1421						intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1422					}
1423					intent.setType("image/*");
1424					chooser = true;
1425					break;
1426				case ATTACHMENT_CHOICE_RECORD_VIDEO:
1427					intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1428					break;
1429				case ATTACHMENT_CHOICE_TAKE_PHOTO:
1430					final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1431					pendingTakePhotoUri.push(uri);
1432					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1433					intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1434					intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1435					intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1436					break;
1437				case ATTACHMENT_CHOICE_CHOOSE_FILE:
1438					chooser = true;
1439					intent.setType("*/*");
1440					intent.addCategory(Intent.CATEGORY_OPENABLE);
1441					intent.setAction(Intent.ACTION_GET_CONTENT);
1442					break;
1443				case ATTACHMENT_CHOICE_RECORD_VOICE:
1444					intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
1445					fallbackPackageId = "eu.siacs.conversations.voicerecorder";
1446					break;
1447				case ATTACHMENT_CHOICE_LOCATION:
1448					intent.setAction("eu.siacs.conversations.location.request");
1449					fallbackPackageId = "eu.siacs.conversations.sharelocation";
1450					break;
1451			}
1452			if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1453				if (chooser) {
1454					startActivityForResult(
1455							Intent.createChooser(intent, getString(R.string.perform_action_with)),
1456							attachmentChoice);
1457				} else {
1458					startActivityForResult(intent, attachmentChoice);
1459				}
1460			} else if (fallbackPackageId != null) {
1461				startActivity(getInstallApkIntent(fallbackPackageId));
1462			}
1463		};
1464		if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1465			conversation.setNextCounterpart(null);
1466			callback.onPresenceSelected();
1467		} else {
1468			activity.selectPresence(conversation, callback);
1469		}
1470	}
1471
1472	private Intent getInstallApkIntent(final String packageId) {
1473		Intent intent = new Intent(Intent.ACTION_VIEW);
1474		intent.setData(Uri.parse("market://details?id=" + packageId));
1475		if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1476			return intent;
1477		} else {
1478			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
1479			return intent;
1480		}
1481	}
1482
1483	@Override
1484	public void onResume() {
1485		new Handler().post(() -> {
1486			final Activity activity = getActivity();
1487			if (activity == null) {
1488				return;
1489			}
1490			final PackageManager packageManager = activity.getPackageManager();
1491			ConversationMenuConfigurator.updateAttachmentAvailability(packageManager);
1492			getActivity().invalidateOptionsMenu();
1493		});
1494		super.onResume();
1495		if (activity != null && this.conversation != null) {
1496			activity.onConversationRead(this.conversation);
1497		}
1498	}
1499
1500	private void showErrorMessage(final Message message) {
1501		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1502		builder.setTitle(R.string.error_message);
1503		builder.setMessage(message.getErrorMessage());
1504		builder.setPositiveButton(R.string.confirm, null);
1505		builder.create().show();
1506	}
1507
1508	private void shareWith(Message message) {
1509		Intent shareIntent = new Intent();
1510		shareIntent.setAction(Intent.ACTION_SEND);
1511		if (message.isGeoUri()) {
1512			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
1513			shareIntent.setType("text/plain");
1514		} else if (!message.isFileOrImage()) {
1515			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
1516			shareIntent.setType("text/plain");
1517		} else {
1518			final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1519			try {
1520				shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(getActivity(), file));
1521			} catch (SecurityException e) {
1522				Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
1523				return;
1524			}
1525			shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1526			String mime = message.getMimeType();
1527			if (mime == null) {
1528				mime = "*/*";
1529			}
1530			shareIntent.setType(mime);
1531		}
1532		try {
1533			startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
1534		} catch (ActivityNotFoundException e) {
1535			//This should happen only on faulty androids because normally chooser is always available
1536			Toast.makeText(getActivity(), R.string.no_application_found_to_open_file, Toast.LENGTH_SHORT).show();
1537		}
1538	}
1539
1540	private void copyMessage(Message message) {
1541		if (activity.copyTextToClipboard(message.getMergedBody().toString(), R.string.message)) {
1542			Toast.makeText(getActivity(), R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1543		}
1544	}
1545
1546	private void deleteFile(Message message) {
1547		if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1548			message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1549			activity.onConversationsListItemUpdated();
1550			refresh();
1551		}
1552	}
1553
1554	private void resendMessage(final Message message) {
1555		if (message.isFileOrImage()) {
1556			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1557			if (file.exists()) {
1558				final Conversation conversation = message.getConversation();
1559				final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1560				if (!message.hasFileOnRemoteHost()
1561						&& xmppConnection != null
1562						&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1563					activity.selectPresence(conversation, () -> {
1564						message.setCounterpart(conversation.getNextCounterpart());
1565						activity.xmppConnectionService.resendFailedMessages(message);
1566						new Handler().post(() -> {
1567							int size = messageList.size();
1568							this.binding.messagesView.setSelection(size - 1);
1569						});
1570					});
1571					return;
1572				}
1573			} else {
1574				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1575				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1576				activity.onConversationsListItemUpdated();
1577				refresh();
1578				return;
1579			}
1580		}
1581		activity.xmppConnectionService.resendFailedMessages(message);
1582		new Handler().post(() -> {
1583			int size = messageList.size();
1584			this.binding.messagesView.setSelection(size - 1);
1585		});
1586	}
1587
1588	private void copyUrl(Message message) {
1589		final String url;
1590		final int resId;
1591		if (message.isGeoUri()) {
1592			resId = R.string.location;
1593			url = message.getBody();
1594		} else if (message.hasFileOnRemoteHost()) {
1595			resId = R.string.file_url;
1596			url = message.getFileParams().url.toString();
1597		} else {
1598			url = message.getBody().trim();
1599			resId = R.string.file_url;
1600		}
1601		if (activity.copyTextToClipboard(url, resId)) {
1602			Toast.makeText(getActivity(), R.string.url_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1603		}
1604	}
1605
1606	private void cancelTransmission(Message message) {
1607		Transferable transferable = message.getTransferable();
1608		if (transferable != null) {
1609			transferable.cancel();
1610		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
1611			activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1612		}
1613	}
1614
1615	private void retryDecryption(Message message) {
1616		message.setEncryption(Message.ENCRYPTION_PGP);
1617		activity.onConversationsListItemUpdated();
1618		refresh();
1619		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1620	}
1621
1622	private void privateMessageWith(final Jid counterpart) {
1623		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1624			activity.xmppConnectionService.sendChatState(conversation);
1625		}
1626		this.binding.textinput.setText("");
1627		this.conversation.setNextCounterpart(counterpart);
1628		updateChatMsgHint();
1629		updateSendButton();
1630		updateEditablity();
1631	}
1632
1633	private void correctMessage(Message message) {
1634		while (message.mergeable(message.next())) {
1635			message = message.next();
1636		}
1637		this.conversation.setCorrectingMessage(message);
1638		final Editable editable = binding.textinput.getText();
1639		this.conversation.setDraftMessage(editable.toString());
1640		this.binding.textinput.setText("");
1641		this.binding.textinput.append(message.getBody());
1642
1643	}
1644
1645	private void highlightInConference(String nick) {
1646		final Editable editable = this.binding.textinput.getText();
1647		String oldString = editable.toString().trim();
1648		final int pos = this.binding.textinput.getSelectionStart();
1649		if (oldString.isEmpty() || pos == 0) {
1650			editable.insert(0, nick + ": ");
1651		} else {
1652			final char before = editable.charAt(pos - 1);
1653			final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1654			if (before == '\n') {
1655				editable.insert(pos, nick + ": ");
1656			} else {
1657				if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1658					if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1659						editable.insert(pos - 2, ", " + nick);
1660						return;
1661					}
1662				}
1663				editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1664				if (Character.isWhitespace(after)) {
1665					this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1666				}
1667			}
1668		}
1669	}
1670
1671	@Override
1672	public void onSaveInstanceState(Bundle outState) {
1673		super.onSaveInstanceState(outState);
1674		if (conversation != null) {
1675			outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1676			final Uri uri = pendingTakePhotoUri.peek();
1677			if (uri != null) {
1678				outState.putString(STATE_PHOTO_URI, uri.toString());
1679			}
1680			final ScrollState scrollState = getScrollPosition();
1681			if (scrollState != null) {
1682				outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1683			}
1684		}
1685	}
1686
1687	@Override
1688	public void onActivityCreated(Bundle savedInstanceState) {
1689		super.onActivityCreated(savedInstanceState);
1690		if (savedInstanceState == null) {
1691			return;
1692		}
1693		String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1694		if (uuid != null) {
1695			this.pendingConversationsUuid.push(uuid);
1696			String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1697			if (takePhotoUri != null) {
1698				pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1699			}
1700			pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1701		}
1702	}
1703
1704	@Override
1705	public void onStart() {
1706		super.onStart();
1707		if (this.reInitRequiredOnStart) {
1708			final Bundle extras = pendingExtras.pop();
1709			reInit(conversation, extras != null);
1710			if (extras != null) {
1711				processExtras(extras);
1712			}
1713		} else {
1714			Log.d(Config.LOGTAG, "skipped reinit on start");
1715		}
1716	}
1717
1718	@Override
1719	public void onStop() {
1720		super.onStop();
1721		final Activity activity = getActivity();
1722		if (activity == null || !activity.isChangingConfigurations()) {
1723			messageListAdapter.stopAudioPlayer();
1724		}
1725		if (this.conversation != null) {
1726			final String msg = this.binding.textinput.getText().toString();
1727			if (this.conversation.setNextMessage(msg)) {
1728				this.activity.xmppConnectionService.updateConversation(this.conversation);
1729			}
1730			updateChatState(this.conversation, msg);
1731			this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1732		}
1733		this.reInitRequiredOnStart = true;
1734	}
1735
1736	private void updateChatState(final Conversation conversation, final String msg) {
1737		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1738		Account.State status = conversation.getAccount().getStatus();
1739		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1740			activity.xmppConnectionService.sendChatState(conversation);
1741		}
1742	}
1743
1744	private void saveMessageDraftStopAudioPlayer() {
1745		final Conversation previousConversation = this.conversation;
1746		if (this.activity == null || this.binding == null || previousConversation == null) {
1747			return;
1748		}
1749		Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1750		final String msg = this.binding.textinput.getText().toString();
1751		if (previousConversation.setNextMessage(msg)) {
1752			activity.xmppConnectionService.updateConversation(previousConversation);
1753		}
1754		updateChatState(this.conversation, msg);
1755		messageListAdapter.stopAudioPlayer();
1756	}
1757
1758	public void reInit(Conversation conversation, Bundle extras) {
1759		this.saveMessageDraftStopAudioPlayer();
1760		if (this.reInit(conversation, extras != null)) {
1761			if (extras != null) {
1762				processExtras(extras);
1763			}
1764			this.reInitRequiredOnStart = false;
1765		} else {
1766			this.reInitRequiredOnStart = true;
1767			pendingExtras.push(extras);
1768		}
1769	}
1770
1771	private void reInit(Conversation conversation) {
1772		reInit(conversation, false);
1773	}
1774
1775	private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1776		if (conversation == null) {
1777			return false;
1778		}
1779		this.conversation = conversation;
1780		//once we set the conversation all is good and it will automatically do the right thing in onStart()
1781		if (this.activity == null || this.binding == null) {
1782			return false;
1783		}
1784		Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1785
1786		if (this.conversation.isRead() && hasExtras) {
1787			Log.d(Config.LOGTAG, "trimming conversation");
1788			this.conversation.trim();
1789		}
1790
1791		setupIme();
1792
1793		final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1794
1795		this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1796		this.binding.textinput.setKeyboardListener(null);
1797		this.binding.textinput.setText("");
1798		this.binding.textinput.append(this.conversation.getNextMessage());
1799		this.binding.textinput.setKeyboardListener(this);
1800		messageListAdapter.updatePreferences();
1801		refresh(false);
1802		this.conversation.messagesLoaded.set(true);
1803
1804		Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1805
1806		if (hasExtras || scrolledToBottomAndNoPending) {
1807			synchronized (this.messageList) {
1808				Log.d(Config.LOGTAG, "jump to first unread message");
1809				final Message first = conversation.getFirstUnreadMessage();
1810				final int bottom = Math.max(0, this.messageList.size() - 1);
1811				final int pos;
1812				if (first == null) {
1813					pos = bottom;
1814				} else {
1815					int i = getIndexOf(first.getUuid(), this.messageList);
1816					pos = i < 0 ? bottom : i;
1817				}
1818				setSelection(pos);
1819			}
1820		}
1821
1822		activity.onConversationRead(this.conversation);
1823		//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
1824		activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1825		return true;
1826	}
1827
1828	private void setSelection(int pos) {
1829		this.binding.messagesView.setSelection(pos);
1830		this.binding.messagesView.post(() -> this.binding.messagesView.setSelection(pos));
1831	}
1832
1833	private boolean scrolledToBottom() {
1834		if (this.binding == null) {
1835			return false;
1836		}
1837		final ListView listView = this.binding.messagesView;
1838		if (listView.getLastVisiblePosition() == listView.getAdapter().getCount() - 1) {
1839			final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
1840			return lastChild != null && lastChild.getBottom() <= listView.getHeight();
1841		} else {
1842			return false;
1843		}
1844	}
1845
1846	private void processExtras(Bundle extras) {
1847		final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1848		final String text = extras.getString(ConversationsActivity.EXTRA_TEXT);
1849		final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
1850		final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1851		if (nick != null) {
1852			if (pm) {
1853				Jid jid = conversation.getJid();
1854				try {
1855					Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
1856					privateMessageWith(next);
1857				} catch (final IllegalArgumentException ignored) {
1858					//do nothing
1859				}
1860			} else {
1861				highlightInConference(nick);
1862			}
1863		} else {
1864			appendText(text);
1865		}
1866		final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
1867		if (message != null) {
1868			startDownloadable(message);
1869		}
1870	}
1871
1872	private boolean showBlockSubmenu(View view) {
1873		final Jid jid = conversation.getJid();
1874		if (jid.getLocal() == null) {
1875			BlockContactDialog.show(activity, conversation);
1876		} else {
1877			PopupMenu popupMenu = new PopupMenu(getActivity(), view);
1878			popupMenu.inflate(R.menu.block);
1879			popupMenu.setOnMenuItemClickListener(menuItem -> {
1880				Blockable blockable;
1881				switch (menuItem.getItemId()) {
1882					case R.id.block_domain:
1883						blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
1884						break;
1885					default:
1886						blockable = conversation;
1887				}
1888				BlockContactDialog.show(activity, blockable);
1889				return true;
1890			});
1891			popupMenu.show();
1892		}
1893		return true;
1894	}
1895
1896	private void updateSnackBar(final Conversation conversation) {
1897		final Account account = conversation.getAccount();
1898		final XmppConnection connection = account.getXmppConnection();
1899		final int mode = conversation.getMode();
1900		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1901		if (account.getStatus() == Account.State.DISABLED) {
1902			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1903		} else if (conversation.isBlocked()) {
1904			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1905		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1906			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1907		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1908			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1909		} else if (mode == Conversation.MODE_MULTI
1910				&& !conversation.getMucOptions().online()
1911				&& account.getStatus() == Account.State.ONLINE) {
1912			switch (conversation.getMucOptions().getError()) {
1913				case NICK_IN_USE:
1914					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1915					break;
1916				case NO_RESPONSE:
1917					showSnackbar(R.string.joining_conference, 0, null);
1918					break;
1919				case SERVER_NOT_FOUND:
1920					if (conversation.receivedMessagesCount() > 0) {
1921						showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
1922					} else {
1923						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1924					}
1925					break;
1926				case PASSWORD_REQUIRED:
1927					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1928					break;
1929				case BANNED:
1930					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1931					break;
1932				case MEMBERS_ONLY:
1933					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1934					break;
1935				case KICKED:
1936					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1937					break;
1938				case UNKNOWN:
1939					showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
1940					break;
1941				case INVALID_NICK:
1942					showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
1943				case SHUTDOWN:
1944					showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
1945					break;
1946				default:
1947					hideSnackbar();
1948					break;
1949			}
1950		} else if (account.hasPendingPgpIntent(conversation)) {
1951			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1952		} else if (connection != null
1953				&& connection.getFeatures().blocking()
1954				&& conversation.countMessages() != 0
1955				&& !conversation.isBlocked()
1956				&& conversation.isWithStranger()) {
1957			showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
1958		} else {
1959			hideSnackbar();
1960		}
1961	}
1962
1963	@Override
1964	public void refresh() {
1965		if (this.binding == null) {
1966			Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
1967			return;
1968		}
1969		this.refresh(true);
1970	}
1971
1972	private void refresh(boolean notifyConversationRead) {
1973		synchronized (this.messageList) {
1974			if (this.conversation != null) {
1975				conversation.populateWithMessages(this.messageList);
1976				updateSnackBar(conversation);
1977				updateStatusMessages();
1978				this.messageListAdapter.notifyDataSetChanged();
1979				updateChatMsgHint();
1980				if (notifyConversationRead && activity != null) {
1981					activity.onConversationRead(this.conversation);
1982				}
1983				updateSendButton();
1984				updateEditablity();
1985			}
1986		}
1987	}
1988
1989	protected void messageSent() {
1990		mSendingPgpMessage.set(false);
1991		this.binding.textinput.setText("");
1992		if (conversation.setCorrectingMessage(null)) {
1993			this.binding.textinput.append(conversation.getDraftMessage());
1994			conversation.setDraftMessage(null);
1995		}
1996		if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
1997			activity.xmppConnectionService.updateConversation(conversation);
1998		}
1999		updateChatMsgHint();
2000		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2001		final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2002		if (prefScrollToBottom || scrolledToBottom()) {
2003			new Handler().post(() -> {
2004				int size = messageList.size();
2005				this.binding.messagesView.setSelection(size - 1);
2006			});
2007		}
2008	}
2009
2010	public void setFocusOnInputField() {
2011		this.binding.textinput.requestFocus();
2012	}
2013
2014	public void doneSendingPgpMessage() {
2015		mSendingPgpMessage.set(false);
2016	}
2017
2018	public long getMaxHttpUploadSize(Conversation conversation) {
2019		final XmppConnection connection = conversation.getAccount().getXmppConnection();
2020		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2021	}
2022
2023	private void updateEditablity() {
2024		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2025		this.binding.textinput.setFocusable(canWrite);
2026		this.binding.textinput.setFocusableInTouchMode(canWrite);
2027		this.binding.textSendButton.setEnabled(canWrite);
2028		this.binding.textinput.setCursorVisible(canWrite);
2029	}
2030
2031	public void updateSendButton() {
2032		boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2033		final Conversation c = this.conversation;
2034		final Presence.Status status;
2035		final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2036		final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
2037		if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2038			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2039				status = Presence.Status.OFFLINE;
2040			} else if (c.getMode() == Conversation.MODE_SINGLE) {
2041				status = c.getContact().getShownStatus();
2042			} else {
2043				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2044			}
2045		} else {
2046			status = Presence.Status.OFFLINE;
2047		}
2048		this.binding.textSendButton.setTag(action);
2049		this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2050	}
2051
2052	protected void updateDateSeparators() {
2053		synchronized (this.messageList) {
2054			for (int i = 0; i < this.messageList.size(); ++i) {
2055				final Message current = this.messageList.get(i);
2056				if (i == 0 || !UIHelper.sameDay(this.messageList.get(i - 1).getTimeSent(), current.getTimeSent())) {
2057					this.messageList.add(i, Message.createDateSeparator(current));
2058					i++;
2059				}
2060			}
2061		}
2062	}
2063
2064	protected void updateStatusMessages() {
2065		updateDateSeparators();
2066		synchronized (this.messageList) {
2067			if (showLoadMoreMessages(conversation)) {
2068				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2069			}
2070			if (conversation.getMode() == Conversation.MODE_SINGLE) {
2071				ChatState state = conversation.getIncomingChatState();
2072				if (state == ChatState.COMPOSING) {
2073					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2074				} else if (state == ChatState.PAUSED) {
2075					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2076				} else {
2077					for (int i = this.messageList.size() - 1; i >= 0; --i) {
2078						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
2079							return;
2080						} else {
2081							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
2082								this.messageList.add(i + 1,
2083										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2084								return;
2085							}
2086						}
2087					}
2088				}
2089			} else {
2090				final MucOptions mucOptions = conversation.getMucOptions();
2091				final List<MucOptions.User> allUsers = mucOptions.getUsers();
2092				final Set<ReadByMarker> addedMarkers = new HashSet<>();
2093				ChatState state = ChatState.COMPOSING;
2094				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2095				if (users.size() == 0) {
2096					state = ChatState.PAUSED;
2097					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2098				}
2099				if (mucOptions.isPrivateAndNonAnonymous()) {
2100					for (int i = this.messageList.size() - 1; i >= 0; --i) {
2101						final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2102						final List<MucOptions.User> shownMarkers = new ArrayList<>();
2103						for (ReadByMarker marker : markersForMessage) {
2104							if (!ReadByMarker.contains(marker, addedMarkers)) {
2105								addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2106								MucOptions.User user = mucOptions.findUser(marker);
2107								if (user != null && !users.contains(user)) {
2108									shownMarkers.add(user);
2109								}
2110							}
2111						}
2112						final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2113						final Message statusMessage;
2114						final int size = shownMarkers.size();
2115						if (size > 1) {
2116							final String body;
2117							if (size <= 4) {
2118								body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2119							} else {
2120								body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2121							}
2122							statusMessage = Message.createStatusMessage(conversation, body);
2123							statusMessage.setCounterparts(shownMarkers);
2124						} else if (size == 1) {
2125							statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2126							statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2127							statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2128						} else {
2129							statusMessage = null;
2130						}
2131						if (statusMessage != null) {
2132							this.messageList.add(i + 1, statusMessage);
2133						}
2134						addedMarkers.add(markerForSender);
2135						if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2136							break;
2137						}
2138					}
2139				}
2140				if (users.size() > 0) {
2141					Message statusMessage;
2142					if (users.size() == 1) {
2143						MucOptions.User user = users.get(0);
2144						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2145						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2146						statusMessage.setTrueCounterpart(user.getRealJid());
2147						statusMessage.setCounterpart(user.getFullJid());
2148					} else {
2149						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2150						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2151						statusMessage.setCounterparts(users);
2152					}
2153					this.messageList.add(statusMessage);
2154				}
2155
2156			}
2157		}
2158	}
2159
2160	public void stopScrolling() {
2161		long now = SystemClock.uptimeMillis();
2162		MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2163		binding.messagesView.dispatchTouchEvent(cancel);
2164	}
2165
2166	private boolean showLoadMoreMessages(final Conversation c) {
2167		final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2168		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2169		return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2170	}
2171
2172	private boolean hasMamSupport(final Conversation c) {
2173		if (c.getMode() == Conversation.MODE_SINGLE) {
2174			final XmppConnection connection = c.getAccount().getXmppConnection();
2175			return connection != null && connection.getFeatures().mam();
2176		} else {
2177			return c.getMucOptions().mamSupport();
2178		}
2179	}
2180
2181	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2182		showSnackbar(message, action, clickListener, null);
2183	}
2184
2185	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2186		this.binding.snackbar.setVisibility(View.VISIBLE);
2187		this.binding.snackbar.setOnClickListener(null);
2188		this.binding.snackbarMessage.setText(message);
2189		this.binding.snackbarMessage.setOnClickListener(null);
2190		this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2191		if (action != 0) {
2192			this.binding.snackbarAction.setText(action);
2193		}
2194		this.binding.snackbarAction.setOnClickListener(clickListener);
2195		this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2196	}
2197
2198	protected void hideSnackbar() {
2199		this.binding.snackbar.setVisibility(View.GONE);
2200	}
2201
2202	protected void sendPlainTextMessage(Message message) {
2203		activity.xmppConnectionService.sendMessage(message);
2204		messageSent();
2205	}
2206
2207	protected void sendPgpMessage(final Message message) {
2208		final XmppConnectionService xmppService = activity.xmppConnectionService;
2209		final Contact contact = message.getConversation().getContact();
2210		if (!activity.hasPgp()) {
2211			activity.showInstallPgpDialog();
2212			return;
2213		}
2214		if (conversation.getAccount().getPgpSignature() == null) {
2215			activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2216			return;
2217		}
2218		if (!mSendingPgpMessage.compareAndSet(false, true)) {
2219			Log.d(Config.LOGTAG, "sending pgp message already in progress");
2220		}
2221		if (conversation.getMode() == Conversation.MODE_SINGLE) {
2222			if (contact.getPgpKeyId() != 0) {
2223				xmppService.getPgpEngine().hasKey(contact,
2224						new UiCallback<Contact>() {
2225
2226							@Override
2227							public void userInputRequried(PendingIntent pi, Contact contact) {
2228								startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2229							}
2230
2231							@Override
2232							public void success(Contact contact) {
2233								encryptTextMessage(message);
2234							}
2235
2236							@Override
2237							public void error(int error, Contact contact) {
2238								activity.runOnUiThread(() -> Toast.makeText(activity,
2239										R.string.unable_to_connect_to_keychain,
2240										Toast.LENGTH_SHORT
2241								).show());
2242								mSendingPgpMessage.set(false);
2243							}
2244						});
2245
2246			} else {
2247				showNoPGPKeyDialog(false, (dialog, which) -> {
2248					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2249					xmppService.updateConversation(conversation);
2250					message.setEncryption(Message.ENCRYPTION_NONE);
2251					xmppService.sendMessage(message);
2252					messageSent();
2253				});
2254			}
2255		} else {
2256			if (conversation.getMucOptions().pgpKeysInUse()) {
2257				if (!conversation.getMucOptions().everybodyHasKeys()) {
2258					Toast warning = Toast
2259							.makeText(getActivity(),
2260									R.string.missing_public_keys,
2261									Toast.LENGTH_LONG);
2262					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2263					warning.show();
2264				}
2265				encryptTextMessage(message);
2266			} else {
2267				showNoPGPKeyDialog(true, (dialog, which) -> {
2268					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2269					message.setEncryption(Message.ENCRYPTION_NONE);
2270					xmppService.updateConversation(conversation);
2271					xmppService.sendMessage(message);
2272					messageSent();
2273				});
2274			}
2275		}
2276	}
2277
2278	public void encryptTextMessage(Message message) {
2279		activity.xmppConnectionService.getPgpEngine().encrypt(message,
2280				new UiCallback<Message>() {
2281
2282					@Override
2283					public void userInputRequried(PendingIntent pi, Message message) {
2284						startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2285					}
2286
2287					@Override
2288					public void success(Message message) {
2289						//TODO the following two call can be made before the callback
2290						getActivity().runOnUiThread(() -> messageSent());
2291					}
2292
2293					@Override
2294					public void error(final int error, Message message) {
2295						getActivity().runOnUiThread(() -> {
2296							doneSendingPgpMessage();
2297							Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2298						});
2299
2300					}
2301				});
2302	}
2303
2304	public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2305		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2306		builder.setIconAttribute(android.R.attr.alertDialogIcon);
2307		if (plural) {
2308			builder.setTitle(getString(R.string.no_pgp_keys));
2309			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2310		} else {
2311			builder.setTitle(getString(R.string.no_pgp_key));
2312			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2313		}
2314		builder.setNegativeButton(getString(R.string.cancel), null);
2315		builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2316		builder.create().show();
2317	}
2318
2319	protected void sendAxolotlMessage(final Message message) {
2320		activity.xmppConnectionService.sendMessage(message);
2321		messageSent();
2322	}
2323
2324	public void appendText(String text) {
2325		if (text == null) {
2326			return;
2327		}
2328		String previous = this.binding.textinput.getText().toString();
2329		if (previous.length() != 0 && !previous.endsWith(" ")) {
2330			text = " " + text;
2331		}
2332		this.binding.textinput.append(text);
2333	}
2334
2335	@Override
2336	public boolean onEnterPressed() {
2337		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2338		final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2339		if (enterIsSend) {
2340			sendMessage();
2341			return true;
2342		} else {
2343			return false;
2344		}
2345	}
2346
2347	@Override
2348	public void onTypingStarted() {
2349		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2350		if (service == null) {
2351			return;
2352		}
2353		Account.State status = conversation.getAccount().getStatus();
2354		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2355			service.sendChatState(conversation);
2356		}
2357		updateSendButton();
2358	}
2359
2360	@Override
2361	public void onTypingStopped() {
2362		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2363		if (service == null) {
2364			return;
2365		}
2366		Account.State status = conversation.getAccount().getStatus();
2367		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2368			service.sendChatState(conversation);
2369		}
2370	}
2371
2372	@Override
2373	public void onTextDeleted() {
2374		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2375		if (service == null) {
2376			return;
2377		}
2378		Account.State status = conversation.getAccount().getStatus();
2379		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2380			service.sendChatState(conversation);
2381		}
2382		updateSendButton();
2383	}
2384
2385	@Override
2386	public void onTextChanged() {
2387		if (conversation != null && conversation.getCorrectingMessage() != null) {
2388			updateSendButton();
2389		}
2390	}
2391
2392	@Override
2393	public boolean onTabPressed(boolean repeated) {
2394		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2395			return false;
2396		}
2397		if (repeated) {
2398			completionIndex++;
2399		} else {
2400			lastCompletionLength = 0;
2401			completionIndex = 0;
2402			final String content = this.binding.textinput.getText().toString();
2403			lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2404			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2405			firstWord = start == 0;
2406			incomplete = content.substring(start, lastCompletionCursor);
2407		}
2408		List<String> completions = new ArrayList<>();
2409		for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2410			String name = user.getName();
2411			if (name != null && name.startsWith(incomplete)) {
2412				completions.add(name + (firstWord ? ": " : " "));
2413			}
2414		}
2415		Collections.sort(completions);
2416		if (completions.size() > completionIndex) {
2417			String completion = completions.get(completionIndex).substring(incomplete.length());
2418			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2419			this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2420			lastCompletionLength = completion.length();
2421		} else {
2422			completionIndex = -1;
2423			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2424			lastCompletionLength = 0;
2425		}
2426		return true;
2427	}
2428
2429	private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2430		try {
2431			getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2432		} catch (final SendIntentException ignored) {
2433		}
2434	}
2435
2436	@Override
2437	public void onBackendConnected() {
2438		Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2439		String uuid = pendingConversationsUuid.pop();
2440		if (uuid != null) {
2441			Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2442			if (conversation == null) {
2443				Log.d(Config.LOGTAG, "unable to restore activity");
2444				clearPending();
2445				return;
2446			}
2447			reInit(conversation);
2448			ScrollState scrollState = pendingScrollState.pop();
2449			if (scrollState != null) {
2450				setScrollPosition(scrollState);
2451			}
2452		}
2453		ActivityResult activityResult = postponedActivityResult.pop();
2454		if (activityResult != null) {
2455			handleActivityResult(activityResult);
2456		}
2457		clearPending();
2458	}
2459
2460	private void clearPending() {
2461		if (postponedActivityResult.pop() != null) {
2462			Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2463		}
2464		pendingScrollState.pop();
2465		if (pendingTakePhotoUri.pop() != null) {
2466			Log.e(Config.LOGTAG, "cleared pending photo uri");
2467		}
2468	}
2469
2470	public Conversation getConversation() {
2471		return conversation;
2472	}
2473}