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