ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import android.app.Activity;
   4import android.app.AlertDialog;
   5import android.app.Fragment;
   6import android.app.PendingIntent;
   7import android.content.ActivityNotFoundException;
   8import android.content.Context;
   9import android.content.DialogInterface;
  10import android.content.Intent;
  11import android.content.IntentSender.SendIntentException;
  12import android.os.Bundle;
  13import android.os.Handler;
  14import android.support.v13.view.inputmethod.InputConnectionCompat;
  15import android.support.v13.view.inputmethod.InputContentInfoCompat;
  16import android.text.Editable;
  17import android.text.InputType;
  18import android.util.Log;
  19import android.util.Pair;
  20import android.view.ContextMenu;
  21import android.view.ContextMenu.ContextMenuInfo;
  22import android.view.Gravity;
  23import android.view.KeyEvent;
  24import android.view.LayoutInflater;
  25import android.view.MenuItem;
  26import android.view.View;
  27import android.view.View.OnClickListener;
  28import android.view.ViewGroup;
  29import android.view.inputmethod.EditorInfo;
  30import android.view.inputmethod.InputMethodManager;
  31import android.widget.AbsListView;
  32import android.widget.AbsListView.OnScrollListener;
  33import android.widget.AdapterView;
  34import android.widget.AdapterView.AdapterContextMenuInfo;
  35import android.widget.ImageButton;
  36import android.widget.ListView;
  37import android.widget.PopupMenu;
  38import android.widget.RelativeLayout;
  39import android.widget.TextView;
  40import android.widget.TextView.OnEditorActionListener;
  41import android.widget.Toast;
  42
  43import net.java.otr4j.session.SessionStatus;
  44
  45import java.util.ArrayList;
  46import java.util.Arrays;
  47import java.util.Collections;
  48import java.util.List;
  49import java.util.UUID;
  50import java.util.concurrent.atomic.AtomicBoolean;
  51
  52import eu.siacs.conversations.Config;
  53import eu.siacs.conversations.R;
  54import eu.siacs.conversations.entities.Account;
  55import eu.siacs.conversations.entities.Blockable;
  56import eu.siacs.conversations.entities.Contact;
  57import eu.siacs.conversations.entities.Conversation;
  58import eu.siacs.conversations.entities.DownloadableFile;
  59import eu.siacs.conversations.entities.Message;
  60import eu.siacs.conversations.entities.MucOptions;
  61import eu.siacs.conversations.entities.Presence;
  62import eu.siacs.conversations.entities.Transferable;
  63import eu.siacs.conversations.entities.TransferablePlaceholder;
  64import eu.siacs.conversations.http.HttpDownloadConnection;
  65import eu.siacs.conversations.persistance.FileBackend;
  66import eu.siacs.conversations.services.MessageArchiveService;
  67import eu.siacs.conversations.services.XmppConnectionService;
  68import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
  69import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
  70import eu.siacs.conversations.ui.adapter.MessageAdapter;
  71import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
  72import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
  73import eu.siacs.conversations.ui.widget.EditMessage;
  74import eu.siacs.conversations.ui.widget.ListSelectionManager;
  75import eu.siacs.conversations.utils.NickValidityChecker;
  76import eu.siacs.conversations.utils.UIHelper;
  77import eu.siacs.conversations.xmpp.XmppConnection;
  78import eu.siacs.conversations.xmpp.chatstate.ChatState;
  79import eu.siacs.conversations.xmpp.jid.Jid;
  80
  81public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
  82
  83	protected Conversation conversation;
  84	private OnClickListener leaveMuc = new OnClickListener() {
  85
  86		@Override
  87		public void onClick(View v) {
  88			activity.endConversation(conversation);
  89		}
  90	};
  91	private OnClickListener joinMuc = new OnClickListener() {
  92
  93		@Override
  94		public void onClick(View v) {
  95			activity.xmppConnectionService.joinMuc(conversation);
  96		}
  97	};
  98	private OnClickListener enterPassword = new OnClickListener() {
  99
 100		@Override
 101		public void onClick(View v) {
 102			MucOptions muc = conversation.getMucOptions();
 103			String password = muc.getPassword();
 104			if (password == null) {
 105				password = "";
 106			}
 107			activity.quickPasswordEdit(password, new OnValueEdited() {
 108
 109				@Override
 110				public void onValueEdited(String value) {
 111					activity.xmppConnectionService.providePasswordForMuc(
 112							conversation, value);
 113				}
 114			});
 115		}
 116	};
 117	protected ListView messagesView;
 118	final protected List<Message> messageList = new ArrayList<>();
 119	protected MessageAdapter messageListAdapter;
 120	private EditMessage mEditMessage;
 121	private ImageButton mSendButton;
 122	private RelativeLayout snackbar;
 123	private TextView snackbarMessage;
 124	private TextView snackbarAction;
 125	private Toast messageLoaderToast;
 126
 127	private OnScrollListener mOnScrollListener = new OnScrollListener() {
 128
 129		@Override
 130		public void onScrollStateChanged(AbsListView view, int scrollState) {
 131			// TODO Auto-generated method stub
 132
 133		}
 134
 135		@Override
 136		public void onScroll(AbsListView view, int firstVisibleItem,
 137							 int visibleItemCount, int totalItemCount) {
 138			synchronized (ConversationFragment.this.messageList) {
 139				if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true,false) && messageList.size() > 0) {
 140					long timestamp;
 141					if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
 142						timestamp = messageList.get(1).getTimeSent();
 143					} else {
 144						timestamp = messageList.get(0).getTimeSent();
 145					}
 146					activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
 147						@Override
 148						public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
 149							if (ConversationFragment.this.conversation != conversation) {
 150								conversation.messagesLoaded.set(true);
 151								return;
 152							}
 153							activity.runOnUiThread(new Runnable() {
 154								@Override
 155								public void run() {
 156									final int oldPosition = messagesView.getFirstVisiblePosition();
 157									Message message = null;
 158									int childPos;
 159									for(childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
 160										message =  messageList.get(oldPosition + childPos);
 161										if (message.getType() != Message.TYPE_STATUS) {
 162											break;
 163										}
 164									}
 165									final String uuid = message != null ? message.getUuid() : null;
 166									View v = messagesView.getChildAt(childPos);
 167									final int pxOffset = (v == null) ? 0 : v.getTop();
 168									ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
 169									try {
 170										updateStatusMessages();
 171									} catch (IllegalStateException e) {
 172										Log.d(Config.LOGTAG,"caught illegal state exception while updating status messages");
 173									}
 174									messageListAdapter.notifyDataSetChanged();
 175									int pos = Math.max(getIndexOf(uuid,messageList),0);
 176									messagesView.setSelectionFromTop(pos, pxOffset);
 177									if (messageLoaderToast != null) {
 178										messageLoaderToast.cancel();
 179									}
 180									conversation.messagesLoaded.set(true);
 181								}
 182							});
 183						}
 184
 185						@Override
 186						public void informUser(final int resId) {
 187
 188							activity.runOnUiThread(new Runnable() {
 189								@Override
 190								public void run() {
 191									if (messageLoaderToast != null) {
 192										messageLoaderToast.cancel();
 193									}
 194									if (ConversationFragment.this.conversation != conversation) {
 195										return;
 196									}
 197									messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
 198									messageLoaderToast.show();
 199								}
 200							});
 201
 202						}
 203					});
 204
 205				}
 206			}
 207		}
 208	};
 209
 210	private int getIndexOf(String uuid, List<Message> messages) {
 211		if (uuid == null) {
 212			return messages.size() - 1;
 213		}
 214		for(int i = 0; i < messages.size(); ++i) {
 215			if (uuid.equals(messages.get(i).getUuid())) {
 216				return i;
 217			} else {
 218				Message next = messages.get(i);
 219				while(next != null && next.wasMergedIntoPrevious()) {
 220					if (uuid.equals(next.getUuid())) {
 221						return i;
 222					}
 223					next = next.next();
 224				}
 225
 226			}
 227		}
 228		return -1;
 229	}
 230
 231	public Pair<Integer,Integer> getScrollPosition() {
 232		if (this.messagesView.getCount() == 0 ||
 233				this.messagesView.getLastVisiblePosition() == this.messagesView.getCount() - 1) {
 234			return null;
 235		} else {
 236			final int pos = messagesView.getFirstVisiblePosition();
 237			final View view = messagesView.getChildAt(0);
 238			if (view == null) {
 239				return null;
 240			} else {
 241				return new Pair<>(pos, view.getTop());
 242			}
 243		}
 244	}
 245
 246	public void setScrollPosition(Pair<Integer,Integer> scrollPosition) {
 247		if (scrollPosition != null) {
 248			this.messagesView.setSelectionFromTop(scrollPosition.first, scrollPosition.second);
 249		}
 250	}
 251
 252	protected OnClickListener clickToDecryptListener = new OnClickListener() {
 253
 254		@Override
 255		public void onClick(View v) {
 256			PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
 257			if (pendingIntent != null) {
 258				try {
 259					activity.startIntentSenderForResult(pendingIntent.getIntentSender(),
 260                            ConversationActivity.REQUEST_DECRYPT_PGP,
 261                            null,
 262                            0,
 263                            0,
 264                            0);
 265				} catch (SendIntentException e) {
 266					Toast.makeText(activity,R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
 267					conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
 268				}
 269			}
 270			updateSnackBar(conversation);
 271		}
 272	};
 273	protected OnClickListener clickToVerify = new OnClickListener() {
 274
 275		@Override
 276		public void onClick(View v) {
 277			activity.verifyOtrSessionDialog(conversation, v);
 278		}
 279	};
 280	private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
 281
 282		@Override
 283		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 284			if (actionId == EditorInfo.IME_ACTION_SEND) {
 285				InputMethodManager imm = (InputMethodManager) v.getContext()
 286						.getSystemService(Context.INPUT_METHOD_SERVICE);
 287				if (imm.isFullscreenMode()) {
 288					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
 289				}
 290				sendMessage();
 291				return true;
 292			} else {
 293				return false;
 294			}
 295		}
 296	};
 297	private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
 298		@Override
 299		public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
 300			// try to get permission to read the image, if applicable
 301			if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
 302				try {
 303					inputContentInfo.requestPermission();
 304				} catch (Exception e) {
 305					Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
 306					Toast.makeText(
 307							activity,
 308							activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()),
 309							Toast.LENGTH_LONG
 310					).show();
 311					return false;
 312				}
 313			}
 314			if (activity.hasStoragePermission(ConversationActivity.REQUEST_ADD_EDITOR_CONTENT)) {
 315				activity.attachImageToConversation(inputContentInfo.getContentUri());
 316			} else {
 317				activity.mPendingEditorContent = inputContentInfo.getContentUri();
 318			}
 319			return true;
 320		}
 321	};
 322	private OnClickListener mSendButtonListener = new OnClickListener() {
 323
 324		@Override
 325		public void onClick(View v) {
 326			Object tag = v.getTag();
 327			if (tag instanceof SendButtonAction) {
 328				SendButtonAction action = (SendButtonAction) tag;
 329				switch (action) {
 330					case TAKE_PHOTO:
 331						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
 332						break;
 333					case RECORD_VIDEO:
 334						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VIDEO);
 335						break;
 336					case SEND_LOCATION:
 337						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
 338						break;
 339					case RECORD_VOICE:
 340						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
 341						break;
 342					case CHOOSE_PICTURE:
 343						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 344						break;
 345					case CANCEL:
 346						if (conversation != null) {
 347							if(conversation.setCorrectingMessage(null)) {
 348								mEditMessage.setText("");
 349								mEditMessage.append(conversation.getDraftMessage());
 350								conversation.setDraftMessage(null);
 351							} else if (conversation.getMode() == Conversation.MODE_MULTI) {
 352								conversation.setNextCounterpart(null);
 353							}
 354							updateChatMsgHint();
 355							updateSendButton();
 356							updateEditablity();
 357						}
 358						break;
 359					default:
 360						sendMessage();
 361				}
 362			} else {
 363				sendMessage();
 364			}
 365		}
 366	};
 367	private OnClickListener clickToMuc = new OnClickListener() {
 368
 369		@Override
 370		public void onClick(View v) {
 371			Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
 372			intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 373			intent.putExtra("uuid", conversation.getUuid());
 374			startActivity(intent);
 375		}
 376	};
 377	private ConversationActivity activity;
 378	private Message selectedMessage;
 379
 380	private void sendMessage() {
 381		final String body = mEditMessage.getText().toString();
 382		final Conversation conversation = this.conversation;
 383		if (body.length() == 0 || conversation == null) {
 384			return;
 385		}
 386		final Message message;
 387		if (conversation.getCorrectingMessage() == null) {
 388			message = new Message(conversation, body, conversation.getNextEncryption());
 389			if (conversation.getMode() == Conversation.MODE_MULTI) {
 390				if (conversation.getNextCounterpart() != null) {
 391					message.setCounterpart(conversation.getNextCounterpart());
 392					message.setType(Message.TYPE_PRIVATE);
 393				}
 394			}
 395		} else {
 396			message = conversation.getCorrectingMessage();
 397			message.setBody(body);
 398			message.setEdited(message.getUuid());
 399			message.setUuid(UUID.randomUUID().toString());
 400		}
 401		switch (message.getConversation().getNextEncryption()) {
 402			case Message.ENCRYPTION_OTR:
 403				sendOtrMessage(message);
 404				break;
 405			case Message.ENCRYPTION_PGP:
 406				sendPgpMessage(message);
 407				break;
 408			case Message.ENCRYPTION_AXOLOTL:
 409				if(!activity.trustKeysIfNeeded(ConversationActivity.REQUEST_TRUST_KEYS_TEXT)) {
 410					sendAxolotlMessage(message);
 411				}
 412				break;
 413			default:
 414				sendPlainTextMessage(message);
 415		}
 416	}
 417
 418	public void updateChatMsgHint() {
 419		final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
 420		if (conversation.getCorrectingMessage() != null) {
 421			this.mEditMessage.setHint(R.string.send_corrected_message);
 422		} else if (multi && conversation.getNextCounterpart() != null) {
 423			this.mEditMessage.setHint(getString(
 424					R.string.send_private_message_to,
 425					conversation.getNextCounterpart().getResourcepart()));
 426		} else if (multi && !conversation.getMucOptions().participating()) {
 427			this.mEditMessage.setHint(R.string.you_are_not_participating);
 428		} else {
 429			this.mEditMessage.setHint(UIHelper.getMessageHint(activity,conversation));
 430			getActivity().invalidateOptionsMenu();
 431		}
 432	}
 433
 434	public void setupIme() {
 435		if (activity != null) {
 436			if (activity.usingEnterKey() && activity.enterIsSend()) {
 437				mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_FLAG_MULTI_LINE));
 438				mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
 439			} else if (activity.usingEnterKey()) {
 440				mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
 441				mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
 442			} else {
 443				mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
 444				mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
 445			}
 446		}
 447	}
 448
 449	@Override
 450	public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 451		final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
 452		view.setOnClickListener(null);
 453
 454		mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
 455		mEditMessage.setOnClickListener(new OnClickListener() {
 456
 457			@Override
 458			public void onClick(View v) {
 459				if (activity != null) {
 460					activity.hideConversationsOverview();
 461				}
 462			}
 463		});
 464
 465		mEditMessage.setOnEditorActionListener(mEditorActionListener);
 466		mEditMessage.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
 467
 468		mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
 469		mSendButton.setOnClickListener(this.mSendButtonListener);
 470
 471		snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
 472		snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
 473		snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
 474
 475		messagesView = (ListView) view.findViewById(R.id.messages_view);
 476		messagesView.setOnScrollListener(mOnScrollListener);
 477		messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
 478		messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
 479		messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
 480
 481			@Override
 482			public void onContactPictureClicked(Message message) {
 483				if (message.getStatus() <= Message.STATUS_RECEIVED) {
 484					if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 485						Jid user = message.getCounterpart();
 486						if (user != null && !user.isBareJid()) {
 487							if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
 488								Toast.makeText(activity,activity.getString(R.string.user_has_left_conference,user.getResourcepart()),Toast.LENGTH_SHORT).show();
 489							}
 490							highlightInConference(user.getResourcepart());
 491						}
 492					} else {
 493						if (!message.getContact().isSelf()) {
 494							String fingerprint;
 495							if (message.getEncryption() == Message.ENCRYPTION_PGP
 496									|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 497								fingerprint = "pgp";
 498							} else {
 499								fingerprint = message.getFingerprint();
 500							}
 501							activity.switchToContactDetails(message.getContact(), fingerprint);
 502						}
 503					}
 504				} else {
 505					Account account = message.getConversation().getAccount();
 506					Intent intent;
 507					if (activity.manuallyChangePresence()) {
 508						intent = new Intent(activity, SetPresenceActivity.class);
 509						intent.putExtra(SetPresenceActivity.EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
 510					} else {
 511						intent = new Intent(activity, EditAccountActivity.class);
 512						intent.putExtra("jid", account.getJid().toBareJid().toString());
 513						String fingerprint;
 514						if (message.getEncryption() == Message.ENCRYPTION_PGP
 515								|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 516							fingerprint = "pgp";
 517						} else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 518							fingerprint = "otr";
 519						} else {
 520							fingerprint = message.getFingerprint();
 521						}
 522						intent.putExtra("fingerprint", fingerprint);
 523					}
 524					startActivity(intent);
 525				}
 526			}
 527		});
 528		messageListAdapter
 529				.setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
 530
 531					@Override
 532					public void onContactPictureLongClicked(Message message) {
 533						if (message.getStatus() <= Message.STATUS_RECEIVED) {
 534							if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 535								Jid user = message.getCounterpart();
 536								if (user != null && !user.isBareJid()) {
 537									if (message.getConversation().getMucOptions().isUserInRoom(user)) {
 538										privateMessageWith(user);
 539									} else {
 540										Toast.makeText(activity, activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
 541									}
 542								}
 543							}
 544						} else {
 545							activity.showQrCode();
 546						}
 547					}
 548				});
 549		messageListAdapter.setOnQuoteListener(new MessageAdapter.OnQuoteListener() {
 550
 551			@Override
 552			public void onQuote(String text) {
 553				if (mEditMessage.isEnabled()) {
 554					text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
 555					Editable editable = mEditMessage.getEditableText();
 556					int position = mEditMessage.getSelectionEnd();
 557					if (position == -1) position = editable.length();
 558					if (position > 0 && editable.charAt(position - 1) != '\n') {
 559						editable.insert(position++, "\n");
 560					}
 561					editable.insert(position, text);
 562					position += text.length();
 563					editable.insert(position++, "\n");
 564					if (position < editable.length() && editable.charAt(position) != '\n') {
 565						editable.insert(position, "\n");
 566					}
 567					mEditMessage.setSelection(position);
 568					mEditMessage.requestFocus();
 569					InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
 570							.getSystemService(Context.INPUT_METHOD_SERVICE);
 571					if (inputMethodManager != null) {
 572						inputMethodManager.showSoftInput(mEditMessage, InputMethodManager.SHOW_IMPLICIT);
 573					}
 574				}
 575			}
 576		});
 577		messagesView.setAdapter(messageListAdapter);
 578
 579		registerForContextMenu(messagesView);
 580
 581		return view;
 582	}
 583
 584	@Override
 585	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
 586		synchronized (this.messageList) {
 587			super.onCreateContextMenu(menu, v, menuInfo);
 588			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
 589			this.selectedMessage = this.messageList.get(acmi.position);
 590			populateContextMenu(menu);
 591		}
 592	}
 593
 594	private void populateContextMenu(ContextMenu menu) {
 595		final Message m = this.selectedMessage;
 596		final Transferable t = m.getTransferable();
 597		Message relevantForCorrection = m;
 598		while(relevantForCorrection.mergeable(relevantForCorrection.next())) {
 599			relevantForCorrection = relevantForCorrection.next();
 600		}
 601		if (m.getType() != Message.TYPE_STATUS) {
 602			final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
 603					&& m.getType() != Message.TYPE_PRIVATE
 604					&& t == null;
 605			activity.getMenuInflater().inflate(R.menu.message_context, menu);
 606			menu.setHeaderTitle(R.string.message_options);
 607			MenuItem selectText = menu.findItem(R.id.select_text);
 608			MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
 609			MenuItem correctMessage = menu.findItem(R.id.correct_message);
 610			MenuItem shareWith = menu.findItem(R.id.share_with);
 611			MenuItem sendAgain = menu.findItem(R.id.send_again);
 612			MenuItem copyUrl = menu.findItem(R.id.copy_url);
 613			MenuItem downloadFile = menu.findItem(R.id.download_file);
 614			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
 615			MenuItem deleteFile = menu.findItem(R.id.delete_file);
 616			MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
 617			if (!treatAsFile && !m.isGeoUri() && !m.treatAsDownloadable()) {
 618				selectText.setVisible(ListSelectionManager.isSupported());
 619			}
 620			if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
 621				retryDecryption.setVisible(true);
 622			}
 623			if (relevantForCorrection.getType() == Message.TYPE_TEXT
 624					&& relevantForCorrection.isLastCorrectableMessage()
 625					&& (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
 626				correctMessage.setVisible(true);
 627			}
 628			if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
 629				shareWith.setVisible(true);
 630			}
 631			if (m.getStatus() == Message.STATUS_SEND_FAILED) {
 632				sendAgain.setVisible(true);
 633			}
 634			if (m.hasFileOnRemoteHost()
 635					|| m.isGeoUri()
 636					|| m.treatAsDownloadable()
 637					|| (t != null && t instanceof HttpDownloadConnection)) {
 638				copyUrl.setVisible(true);
 639			}
 640			if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
 641				downloadFile.setVisible(true);
 642				downloadFile.setTitle(activity.getString(R.string.download_x_file,UIHelper.getFileDescriptionString(activity, m)));
 643			}
 644			boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
 645					|| m.getStatus() == Message.STATUS_UNSEND
 646					|| m.getStatus() == Message.STATUS_OFFERED;
 647			if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
 648				cancelTransmission.setVisible(true);
 649			}
 650			if (treatAsFile) {
 651				String path = m.getRelativeFilePath();
 652				if (path == null || !path.startsWith("/")) {
 653					deleteFile.setVisible(true);
 654					deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
 655				}
 656			}
 657			if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
 658				showErrorMessage.setVisible(true);
 659			}
 660		}
 661	}
 662
 663	@Override
 664	public boolean onContextItemSelected(MenuItem item) {
 665		switch (item.getItemId()) {
 666			case R.id.share_with:
 667				shareWith(selectedMessage);
 668				return true;
 669			case R.id.select_text:
 670				selectText(selectedMessage);
 671				return true;
 672			case R.id.correct_message:
 673				correctMessage(selectedMessage);
 674				return true;
 675			case R.id.send_again:
 676				resendMessage(selectedMessage);
 677				return true;
 678			case R.id.copy_url:
 679				copyUrl(selectedMessage);
 680				return true;
 681			case R.id.download_file:
 682				downloadFile(selectedMessage);
 683				return true;
 684			case R.id.cancel_transmission:
 685				cancelTransmission(selectedMessage);
 686				return true;
 687			case R.id.retry_decryption:
 688				retryDecryption(selectedMessage);
 689				return true;
 690			case R.id.delete_file:
 691				deleteFile(selectedMessage);
 692				return true;
 693			case R.id.show_error_message:
 694				showErrorMessage(selectedMessage);
 695				return true;
 696			default:
 697				return super.onContextItemSelected(item);
 698		}
 699	}
 700
 701	private void showErrorMessage(final Message message) {
 702		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
 703		builder.setTitle(R.string.error_message);
 704		builder.setMessage(message.getErrorMessage());
 705		builder.setPositiveButton(R.string.confirm,null);
 706		builder.create().show();
 707	}
 708
 709	private void shareWith(Message message) {
 710		Intent shareIntent = new Intent();
 711		shareIntent.setAction(Intent.ACTION_SEND);
 712		if (message.isGeoUri()) {
 713			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
 714			shareIntent.setType("text/plain");
 715		} else if (!message.isFileOrImage()) {
 716			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
 717			shareIntent.setType("text/plain");
 718		} else {
 719			final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 720			try {
 721				shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(activity, file));
 722			} catch (SecurityException e) {
 723				Toast.makeText(activity, activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
 724				return;
 725			}
 726			shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 727			String mime = message.getMimeType();
 728			if (mime == null) {
 729				mime = "*/*";
 730			}
 731			shareIntent.setType(mime);
 732		}
 733		try {
 734			activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
 735		} catch (ActivityNotFoundException e) {
 736			//This should happen only on faulty androids because normally chooser is always available
 737			Toast.makeText(activity,R.string.no_application_found_to_open_file,Toast.LENGTH_SHORT).show();
 738		}
 739	}
 740
 741	private void selectText(Message message) {
 742		final int index;
 743		synchronized (this.messageList) {
 744			index = this.messageList.indexOf(message);
 745		}
 746		if (index >= 0) {
 747			final int first = this.messagesView.getFirstVisiblePosition();
 748			final int last = first + this.messagesView.getChildCount();
 749			if (index >= first && index < last)	{
 750				final View view = this.messagesView.getChildAt(index - first);
 751				final TextView messageBody = this.messageListAdapter.getMessageBody(view);
 752				if (messageBody != null) {
 753					ListSelectionManager.startSelection(messageBody);
 754				}
 755			}
 756		}
 757	}
 758
 759	private void deleteFile(Message message) {
 760		if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
 761			message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 762			activity.updateConversationList();
 763			updateMessages();
 764		}
 765	}
 766
 767	private void resendMessage(final Message message) {
 768		if (message.isFileOrImage()) {
 769			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 770			if (file.exists()) {
 771				final Conversation conversation = message.getConversation();
 772				final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
 773				if (!message.hasFileOnRemoteHost()
 774						&& xmppConnection != null
 775						&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
 776					activity.selectPresence(conversation, new OnPresenceSelected() {
 777						@Override
 778						public void onPresenceSelected() {
 779							message.setCounterpart(conversation.getNextCounterpart());
 780							activity.xmppConnectionService.resendFailedMessages(message);
 781						}
 782					});
 783					return;
 784				}
 785			} else {
 786				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
 787				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 788				activity.updateConversationList();
 789				updateMessages();
 790				return;
 791			}
 792		}
 793		activity.xmppConnectionService.resendFailedMessages(message);
 794	}
 795
 796	private void copyUrl(Message message) {
 797		final String url;
 798		final int resId;
 799		if (message.isGeoUri()) {
 800			resId = R.string.location;
 801			url = message.getBody();
 802		} else if (message.hasFileOnRemoteHost()) {
 803			resId = R.string.file_url;
 804			url = message.getFileParams().url.toString();
 805		} else {
 806			url = message.getBody().trim();
 807			resId = R.string.file_url;
 808		}
 809		if (activity.copyTextToClipboard(url, resId)) {
 810			Toast.makeText(activity, R.string.url_copied_to_clipboard,
 811					Toast.LENGTH_SHORT).show();
 812		}
 813	}
 814
 815	private void downloadFile(Message message) {
 816		activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message,true);
 817	}
 818
 819	private void cancelTransmission(Message message) {
 820		Transferable transferable = message.getTransferable();
 821		if (transferable != null) {
 822			transferable.cancel();
 823		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
 824			activity.xmppConnectionService.markMessage(message,Message.STATUS_SEND_FAILED);
 825		}
 826	}
 827
 828	private void retryDecryption(Message message) {
 829		message.setEncryption(Message.ENCRYPTION_PGP);
 830		activity.updateConversationList();
 831		updateMessages();
 832		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
 833	}
 834
 835	protected void privateMessageWith(final Jid counterpart) {
 836		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 837			activity.xmppConnectionService.sendChatState(conversation);
 838		}
 839		this.mEditMessage.setText("");
 840		this.conversation.setNextCounterpart(counterpart);
 841		updateChatMsgHint();
 842		updateSendButton();
 843		updateEditablity();
 844	}
 845
 846	private void correctMessage(Message message) {
 847		while(message.mergeable(message.next())) {
 848			message = message.next();
 849		}
 850		this.conversation.setCorrectingMessage(message);
 851		final Editable editable = mEditMessage.getText();
 852		this.conversation.setDraftMessage(editable.toString());
 853		this.mEditMessage.setText("");
 854		this.mEditMessage.append(message.getBody());
 855
 856	}
 857
 858	protected void highlightInConference(String nick) {
 859		final Editable editable = mEditMessage.getText();
 860		String oldString = editable.toString().trim();
 861		final int pos = mEditMessage.getSelectionStart();
 862		if (oldString.isEmpty() || pos == 0) {
 863			editable.insert(0, nick + ": ");
 864		} else {
 865			final char before = editable.charAt(pos - 1);
 866			final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
 867			if (before == '\n') {
 868				editable.insert(pos, nick + ": ");
 869			} else {
 870				if (pos > 2 && editable.subSequence(pos-2,pos).toString().equals(": ")) {
 871					if (NickValidityChecker.check(conversation,Arrays.asList(editable.subSequence(0,pos-2).toString().split(", ")))) {
 872						editable.insert(pos - 2, ", " + nick);
 873						return;
 874					}
 875				}
 876				editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
 877				if (Character.isWhitespace(after)) {
 878					mEditMessage.setSelection(mEditMessage.getSelectionStart() + 1);
 879				}
 880			}
 881		}
 882	}
 883
 884	@Override
 885	public void onStop() {
 886		super.onStop();
 887		if (activity == null || !activity.isChangingConfigurations()) {
 888			messageListAdapter.stopAudioPlayer();
 889		}
 890		if (this.conversation != null) {
 891			final String msg = mEditMessage.getText().toString();
 892			this.conversation.setNextMessage(msg);
 893			updateChatState(this.conversation, msg);
 894		}
 895	}
 896
 897	private void updateChatState(final Conversation conversation, final String msg) {
 898		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
 899		Account.State status = conversation.getAccount().getStatus();
 900		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
 901			activity.xmppConnectionService.sendChatState(conversation);
 902		}
 903	}
 904
 905	public boolean reInit(Conversation conversation) {
 906		if (conversation == null) {
 907			return false;
 908		}
 909		this.activity = (ConversationActivity) getActivity();
 910		setupIme();
 911		if (this.conversation != null) {
 912			final String msg = mEditMessage.getText().toString();
 913			this.conversation.setNextMessage(msg);
 914			if (this.conversation != conversation) {
 915				updateChatState(this.conversation, msg);
 916				messageListAdapter.stopAudioPlayer();
 917			}
 918			this.conversation.trim();
 919
 920		}
 921
 922		if (activity != null) {
 923			this.mSendButton.setContentDescription(activity.getString(R.string.send_message_to_x,conversation.getName()));
 924		}
 925
 926		this.conversation = conversation;
 927		this.mEditMessage.setKeyboardListener(null);
 928		this.mEditMessage.setText("");
 929		this.mEditMessage.append(this.conversation.getNextMessage());
 930		this.mEditMessage.setKeyboardListener(this);
 931		messageListAdapter.updatePreferences();
 932		this.messagesView.setAdapter(messageListAdapter);
 933		updateMessages();
 934		this.conversation.messagesLoaded.set(true);
 935		synchronized (this.messageList) {
 936			final Message first = conversation.getFirstUnreadMessage();
 937			final int bottom = Math.max(0, this.messageList.size() - 1);
 938			final int pos;
 939			if (first == null) {
 940				pos = bottom;
 941			} else {
 942				int i = getIndexOf(first.getUuid(), this.messageList);
 943				pos = i < 0 ? bottom : i;
 944			}
 945			messagesView.setSelection(pos);
 946			return pos == bottom;
 947		}
 948	}
 949
 950	private OnClickListener mEnableAccountListener = new OnClickListener() {
 951		@Override
 952		public void onClick(View v) {
 953			final Account account = conversation == null ? null : conversation.getAccount();
 954			if (account != null) {
 955				account.setOption(Account.OPTION_DISABLED, false);
 956				activity.xmppConnectionService.updateAccount(account);
 957			}
 958		}
 959	};
 960
 961	private OnClickListener mUnblockClickListener = new OnClickListener() {
 962		@Override
 963		public void onClick(final View v) {
 964			v.post(new Runnable() {
 965				@Override
 966				public void run() {
 967					v.setVisibility(View.INVISIBLE);
 968				}
 969			});
 970			if (conversation.isDomainBlocked()) {
 971				BlockContactDialog.show(activity, conversation);
 972			} else {
 973				activity.unblockConversation(conversation);
 974			}
 975		}
 976	};
 977
 978	private void showBlockSubmenu(View view) {
 979		final Jid jid = conversation.getJid();
 980			if (jid.isDomainJid()) {
 981				BlockContactDialog.show(activity, conversation);
 982			} else {
 983				PopupMenu popupMenu = new PopupMenu(activity, view);
 984				popupMenu.inflate(R.menu.block);
 985				popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
 986					@Override
 987					public boolean onMenuItemClick(MenuItem menuItem) {
 988						Blockable blockable;
 989						switch (menuItem.getItemId()) {
 990							case R.id.block_domain:
 991								blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
 992								break;
 993							default:
 994								blockable = conversation;
 995						}
 996						BlockContactDialog.show(activity, blockable);
 997						return true;
 998					}
 999				});
