ConversationFragment.java

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