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