1000				popupMenu.show();
1001			}
1002	}
1003
1004	private OnClickListener mBlockClickListener = new OnClickListener() {
1005		@Override
1006		public void onClick(final View view) {
1007			showBlockSubmenu(view);
1008		}
1009	};
1010
1011	private OnClickListener mAddBackClickListener = new OnClickListener() {
1012
1013		@Override
1014		public void onClick(View v) {
1015			final Contact contact = conversation == null ? null : conversation.getContact();
1016			if (contact != null) {
1017				activity.xmppConnectionService.createContact(contact);
1018				activity.switchToContactDetails(contact);
1019			}
1020		}
1021	};
1022
1023	private View.OnLongClickListener mLongPressBlockListener = new View.OnLongClickListener() {
1024		@Override
1025		public boolean onLongClick(View v) {
1026			showBlockSubmenu(v);
1027			return true;
1028		}
1029	};
1030
1031	private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
1032		@Override
1033		public void onClick(View v) {
1034			final Contact contact = conversation == null ? null : conversation.getContact();
1035			if (contact != null) {
1036				activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
1037						activity.xmppConnectionService.getPresenceGenerator()
1038								.sendPresenceUpdatesTo(contact));
1039				hideSnackbar();
1040			}
1041		}
1042	};
1043
1044	private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
1045		@Override
1046		public void onClick(View view) {
1047			Intent intent = new Intent(activity, VerifyOTRActivity.class);
1048			intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
1049			intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
1050			intent.putExtra(VerifyOTRActivity.EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
1051			intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
1052			startActivity(intent);
1053		}
1054	};
1055
1056	private void updateSnackBar(final Conversation conversation) {
1057		final Account account = conversation.getAccount();
1058		final XmppConnection connection = account.getXmppConnection();
1059		final int mode = conversation.getMode();
1060		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1061		if (account.getStatus() == Account.State.DISABLED) {
1062			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1063		} else if (conversation.isBlocked()) {
1064			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1065		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1066			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1067		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1068			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1069		} else if (mode == Conversation.MODE_MULTI
1070				&& !conversation.getMucOptions().online()
1071				&& account.getStatus() == Account.State.ONLINE) {
1072			switch (conversation.getMucOptions().getError()) {
1073				case NICK_IN_USE:
1074					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1075					break;
1076				case NO_RESPONSE:
1077					showSnackbar(R.string.joining_conference, 0, null);
1078					break;
1079				case SERVER_NOT_FOUND:
1080					if (conversation.receivedMessagesCount() > 0) {
1081						showSnackbar(R.string.remote_server_not_found,R.string.try_again, joinMuc);
1082					} else {
1083						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1084					}
1085					break;
1086				case PASSWORD_REQUIRED:
1087					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1088					break;
1089				case BANNED:
1090					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1091					break;
1092				case MEMBERS_ONLY:
1093					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1094					break;
1095				case KICKED:
1096					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1097					break;
1098				case UNKNOWN:
1099					showSnackbar(R.string.conference_unknown_error, R.string.join, joinMuc);
1100					break;
1101				case SHUTDOWN:
1102					showSnackbar(R.string.conference_shutdown, R.string.join, joinMuc);
1103					break;
1104				default:
1105					hideSnackbar();
1106					break;
1107			}
1108		} else if (account.hasPendingPgpIntent(conversation)) {
1109			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1110		} else if (mode == Conversation.MODE_SINGLE
1111				&& conversation.smpRequested()) {
1112			showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
1113		} else if (mode == Conversation.MODE_SINGLE
1114				&& conversation.hasValidOtrSession()
1115				&& (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
1116				&& (!conversation.isOtrFingerprintVerified())) {
1117			showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
1118		} else if (connection != null
1119				&& connection.getFeatures().blocking()
1120				&& conversation.countMessages() != 0
1121				&& !conversation.isBlocked()
1122				&& conversation.isWithStranger()) {
1123			showSnackbar(R.string.received_message_from_stranger,R.string.block, mBlockClickListener);
1124		} else {
1125			hideSnackbar();
1126		}
1127	}
1128
1129	public void updateMessages() {
1130		synchronized (this.messageList) {
1131			if (getView() == null) {
1132				return;
1133			}
1134			final ConversationActivity activity = (ConversationActivity) getActivity();
1135			if (this.conversation != null) {
1136				conversation.populateWithMessages(ConversationFragment.this.messageList);
1137				updateSnackBar(conversation);
1138				updateStatusMessages();
1139				this.messageListAdapter.notifyDataSetChanged();
1140				updateChatMsgHint();
1141				if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
1142					activity.sendReadMarkerIfNecessary(conversation);
1143				}
1144				updateSendButton();
1145				updateEditablity();
1146			}
1147		}
1148	}
1149
1150	protected void messageSent() {
1151		mSendingPgpMessage.set(false);
1152		mEditMessage.setText("");
1153		if (conversation.setCorrectingMessage(null)) {
1154			mEditMessage.append(conversation.getDraftMessage());
1155			conversation.setDraftMessage(null);
1156		}
1157		conversation.setNextMessage(mEditMessage.getText().toString());
1158		updateChatMsgHint();
1159		new Handler().post(new Runnable() {
1160			@Override
1161			public void run() {
1162				int size = messageList.size();
1163				messagesView.setSelection(size - 1);
1164			}
1165		});
1166	}
1167
1168	public void setFocusOnInputField() {
1169		mEditMessage.requestFocus();
1170	}
1171
1172	public void doneSendingPgpMessage() {
1173		mSendingPgpMessage.set(false);
1174	}
1175
1176	enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE, RECORD_VIDEO;
1177
1178		public static SendButtonAction valueOfOrDefault(String setting, SendButtonAction text) {
1179			try {
1180				return valueOf(setting);
1181			} catch (IllegalArgumentException e) {
1182				return TEXT;
1183			}
1184		}
1185	}
1186
1187	private int getSendButtonImageResource(SendButtonAction action, Presence.Status status) {
1188		switch (action) {
1189			case TEXT:
1190				switch (status) {
1191					case CHAT:
1192					case ONLINE:
1193						return R.drawable.ic_send_text_online;
1194					case AWAY:
1195						return R.drawable.ic_send_text_away;
1196					case XA:
1197					case DND:
1198						return R.drawable.ic_send_text_dnd;
1199					default:
1200						return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1201				}
1202			case RECORD_VIDEO:
1203				switch (status) {
1204					case CHAT:
1205					case ONLINE:
1206						return R.drawable.ic_send_videocam_online;
1207					case AWAY:
1208						return R.drawable.ic_send_videocam_away;
1209					case XA:
1210					case DND:
1211						return R.drawable.ic_send_videocam_dnd;
1212					default:
1213						return activity.getThemeResource(R.attr.ic_send_videocam_offline, R.drawable.ic_send_videocam_offline);
1214				}
1215			case TAKE_PHOTO:
1216				switch (status) {
1217					case CHAT:
1218					case ONLINE:
1219						return R.drawable.ic_send_photo_online;
1220					case AWAY:
1221						return R.drawable.ic_send_photo_away;
1222					case XA:
1223					case DND:
1224						return R.drawable.ic_send_photo_dnd;
1225					default:
1226						return activity.getThemeResource(R.attr.ic_send_photo_offline, R.drawable.ic_send_photo_offline);
1227				}
1228			case RECORD_VOICE:
1229				switch (status) {
1230					case CHAT:
1231					case ONLINE:
1232						return R.drawable.ic_send_voice_online;
1233					case AWAY:
1234						return R.drawable.ic_send_voice_away;
1235					case XA:
1236					case DND:
1237						return R.drawable.ic_send_voice_dnd;
1238					default:
1239						return activity.getThemeResource(R.attr.ic_send_voice_offline, R.drawable.ic_send_voice_offline);
1240				}
1241			case SEND_LOCATION:
1242				switch (status) {
1243					case CHAT:
1244					case ONLINE:
1245						return R.drawable.ic_send_location_online;
1246					case AWAY:
1247						return R.drawable.ic_send_location_away;
1248					case XA:
1249					case DND:
1250						return R.drawable.ic_send_location_dnd;
1251					default:
1252						return activity.getThemeResource(R.attr.ic_send_location_offline, R.drawable.ic_send_location_offline);
1253				}
1254			case CANCEL:
1255				switch (status) {
1256					case CHAT:
1257					case ONLINE:
1258						return R.drawable.ic_send_cancel_online;
1259					case AWAY:
1260						return R.drawable.ic_send_cancel_away;
1261					case XA:
1262					case DND:
1263						return R.drawable.ic_send_cancel_dnd;
1264					default:
1265						return activity.getThemeResource(R.attr.ic_send_cancel_offline, R.drawable.ic_send_cancel_offline);
1266				}
1267			case CHOOSE_PICTURE:
1268				switch (status) {
1269					case CHAT:
1270					case ONLINE:
1271						return R.drawable.ic_send_picture_online;
1272					case AWAY:
1273						return R.drawable.ic_send_picture_away;
1274					case XA:
1275					case DND:
1276						return R.drawable.ic_send_picture_dnd;
1277					default:
1278						return activity.getThemeResource(R.attr.ic_send_picture_offline, R.drawable.ic_send_picture_offline);
1279				}
1280		}
1281		return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1282	}
1283
1284	private void updateEditablity() {
1285		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
1286		this.mEditMessage.setFocusable(canWrite);
1287		this.mEditMessage.setFocusableInTouchMode(canWrite);
1288		this.mSendButton.setEnabled(canWrite);
1289		this.mEditMessage.setCursorVisible(canWrite);
1290	}
1291
1292	public void updateSendButton() {
1293		final Conversation c = this.conversation;
1294		final SendButtonAction action;
1295		final Presence.Status status;
1296		final String text = this.mEditMessage == null ? "" : this.mEditMessage.getText().toString();
1297		final boolean empty = text.length() == 0;
1298		final boolean conference = c.getMode() == Conversation.MODE_MULTI;
1299		if (c.getCorrectingMessage() != null && (empty || text.equals(c.getCorrectingMessage().getBody()))) {
1300			action = SendButtonAction.CANCEL;
1301		} else if (conference && !c.getAccount().httpUploadAvailable()) {
1302			if (empty && c.getNextCounterpart() != null) {
1303				action = SendButtonAction.CANCEL;
1304			} else {
1305				action = SendButtonAction.TEXT;
1306			}
1307		} else {
1308			if (empty) {
1309				if (conference && c.getNextCounterpart() != null) {
1310					action = SendButtonAction.CANCEL;
1311				} else {
1312					String setting = activity.getPreferences().getString("quick_action", activity.getResources().getString(R.string.quick_action));
1313					if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
1314						action = SendButtonAction.SEND_LOCATION;
1315					} else {
1316						if (setting.equals("recent")) {
1317							setting = activity.getPreferences().getString(ConversationActivity.RECENTLY_USED_QUICK_ACTION, SendButtonAction.TEXT.toString());
1318							action = SendButtonAction.valueOfOrDefault(setting,SendButtonAction.TEXT);
1319						} else {
1320							action = SendButtonAction.valueOfOrDefault(setting,SendButtonAction.TEXT);
1321						}
1322					}
1323				}
1324			} else {
1325				action = SendButtonAction.TEXT;
1326			}
1327		}
1328		if (activity.useSendButtonToIndicateStatus() && c.getAccount().getStatus() == Account.State.ONLINE) {
1329			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1330				status = Presence.Status.OFFLINE;
1331			} else if (c.getMode() == Conversation.MODE_SINGLE) {
1332				status = c.getContact().getShownStatus();
1333			} else {
1334				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1335			}
1336		} else {
1337			status = Presence.Status.OFFLINE;
1338		}
1339		this.mSendButton.setTag(action);
1340		this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
1341	}
1342
1343	protected void updateDateSeparators() {
1344		synchronized (this.messageList) {
1345			for(int i = 0; i < this.messageList.size(); ++i) {
1346				final Message current = this.messageList.get(i);
1347				if (i == 0 || !UIHelper.sameDay(this.messageList.get(i-1).getTimeSent(),current.getTimeSent())) {
1348					this.messageList.add(i,Message.createDateSeparator(current));
1349					i++;
1350				}
1351			}
1352		}
1353	}
1354
1355	protected void updateStatusMessages() {
1356		updateDateSeparators();
1357		synchronized (this.messageList) {
1358			if (showLoadMoreMessages(conversation)) {
1359				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1360			}
1361			if (conversation.getMode() == Conversation.MODE_SINGLE) {
1362				ChatState state = conversation.getIncomingChatState();
1363				if (state == ChatState.COMPOSING) {
1364					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1365				} else if (state == ChatState.PAUSED) {
1366					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1367				} else {
1368					for (int i = this.messageList.size() - 1; i >= 0; --i) {
1369						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1370							return;
1371						} else {
1372							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1373								this.messageList.add(i + 1,
1374										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1375								return;
1376							}
1377						}
1378					}
1379				}
1380			} else {
1381				ChatState state = ChatState.COMPOSING;
1382				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state,5);
1383				if (users.size() == 0) {
1384					state = ChatState.PAUSED;
1385					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1386
1387				}
1388				if (users.size() > 0) {
1389					Message statusMessage;
1390					if (users.size() == 1) {
1391						MucOptions.User user = users.get(0);
1392						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
1393						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
1394						statusMessage.setTrueCounterpart(user.getRealJid());
1395						statusMessage.setCounterpart(user.getFullJid());
1396					} else {
1397						StringBuilder builder = new StringBuilder();
1398						for(MucOptions.User user : users) {
1399							if (builder.length() != 0) {
1400								builder.append(", ");
1401							}
1402							builder.append(UIHelper.getDisplayName(user));
1403						}
1404						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
1405						statusMessage = Message.createStatusMessage(conversation, getString(id, builder.toString()));
1406					}
1407					this.messageList.add(statusMessage);
1408				}
1409
1410			}
1411		}
1412	}
1413
1414	private boolean showLoadMoreMessages(final Conversation c) {
1415		final boolean mam = hasMamSupport(c);
1416		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1417		return mam && (c.getLastClearHistory().getTimestamp() != 0  || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer()  && !service.queryInProgress(c)));
1418	}
1419
1420	private boolean hasMamSupport(final Conversation c) {
1421		if (c.getMode() == Conversation.MODE_SINGLE) {
1422			final XmppConnection connection = c.getAccount().getXmppConnection();
1423			return connection != null && connection.getFeatures().mam();
1424		} else {
1425			return c.getMucOptions().mamSupport();
1426		}
1427	}
1428
1429	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
1430		showSnackbar(message,action,clickListener,null);
1431	}
1432
1433	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
1434		snackbar.setVisibility(View.VISIBLE);
1435		snackbar.setOnClickListener(null);
1436		snackbarMessage.setText(message);
1437		snackbarMessage.setOnClickListener(null);
1438		snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
1439		if (action != 0) {
1440			snackbarAction.setText(action);
1441		}
1442		snackbarAction.setOnClickListener(clickListener);
1443		snackbarAction.setOnLongClickListener(longClickListener);
1444	}
1445
1446	protected void hideSnackbar() {
1447		snackbar.setVisibility(View.GONE);
1448	}
1449
1450	protected void sendPlainTextMessage(Message message) {
1451		ConversationActivity activity = (ConversationActivity) getActivity();
1452		activity.xmppConnectionService.sendMessage(message);
1453		messageSent();
1454	}
1455
1456	private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
1457
1458	protected void sendPgpMessage(final Message message) {
1459		final ConversationActivity activity = (ConversationActivity) getActivity();
1460		final XmppConnectionService xmppService = activity.xmppConnectionService;
1461		final Contact contact = message.getConversation().getContact();
1462		if (!activity.hasPgp()) {
1463			activity.showInstallPgpDialog();
1464			return;
1465		}
1466		if (conversation.getAccount().getPgpSignature() == null) {
1467			activity.announcePgp(conversation.getAccount(), conversation, activity.onOpenPGPKeyPublished);
1468			return;
1469		}
1470		if (!mSendingPgpMessage.compareAndSet(false,true)) {
1471			Log.d(Config.LOGTAG,"sending pgp message already in progress");
1472		}
1473		if (conversation.getMode() == Conversation.MODE_SINGLE) {
1474			if (contact.getPgpKeyId() != 0) {
1475				xmppService.getPgpEngine().hasKey(contact,
1476						new UiCallback<Contact>() {
1477
1478							@Override
1479							public void userInputRequried(PendingIntent pi,
1480														  Contact contact) {
1481								activity.runIntent(
1482										pi,
1483										ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1484							}
1485
1486							@Override
1487							public void success(Contact contact) {
1488								activity.encryptTextMessage(message);
1489							}
1490
1491							@Override
1492							public void error(int error, Contact contact) {
1493								activity.runOnUiThread(new Runnable() {
1494									@Override
1495									public void run() {
1496										Toast.makeText(activity,
1497												R.string.unable_to_connect_to_keychain,
1498												Toast.LENGTH_SHORT
1499										).show();
1500									}
1501								});
1502								mSendingPgpMessage.set(false);
1503							}
1504						});
1505
1506			} else {
1507				showNoPGPKeyDialog(false,
1508						new DialogInterface.OnClickListener() {
1509
1510							@Override
1511							public void onClick(DialogInterface dialog,
1512												int which) {
1513								conversation
1514										.setNextEncryption(Message.ENCRYPTION_NONE);
1515								xmppService.updateConversation(conversation);
1516								message.setEncryption(Message.ENCRYPTION_NONE);
1517								xmppService.sendMessage(message);
1518								messageSent();
1519							}
1520						});
1521			}
1522		} else {
1523			if (conversation.getMucOptions().pgpKeysInUse()) {
1524				if (!conversation.getMucOptions().everybodyHasKeys()) {
1525					Toast warning = Toast
1526							.makeText(getActivity(),
1527									R.string.missing_public_keys,
1528									Toast.LENGTH_LONG);
1529					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1530					warning.show();
1531				}
1532				activity.encryptTextMessage(message);
1533			} else {
1534				showNoPGPKeyDialog(true,
1535						new DialogInterface.OnClickListener() {
1536
1537							@Override
1538							public void onClick(DialogInterface dialog,
1539												int which) {
1540								conversation
1541										.setNextEncryption(Message.ENCRYPTION_NONE);
1542								message.setEncryption(Message.ENCRYPTION_NONE);
1543								xmppService.updateConversation(conversation);
1544								xmppService.sendMessage(message);
1545								messageSent();
1546							}
1547						});
1548			}
1549		}
1550	}
1551
1552	public void showNoPGPKeyDialog(boolean plural,
1553								   DialogInterface.OnClickListener listener) {
1554		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1555		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1556		if (plural) {
1557			builder.setTitle(getString(R.string.no_pgp_keys));
1558			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1559		} else {
1560			builder.setTitle(getString(R.string.no_pgp_key));
1561			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1562		}
1563		builder.setNegativeButton(getString(R.string.cancel), null);
1564		builder.setPositiveButton(getString(R.string.send_unencrypted),
1565				listener);
1566		builder.create().show();
1567	}
1568
1569	protected void sendAxolotlMessage(final Message message) {
1570		final ConversationActivity activity = (ConversationActivity) getActivity();
1571		final XmppConnectionService xmppService = activity.xmppConnectionService;
1572		xmppService.sendMessage(message);
1573		messageSent();
1574	}
1575
1576	protected void sendOtrMessage(final Message message) {
1577		final ConversationActivity activity = (ConversationActivity) getActivity();
1578		final XmppConnectionService xmppService = activity.xmppConnectionService;
1579		activity.selectPresence(message.getConversation(),
1580				new OnPresenceSelected() {
1581
1582					@Override
1583					public void onPresenceSelected() {
1584						message.setCounterpart(conversation.getNextCounterpart());
1585						xmppService.sendMessage(message);
1586						messageSent();
1587					}
1588				});
1589	}
1590
1591	public void appendText(String text) {
1592		if (text == null) {
1593			return;
1594		}
1595		String previous = this.mEditMessage.getText().toString();
1596		if (previous.length() != 0 && !previous.endsWith(" ")) {
1597			text = " " + text;
1598		}
1599		this.mEditMessage.append(text);
1600	}
1601
1602	@Override
1603	public boolean onEnterPressed() {
1604		if (activity.enterIsSend()) {
1605			sendMessage();
1606			return true;
1607		} else {
1608			return false;
1609		}
1610	}
1611
1612	@Override
1613	public void onTypingStarted() {
1614		Account.State status = conversation.getAccount().getStatus();
1615		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1616			activity.xmppConnectionService.sendChatState(conversation);
1617		}
1618		activity.hideConversationsOverview();
1619		updateSendButton();
1620	}
1621
1622	@Override
1623	public void onTypingStopped() {
1624		Account.State status = conversation.getAccount().getStatus();
1625		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1626			activity.xmppConnectionService.sendChatState(conversation);
1627		}
1628	}
1629
1630	@Override
1631	public void onTextDeleted() {
1632		Account.State status = conversation.getAccount().getStatus();
1633		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1634			activity.xmppConnectionService.sendChatState(conversation);
1635		}
1636		updateSendButton();
1637	}
1638
1639	@Override
1640	public void onTextChanged() {
1641		if (conversation != null && conversation.getCorrectingMessage() != null) {
1642			updateSendButton();
1643		}
1644	}
1645
1646	private int completionIndex = 0;
1647	private int lastCompletionLength = 0;
1648	private String incomplete;
1649	private int lastCompletionCursor;
1650	private boolean firstWord = false;
1651
1652	@Override
1653	public boolean onTabPressed(boolean repeated) {
1654		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
1655			return false;
1656		}
1657		if (repeated) {
1658			completionIndex++;
1659		} else {
1660			lastCompletionLength = 0;
1661			completionIndex = 0;
1662			final String content = mEditMessage.getText().toString();
1663			lastCompletionCursor = mEditMessage.getSelectionEnd();
1664			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ",lastCompletionCursor-1) + 1 : 0;
1665			firstWord = start == 0;
1666			incomplete = content.substring(start,lastCompletionCursor);
1667		}
1668		List<String> completions = new ArrayList<>();
1669		for(MucOptions.User user : conversation.getMucOptions().getUsers()) {
1670			String name = user.getName();
1671			if (name != null && name.startsWith(incomplete)) {
1672				completions.add(name+(firstWord ? ": " : " "));
1673			}
1674		}
1675		Collections.sort(completions);
1676		if (completions.size() > completionIndex) {
1677			String completion = completions.get(completionIndex).substring(incomplete.length());
1678			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1679			mEditMessage.getEditableText().insert(lastCompletionCursor, completion);
1680			lastCompletionLength = completion.length();
1681		} else {
1682			completionIndex = -1;
1683			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1684			lastCompletionLength = 0;
1685		}
1686		return true;
1687	}
1688
1689	@Override
1690	public void onActivityResult(int requestCode, int resultCode,
1691	                                final Intent data) {
1692		if (resultCode == Activity.RESULT_OK) {
1693			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1694				activity.getSelectedConversation().getAccount().getPgpDecryptionService().continueDecryption(true);
1695			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_TEXT) {
1696				final String body = mEditMessage.getText().toString();
1697				Message message = new Message(conversation, body, conversation.getNextEncryption());
1698				sendAxolotlMessage(message);
1699			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_MENU) {
1700				int choice = data.getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID);
1701				activity.selectPresenceToAttachFile(choice, conversation.getNextEncryption());
1702			}
1703		} else if (resultCode == Activity.RESULT_CANCELED) {
1704			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1705				// discard the message to prevent decryption being blocked
1706				conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
1707			}
1708		}
1709	}
1710
1711}