ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import android.app.AlertDialog;
   4import android.app.Fragment;
   5import android.app.PendingIntent;
   6import android.content.Context;
   7import android.content.DialogInterface;
   8import android.content.Intent;
   9import android.content.IntentSender;
  10import android.content.IntentSender.SendIntentException;
  11import android.os.Bundle;
  12import android.text.InputType;
  13import android.view.ContextMenu;
  14import android.view.ContextMenu.ContextMenuInfo;
  15import android.view.Gravity;
  16import android.view.KeyEvent;
  17import android.view.LayoutInflater;
  18import android.view.MenuItem;
  19import android.view.View;
  20import android.view.View.OnClickListener;
  21import android.view.ViewGroup;
  22import android.view.inputmethod.EditorInfo;
  23import android.view.inputmethod.InputMethodManager;
  24import android.widget.AbsListView;
  25import android.widget.AbsListView.OnScrollListener;
  26import android.widget.AdapterView;
  27import android.widget.AdapterView.AdapterContextMenuInfo;
  28import android.widget.ImageButton;
  29import android.widget.ListView;
  30import android.widget.RelativeLayout;
  31import android.widget.TextView;
  32import android.widget.TextView.OnEditorActionListener;
  33import android.widget.Toast;
  34
  35import net.java.otr4j.session.SessionStatus;
  36
  37import java.util.ArrayList;
  38import java.util.List;
  39import java.util.NoSuchElementException;
  40import java.util.concurrent.ConcurrentLinkedQueue;
  41
  42import eu.siacs.conversations.Config;
  43import eu.siacs.conversations.R;
  44import eu.siacs.conversations.crypto.PgpEngine;
  45import eu.siacs.conversations.entities.Account;
  46import eu.siacs.conversations.entities.Contact;
  47import eu.siacs.conversations.entities.Conversation;
  48import eu.siacs.conversations.entities.Transferable;
  49import eu.siacs.conversations.entities.DownloadableFile;
  50import eu.siacs.conversations.entities.TransferablePlaceholder;
  51import eu.siacs.conversations.entities.Message;
  52import eu.siacs.conversations.entities.MucOptions;
  53import eu.siacs.conversations.entities.Presences;
  54import eu.siacs.conversations.services.XmppConnectionService;
  55import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
  56import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
  57import eu.siacs.conversations.ui.adapter.MessageAdapter;
  58import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
  59import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
  60import eu.siacs.conversations.utils.GeoHelper;
  61import eu.siacs.conversations.utils.UIHelper;
  62import eu.siacs.conversations.xmpp.chatstate.ChatState;
  63import eu.siacs.conversations.xmpp.jid.Jid;
  64
  65public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
  66
  67	protected Conversation conversation;
  68	private OnClickListener leaveMuc = new OnClickListener() {
  69
  70		@Override
  71		public void onClick(View v) {
  72			activity.endConversation(conversation);
  73		}
  74	};
  75	private OnClickListener joinMuc = new OnClickListener() {
  76
  77		@Override
  78		public void onClick(View v) {
  79			activity.xmppConnectionService.joinMuc(conversation);
  80		}
  81	};
  82	private OnClickListener enterPassword = new OnClickListener() {
  83
  84		@Override
  85		public void onClick(View v) {
  86			MucOptions muc = conversation.getMucOptions();
  87			String password = muc.getPassword();
  88			if (password == null) {
  89				password = "";
  90			}
  91			activity.quickPasswordEdit(password, new OnValueEdited() {
  92
  93				@Override
  94				public void onValueEdited(String value) {
  95					activity.xmppConnectionService.providePasswordForMuc(
  96							conversation, value);
  97				}
  98			});
  99		}
 100	};
 101	protected ListView messagesView;
 102	final protected List<Message> messageList = new ArrayList<>();
 103	protected MessageAdapter messageListAdapter;
 104	private EditMessage mEditMessage;
 105	private ImageButton mSendButton;
 106	private RelativeLayout snackbar;
 107	private TextView snackbarMessage;
 108	private TextView snackbarAction;
 109	private boolean messagesLoaded = true;
 110	private Toast messageLoaderToast;
 111
 112	private OnScrollListener mOnScrollListener = new OnScrollListener() {
 113
 114		@Override
 115		public void onScrollStateChanged(AbsListView view, int scrollState) {
 116			// TODO Auto-generated method stub
 117
 118		}
 119
 120		private int getIndexOf(String uuid, List<Message> messages) {
 121			if (uuid == null) {
 122				return 0;
 123			}
 124			for(int i = 0; i < messages.size(); ++i) {
 125				if (uuid.equals(messages.get(i).getUuid())) {
 126					return i;
 127				} else {
 128					Message next = messages.get(i);
 129					while(next != null && next.wasMergedIntoPrevious()) {
 130						if (uuid.equals(next.getUuid())) {
 131							return i;
 132						}
 133						next = next.next();
 134					}
 135
 136				}
 137			}
 138			return 0;
 139		}
 140
 141		@Override
 142		public void onScroll(AbsListView view, int firstVisibleItem,
 143							 int visibleItemCount, int totalItemCount) {
 144			synchronized (ConversationFragment.this.messageList) {
 145				if (firstVisibleItem < 5 && messagesLoaded && messageList.size() > 0) {
 146					long timestamp = ConversationFragment.this.messageList.get(0).getTimeSent();
 147					messagesLoaded = false;
 148					activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
 149						@Override
 150						public void onMoreMessagesLoaded(final int c, Conversation conversation) {
 151							if (ConversationFragment.this.conversation != conversation) {
 152								return;
 153							}
 154							activity.runOnUiThread(new Runnable() {
 155								@Override
 156								public void run() {
 157									final int oldPosition = messagesView.getFirstVisiblePosition();
 158									Message message = messageList.get(oldPosition);
 159									String uuid = message != null ? message.getUuid() : null;
 160									View v = messagesView.getChildAt(0);
 161									final int pxOffset = (v == null) ? 0 : v.getTop();
 162									ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
 163									updateStatusMessages();
 164									messageListAdapter.notifyDataSetChanged();
 165									int pos = getIndexOf(uuid,messageList);
 166									messagesView.setSelectionFromTop(pos, pxOffset);
 167									messagesLoaded = true;
 168									if (messageLoaderToast != null) {
 169										messageLoaderToast.cancel();
 170									}
 171								}
 172							});
 173						}
 174
 175						@Override
 176						public void informUser(final int resId) {
 177
 178							activity.runOnUiThread(new Runnable() {
 179								@Override
 180								public void run() {
 181									if (messageLoaderToast != null) {
 182										messageLoaderToast.cancel();
 183									}
 184									if (ConversationFragment.this.conversation != conversation) {
 185										return;
 186									}
 187									messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
 188									messageLoaderToast.show();
 189								}
 190							});
 191
 192						}
 193					});
 194
 195				}
 196			}
 197		}
 198	};
 199	private IntentSender askForPassphraseIntent = null;
 200	protected OnClickListener clickToDecryptListener = new OnClickListener() {
 201
 202		@Override
 203		public void onClick(View v) {
 204			if (activity.hasPgp() && askForPassphraseIntent != null) {
 205				try {
 206					getActivity().startIntentSenderForResult(
 207							askForPassphraseIntent,
 208							ConversationActivity.REQUEST_DECRYPT_PGP, null, 0,
 209							0, 0);
 210					askForPassphraseIntent = null;
 211				} catch (SendIntentException e) {
 212					//
 213				}
 214			}
 215		}
 216	};
 217	protected OnClickListener clickToVerify = new OnClickListener() {
 218
 219		@Override
 220		public void onClick(View v) {
 221			activity.verifyOtrSessionDialog(conversation, v);
 222		}
 223	};
 224	private ConcurrentLinkedQueue<Message> mEncryptedMessages = new ConcurrentLinkedQueue<>();
 225	private boolean mDecryptJobRunning = false;
 226	private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
 227
 228		@Override
 229		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 230			if (actionId == EditorInfo.IME_ACTION_SEND) {
 231				InputMethodManager imm = (InputMethodManager) v.getContext()
 232						.getSystemService(Context.INPUT_METHOD_SERVICE);
 233				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
 234				sendMessage();
 235				return true;
 236			} else {
 237				return false;
 238			}
 239		}
 240	};
 241	private OnClickListener mSendButtonListener = new OnClickListener() {
 242
 243		@Override
 244		public void onClick(View v) {
 245			Object tag = v.getTag();
 246			if (tag instanceof SendButtonAction) {
 247				SendButtonAction action = (SendButtonAction) tag;
 248				switch (action) {
 249					case TAKE_PHOTO:
 250						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
 251						break;
 252					case SEND_LOCATION:
 253						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
 254						break;
 255					case RECORD_VOICE:
 256						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
 257						break;
 258					case CHOOSE_PICTURE:
 259						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 260						break;
 261					case CANCEL:
 262						if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
 263							conversation.setNextCounterpart(null);
 264							updateChatMsgHint();
 265							updateSendButton();
 266						}
 267						break;
 268					default:
 269						sendMessage();
 270				}
 271			} else {
 272				sendMessage();
 273			}
 274		}
 275	};
 276	private OnClickListener clickToMuc = new OnClickListener() {
 277
 278		@Override
 279		public void onClick(View v) {
 280			Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
 281			intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 282			intent.putExtra("uuid", conversation.getUuid());
 283			startActivity(intent);
 284		}
 285	};
 286	private ConversationActivity activity;
 287	private Message selectedMessage;
 288
 289	private void sendMessage() {
 290		final String body = mEditMessage.getText().toString();
 291		if (body.length() == 0 || this.conversation == null) {
 292			return;
 293		}
 294		Message message = new Message(conversation, body, conversation.getNextEncryption(activity.forceEncryption()));
 295		if (conversation.getMode() == Conversation.MODE_MULTI) {
 296			if (conversation.getNextCounterpart() != null) {
 297				message.setCounterpart(conversation.getNextCounterpart());
 298				message.setType(Message.TYPE_PRIVATE);
 299			}
 300		}
 301		if (conversation.getNextEncryption(activity.forceEncryption()) == Message.ENCRYPTION_OTR) {
 302			sendOtrMessage(message);
 303		} else if (conversation.getNextEncryption(activity.forceEncryption()) == Message.ENCRYPTION_PGP) {
 304			sendPgpMessage(message);
 305		} else {
 306			sendPlainTextMessage(message);
 307		}
 308	}
 309
 310	public void updateChatMsgHint() {
 311		if (conversation.getMode() == Conversation.MODE_MULTI
 312				&& conversation.getNextCounterpart() != null) {
 313			this.mEditMessage.setHint(getString(
 314					R.string.send_private_message_to,
 315					conversation.getNextCounterpart().getResourcepart()));
 316		} else {
 317			switch (conversation.getNextEncryption(activity.forceEncryption())) {
 318				case Message.ENCRYPTION_NONE:
 319					mEditMessage
 320							.setHint(getString(R.string.send_plain_text_message));
 321					break;
 322				case Message.ENCRYPTION_OTR:
 323					mEditMessage.setHint(getString(R.string.send_otr_message));
 324					break;
 325				case Message.ENCRYPTION_PGP:
 326					mEditMessage.setHint(getString(R.string.send_pgp_message));
 327					break;
 328				default:
 329					break;
 330			}
 331			getActivity().invalidateOptionsMenu();
 332		}
 333	}
 334
 335	private void setupIme() {
 336		if (((ConversationActivity) getActivity()).usingEnterKey()) {
 337			mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
 338		} else {
 339			mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
 340		}
 341	}
 342
 343	@Override
 344	public View onCreateView(final LayoutInflater inflater,
 345							 ViewGroup container, Bundle savedInstanceState) {
 346		final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
 347		view.setOnClickListener(null);
 348		mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
 349		setupIme();
 350		mEditMessage.setOnClickListener(new OnClickListener() {
 351
 352			@Override
 353			public void onClick(View v) {
 354				if (activity != null) {
 355					activity.hideConversationsOverview();
 356				}
 357			}
 358		});
 359		mEditMessage.setOnEditorActionListener(mEditorActionListener);
 360
 361		mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
 362		mSendButton.setOnClickListener(this.mSendButtonListener);
 363
 364		snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
 365		snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
 366		snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
 367
 368		messagesView = (ListView) view.findViewById(R.id.messages_view);
 369		messagesView.setOnScrollListener(mOnScrollListener);
 370		messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
 371		messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
 372		messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
 373
 374			@Override
 375			public void onContactPictureClicked(Message message) {
 376				if (message.getStatus() <= Message.STATUS_RECEIVED) {
 377					if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 378						if (message.getCounterpart() != null) {
 379							if (!message.getCounterpart().isBareJid()) {
 380								highlightInConference(message.getCounterpart().getResourcepart());
 381							} else {
 382								highlightInConference(message.getCounterpart().toString());
 383							}
 384						}
 385					} else {
 386						activity.switchToContactDetails(message.getContact());
 387					}
 388				} else {
 389					Account account = message.getConversation().getAccount();
 390					Intent intent = new Intent(activity, EditAccountActivity.class);
 391					intent.putExtra("jid", account.getJid().toBareJid().toString());
 392					startActivity(intent);
 393				}
 394			}
 395		});
 396		messageListAdapter
 397				.setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
 398
 399					@Override
 400					public void onContactPictureLongClicked(Message message) {
 401						if (message.getStatus() <= Message.STATUS_RECEIVED) {
 402							if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 403								if (message.getCounterpart() != null) {
 404									privateMessageWith(message.getCounterpart());
 405								}
 406							}
 407						} else {
 408							activity.showQrCode();
 409						}
 410					}
 411				});
 412		messagesView.setAdapter(messageListAdapter);
 413
 414		registerForContextMenu(messagesView);
 415
 416		return view;
 417	}
 418
 419	@Override
 420	public void onCreateContextMenu(ContextMenu menu, View v,
 421									ContextMenuInfo menuInfo) {
 422		synchronized (this.messageList) {
 423			super.onCreateContextMenu(menu, v, menuInfo);
 424			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
 425			this.selectedMessage = this.messageList.get(acmi.position);
 426			populateContextMenu(menu);
 427		}
 428	}
 429
 430	private void populateContextMenu(ContextMenu menu) {
 431		final Message m = this.selectedMessage;
 432		if (m.getType() != Message.TYPE_STATUS) {
 433			activity.getMenuInflater().inflate(R.menu.message_context, menu);
 434			menu.setHeaderTitle(R.string.message_options);
 435			MenuItem copyText = menu.findItem(R.id.copy_text);
 436			MenuItem shareWith = menu.findItem(R.id.share_with);
 437			MenuItem sendAgain = menu.findItem(R.id.send_again);
 438			MenuItem copyUrl = menu.findItem(R.id.copy_url);
 439			MenuItem downloadFile = menu.findItem(R.id.download_file);
 440			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
 441			if ((m.getType() == Message.TYPE_TEXT || m.getType() == Message.TYPE_PRIVATE)
 442					&& m.getTransferable() == null
 443					&& !GeoHelper.isGeoUri(m.getBody())
 444					&& m.treatAsDownloadable() != Message.Decision.MUST) {
 445				copyText.setVisible(true);
 446			}
 447			if ((m.getType() != Message.TYPE_TEXT
 448					&& m.getType() != Message.TYPE_PRIVATE
 449					&& m.getTransferable() == null)
 450					|| (GeoHelper.isGeoUri(m.getBody()))) {
 451				shareWith.setVisible(true);
 452			}
 453			if (m.getStatus() == Message.STATUS_SEND_FAILED) {
 454				sendAgain.setVisible(true);
 455			}
 456			if (m.hasFileOnRemoteHost()
 457					|| GeoHelper.isGeoUri(m.getBody())
 458					|| m.treatAsDownloadable() == Message.Decision.MUST) {
 459				copyUrl.setVisible(true);
 460			}
 461			if (m.getType() == Message.TYPE_TEXT && m.getTransferable() == null && m.treatAsDownloadable() != Message.Decision.NEVER) {
 462				downloadFile.setVisible(true);
 463				downloadFile.setTitle(activity.getString(R.string.download_x_file,UIHelper.getFileDescriptionString(activity, m)));
 464			}
 465			if ((m.getTransferable() != null && !(m.getTransferable() instanceof TransferablePlaceholder))
 466					|| (m.isFileOrImage() && (m.getStatus() == Message.STATUS_WAITING
 467					|| m.getStatus() == Message.STATUS_OFFERED))) {
 468				cancelTransmission.setVisible(true);
 469			}
 470		}
 471	}
 472
 473	@Override
 474	public boolean onContextItemSelected(MenuItem item) {
 475		switch (item.getItemId()) {
 476			case R.id.share_with:
 477				shareWith(selectedMessage);
 478				return true;
 479			case R.id.copy_text:
 480				copyText(selectedMessage);
 481				return true;
 482			case R.id.send_again:
 483				resendMessage(selectedMessage);
 484				return true;
 485			case R.id.copy_url:
 486				copyUrl(selectedMessage);
 487				return true;
 488			case R.id.download_file:
 489				downloadFile(selectedMessage);
 490				return true;
 491			case R.id.cancel_transmission:
 492				cancelTransmission(selectedMessage);
 493				return true;
 494			default:
 495				return super.onContextItemSelected(item);
 496		}
 497	}
 498
 499	private void shareWith(Message message) {
 500		Intent shareIntent = new Intent();
 501		shareIntent.setAction(Intent.ACTION_SEND);
 502		if (GeoHelper.isGeoUri(message.getBody())) {
 503			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
 504			shareIntent.setType("text/plain");
 505		} else {
 506			shareIntent.putExtra(Intent.EXTRA_STREAM,
 507					activity.xmppConnectionService.getFileBackend()
 508							.getJingleFileUri(message));
 509			shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 510			String mime = message.getMimeType();
 511			if (mime == null) {
 512				mime = "image/webp";
 513			}
 514			shareIntent.setType(mime);
 515		}
 516		activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
 517	}
 518
 519	private void copyText(Message message) {
 520		if (activity.copyTextToClipboard(message.getMergedBody(),
 521				R.string.message_text)) {
 522			Toast.makeText(activity, R.string.message_copied_to_clipboard,
 523					Toast.LENGTH_SHORT).show();
 524		}
 525	}
 526
 527	private void resendMessage(Message message) {
 528		if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
 529			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 530			if (!file.exists()) {
 531				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
 532				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 533				return;
 534			}
 535		}
 536		activity.xmppConnectionService.resendFailedMessages(message);
 537	}
 538
 539	private void copyUrl(Message message) {
 540		final String url;
 541		final int resId;
 542		if (GeoHelper.isGeoUri(message.getBody())) {
 543			resId = R.string.location;
 544			url = message.getBody();
 545		} else if (message.hasFileOnRemoteHost()) {
 546			resId = R.string.file_url;
 547			url = message.getFileParams().url.toString();
 548		} else {
 549			url = message.getBody().trim();
 550			resId = R.string.file_url;
 551		}
 552		if (activity.copyTextToClipboard(url, resId)) {
 553			Toast.makeText(activity, R.string.url_copied_to_clipboard,
 554					Toast.LENGTH_SHORT).show();
 555		}
 556	}
 557
 558	private void downloadFile(Message message) {
 559		activity.xmppConnectionService.getHttpConnectionManager()
 560				.createNewDownloadConnection(message);
 561	}
 562
 563	private void cancelTransmission(Message message) {
 564		Transferable transferable = message.getTransferable();
 565		if (transferable != null) {
 566			transferable.cancel();
 567		} else {
 568			activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 569		}
 570	}
 571
 572	protected void privateMessageWith(final Jid counterpart) {
 573		this.mEditMessage.setText("");
 574		this.conversation.setNextCounterpart(counterpart);
 575		updateChatMsgHint();
 576		updateSendButton();
 577	}
 578
 579	protected void highlightInConference(String nick) {
 580		String oldString = mEditMessage.getText().toString().trim();
 581		if (oldString.isEmpty() || mEditMessage.getSelectionStart() == 0) {
 582			mEditMessage.getText().insert(0, nick + ": ");
 583		} else {
 584			if (mEditMessage.getText().charAt(
 585					mEditMessage.getSelectionStart() - 1) != ' ') {
 586				nick = " " + nick;
 587			}
 588			mEditMessage.getText().insert(mEditMessage.getSelectionStart(),
 589					nick + " ");
 590		}
 591	}
 592
 593	@Override
 594	public void onStop() {
 595		mDecryptJobRunning = false;
 596		super.onStop();
 597		if (this.conversation != null) {
 598			final String msg = mEditMessage.getText().toString();
 599			this.conversation.setNextMessage(msg);
 600			updateChatState(this.conversation, msg);
 601		}
 602	}
 603
 604	private void updateChatState(final Conversation conversation, final String msg) {
 605		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
 606		Account.State status = conversation.getAccount().getStatus();
 607		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
 608			activity.xmppConnectionService.sendChatState(conversation);
 609		}
 610	}
 611
 612	public void reInit(Conversation conversation) {
 613		if (conversation == null) {
 614			return;
 615		}
 616
 617		this.activity = (ConversationActivity) getActivity();
 618
 619		if (this.conversation != null) {
 620			final String msg = mEditMessage.getText().toString();
 621			this.conversation.setNextMessage(msg);
 622			if (this.conversation != conversation) {
 623				updateChatState(this.conversation, msg);
 624			}
 625			this.conversation.trim();
 626		}
 627
 628		this.askForPassphraseIntent = null;
 629		this.conversation = conversation;
 630		this.mDecryptJobRunning = false;
 631		this.mEncryptedMessages.clear();
 632		if (this.conversation.getMode() == Conversation.MODE_MULTI) {
 633			this.conversation.setNextCounterpart(null);
 634		}
 635		this.mEditMessage.setKeyboardListener(null);
 636		this.mEditMessage.setText("");
 637		this.mEditMessage.append(this.conversation.getNextMessage());
 638		this.mEditMessage.setKeyboardListener(this);
 639		this.messagesView.setAdapter(messageListAdapter);
 640		updateMessages();
 641		this.messagesLoaded = true;
 642		int size = this.messageList.size();
 643		if (size > 0) {
 644			messagesView.setSelection(size - 1);
 645		}
 646	}
 647
 648	private OnClickListener mUnblockClickListener = new OnClickListener() {
 649		@Override
 650		public void onClick(final View v) {
 651			v.post(new Runnable() {
 652				@Override
 653				public void run() {
 654					v.setVisibility(View.INVISIBLE);
 655				}
 656			});
 657			if (conversation.isDomainBlocked()) {
 658				BlockContactDialog.show(activity, activity.xmppConnectionService, conversation);
 659			} else {
 660				activity.unblockConversation(conversation);
 661			}
 662		}
 663	};
 664
 665	private OnClickListener mAddBackClickListener = new OnClickListener() {
 666
 667		@Override
 668		public void onClick(View v) {
 669			final Contact contact = conversation == null ? null : conversation.getContact();
 670			if (contact != null) {
 671				activity.xmppConnectionService.createContact(contact);
 672				activity.switchToContactDetails(contact);
 673			}
 674		}
 675	};
 676
 677	private OnClickListener mUnmuteClickListener = new OnClickListener() {
 678
 679		@Override
 680		public void onClick(final View v) {
 681			activity.unmuteConversation(conversation);
 682		}
 683	};
 684
 685	private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
 686		@Override
 687		public void onClick(View view) {
 688			Intent intent = new Intent(activity, VerifyOTRActivity.class);
 689			intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 690			intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 691			intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
 692			intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
 693			startActivity(intent);
 694		}
 695	};
 696
 697	private void updateSnackBar(final Conversation conversation) {
 698		final Account account = conversation.getAccount();
 699		final Contact contact = conversation.getContact();
 700		final int mode = conversation.getMode();
 701		if (conversation.isBlocked()) {
 702			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
 703		} else if (!contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
 704			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
 705		} else if (mode == Conversation.MODE_MULTI
 706				&& !conversation.getMucOptions().online()
 707				&& account.getStatus() == Account.State.ONLINE) {
 708			switch (conversation.getMucOptions().getError()) {
 709				case MucOptions.ERROR_NICK_IN_USE:
 710					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
 711					break;
 712				case MucOptions.ERROR_UNKNOWN:
 713					showSnackbar(R.string.conference_not_found, R.string.leave, leaveMuc);
 714					break;
 715				case MucOptions.ERROR_PASSWORD_REQUIRED:
 716					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
 717					break;
 718				case MucOptions.ERROR_BANNED:
 719					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
 720					break;
 721				case MucOptions.ERROR_MEMBERS_ONLY:
 722					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
 723					break;
 724				case MucOptions.KICKED_FROM_ROOM:
 725					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
 726					break;
 727				default:
 728					break;
 729			}
 730		} else if (askForPassphraseIntent != null) {
 731			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
 732		} else if (mode == Conversation.MODE_SINGLE
 733				&& conversation.smpRequested()) {
 734			showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
 735		} else if (mode == Conversation.MODE_SINGLE
 736				&& conversation.hasValidOtrSession()
 737				&& (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
 738				&& (!conversation.isOtrFingerprintVerified())) {
 739			showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
 740		} else if (conversation.isMuted()) {
 741			showSnackbar(R.string.notifications_disabled, R.string.enable, this.mUnmuteClickListener);
 742		} else {
 743			hideSnackbar();
 744		}
 745	}
 746
 747	public void updateMessages() {
 748		synchronized (this.messageList) {
 749			if (getView() == null) {
 750				return;
 751			}
 752			final ConversationActivity activity = (ConversationActivity) getActivity();
 753			if (this.conversation != null) {
 754				updateSnackBar(this.conversation);
 755				conversation.populateWithMessages(ConversationFragment.this.messageList);
 756				for (final Message message : this.messageList) {
 757					if (message.getEncryption() == Message.ENCRYPTION_PGP
 758							&& (message.getStatus() == Message.STATUS_RECEIVED || message
 759							.getStatus() >= Message.STATUS_SEND)
 760							&& message.getTransferable() == null) {
 761						if (!mEncryptedMessages.contains(message)) {
 762							mEncryptedMessages.add(message);
 763						}
 764					}
 765				}
 766				decryptNext();
 767				updateStatusMessages();
 768				this.messageListAdapter.notifyDataSetChanged();
 769				updateChatMsgHint();
 770				if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
 771					activity.sendReadMarkerIfNecessary(conversation);
 772				}
 773				this.updateSendButton();
 774			}
 775		}
 776	}
 777
 778	private void decryptNext() {
 779		Message next = this.mEncryptedMessages.peek();
 780		PgpEngine engine = activity.xmppConnectionService.getPgpEngine();
 781
 782		if (next != null && engine != null && !mDecryptJobRunning) {
 783			mDecryptJobRunning = true;
 784			engine.decrypt(next, new UiCallback<Message>() {
 785
 786				@Override
 787				public void userInputRequried(PendingIntent pi, Message message) {
 788					mDecryptJobRunning = false;
 789					askForPassphraseIntent = pi.getIntentSender();
 790					updateSnackBar(conversation);
 791				}
 792
 793				@Override
 794				public void success(Message message) {
 795					mDecryptJobRunning = false;
 796					try {
 797						mEncryptedMessages.remove();
 798					} catch (final NoSuchElementException ignored) {
 799
 800					}
 801					askForPassphraseIntent = null;
 802					activity.xmppConnectionService.updateMessage(message);
 803				}
 804
 805				@Override
 806				public void error(int error, Message message) {
 807					message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
 808					mDecryptJobRunning = false;
 809					try {
 810						mEncryptedMessages.remove();
 811					} catch (final NoSuchElementException ignored) {
 812
 813					}
 814					activity.xmppConnectionService.updateConversationUi();
 815				}
 816			});
 817		}
 818	}
 819
 820	private void messageSent() {
 821		int size = this.messageList.size();
 822		messagesView.setSelection(size - 1);
 823		mEditMessage.setText("");
 824		updateChatMsgHint();
 825	}
 826
 827	enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
 828
 829	private int getSendButtonImageResource(SendButtonAction action, int status) {
 830		switch (action) {
 831			case TEXT:
 832				switch (status) {
 833					case Presences.CHAT:
 834					case Presences.ONLINE:
 835						return R.drawable.ic_send_text_online;
 836					case Presences.AWAY:
 837						return R.drawable.ic_send_text_away;
 838					case Presences.XA:
 839					case Presences.DND:
 840						return R.drawable.ic_send_text_dnd;
 841					default:
 842						return R.drawable.ic_send_text_offline;
 843				}
 844			case TAKE_PHOTO:
 845				switch (status) {
 846					case Presences.CHAT:
 847					case Presences.ONLINE:
 848						return R.drawable.ic_send_photo_online;
 849					case Presences.AWAY:
 850						return R.drawable.ic_send_photo_away;
 851					case Presences.XA:
 852					case Presences.DND:
 853						return R.drawable.ic_send_photo_dnd;
 854					default:
 855						return R.drawable.ic_send_photo_offline;
 856				}
 857			case RECORD_VOICE:
 858				switch (status) {
 859					case Presences.CHAT:
 860					case Presences.ONLINE:
 861						return R.drawable.ic_send_voice_online;
 862					case Presences.AWAY:
 863						return R.drawable.ic_send_voice_away;
 864					case Presences.XA:
 865					case Presences.DND:
 866						return R.drawable.ic_send_voice_dnd;
 867					default:
 868						return R.drawable.ic_send_voice_offline;
 869				}
 870			case SEND_LOCATION:
 871				switch (status) {
 872					case Presences.CHAT:
 873					case Presences.ONLINE:
 874						return R.drawable.ic_send_location_online;
 875					case Presences.AWAY:
 876						return R.drawable.ic_send_location_away;
 877					case Presences.XA:
 878					case Presences.DND:
 879						return R.drawable.ic_send_location_dnd;
 880					default:
 881						return R.drawable.ic_send_location_offline;
 882				}
 883			case CANCEL:
 884				switch (status) {
 885					case Presences.CHAT:
 886					case Presences.ONLINE:
 887						return R.drawable.ic_send_cancel_online;
 888					case Presences.AWAY:
 889						return R.drawable.ic_send_cancel_away;
 890					case Presences.XA:
 891					case Presences.DND:
 892						return R.drawable.ic_send_cancel_dnd;
 893					default:
 894						return R.drawable.ic_send_cancel_offline;
 895				}
 896			case CHOOSE_PICTURE:
 897				switch (status) {
 898					case Presences.CHAT:
 899					case Presences.ONLINE:
 900						return R.drawable.ic_send_picture_online;
 901					case Presences.AWAY:
 902						return R.drawable.ic_send_picture_away;
 903					case Presences.XA:
 904					case Presences.DND:
 905						return R.drawable.ic_send_picture_dnd;
 906					default:
 907						return R.drawable.ic_send_picture_offline;
 908				}
 909		}
 910		return R.drawable.ic_send_text_offline;
 911	}
 912
 913	public void updateSendButton() {
 914		final Conversation c = this.conversation;
 915		final SendButtonAction action;
 916		final int status;
 917		final boolean empty = this.mEditMessage == null || this.mEditMessage.getText().length() == 0;
 918		final boolean conference = c.getMode() == Conversation.MODE_MULTI;
 919		if (conference && !c.getAccount().httpUploadAvailable()) {
 920			if (empty && c.getNextCounterpart() != null) {
 921				action = SendButtonAction.CANCEL;
 922			} else {
 923				action = SendButtonAction.TEXT;
 924			}
 925		} else {
 926			if (empty) {
 927				if (conference && c.getNextCounterpart() != null) {
 928					action = SendButtonAction.CANCEL;
 929				} else {
 930					String setting = activity.getPreferences().getString("quick_action", "recent");
 931					if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
 932						setting = "location";
 933					} else if (setting.equals("recent")) {
 934						setting = activity.getPreferences().getString("recently_used_quick_action", "text");
 935					}
 936					switch (setting) {
 937						case "photo":
 938							action = SendButtonAction.TAKE_PHOTO;
 939							break;
 940						case "location":
 941							action = SendButtonAction.SEND_LOCATION;
 942							break;
 943						case "voice":
 944							action = SendButtonAction.RECORD_VOICE;
 945							break;
 946						case "picture":
 947							action = SendButtonAction.CHOOSE_PICTURE;
 948							break;
 949						default:
 950							action = SendButtonAction.TEXT;
 951							break;
 952					}
 953				}
 954			} else {
 955				action = SendButtonAction.TEXT;
 956			}
 957		}
 958		if (activity.useSendButtonToIndicateStatus() && c != null
 959				&& c.getAccount().getStatus() == Account.State.ONLINE) {
 960			if (c.getMode() == Conversation.MODE_SINGLE) {
 961				status = c.getContact().getMostAvailableStatus();
 962			} else {
 963				status = c.getMucOptions().online() ? Presences.ONLINE : Presences.OFFLINE;
 964			}
 965		} else {
 966			status = Presences.OFFLINE;
 967		}
 968		this.mSendButton.setTag(action);
 969		this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
 970	}
 971
 972	protected void updateStatusMessages() {
 973		synchronized (this.messageList) {
 974			if (conversation.getMode() == Conversation.MODE_SINGLE) {
 975				ChatState state = conversation.getIncomingChatState();
 976				if (state == ChatState.COMPOSING) {
 977					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
 978				} else if (state == ChatState.PAUSED) {
 979					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
 980				} else {
 981					for (int i = this.messageList.size() - 1; i >= 0; --i) {
 982						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
 983							return;
 984						} else {
 985							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
 986								this.messageList.add(i + 1,
 987										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
 988								return;
 989							}
 990						}
 991					}
 992				}
 993			}
 994		}
 995	}
 996
 997	protected void showSnackbar(final int message, final int action,
 998								final OnClickListener clickListener) {
 999		snackbar.setVisibility(View.VISIBLE);
1000		snackbar.setOnClickListener(null);
1001		snackbarMessage.setText(message);
1002		snackbarMessage.setOnClickListener(null);
1003		snackbarAction.setVisibility(View.VISIBLE);
1004		snackbarAction.setText(action);
1005		snackbarAction.setOnClickListener(clickListener);
1006	}
1007
1008	protected void hideSnackbar() {
1009		snackbar.setVisibility(View.GONE);
1010	}
1011
1012	protected void sendPlainTextMessage(Message message) {
1013		ConversationActivity activity = (ConversationActivity) getActivity();
1014		activity.xmppConnectionService.sendMessage(message);
1015		messageSent();
1016	}
1017
1018	protected void sendPgpMessage(final Message message) {
1019		final ConversationActivity activity = (ConversationActivity) getActivity();
1020		final XmppConnectionService xmppService = activity.xmppConnectionService;
1021		final Contact contact = message.getConversation().getContact();
1022		if (activity.hasPgp()) {
1023			if (conversation.getMode() == Conversation.MODE_SINGLE) {
1024				if (contact.getPgpKeyId() != 0) {
1025					xmppService.getPgpEngine().hasKey(contact,
1026							new UiCallback<Contact>() {
1027
1028								@Override
1029								public void userInputRequried(PendingIntent pi,
1030															  Contact contact) {
1031									activity.runIntent(
1032											pi,
1033											ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1034								}
1035
1036								@Override
1037								public void success(Contact contact) {
1038									messageSent();
1039									activity.encryptTextMessage(message);
1040								}
1041
1042								@Override
1043								public void error(int error, Contact contact) {
1044
1045								}
1046							});
1047
1048				} else {
1049					showNoPGPKeyDialog(false,
1050							new DialogInterface.OnClickListener() {
1051
1052								@Override
1053								public void onClick(DialogInterface dialog,
1054													int which) {
1055									conversation
1056											.setNextEncryption(Message.ENCRYPTION_NONE);
1057									xmppService.databaseBackend
1058											.updateConversation(conversation);
1059									message.setEncryption(Message.ENCRYPTION_NONE);
1060									xmppService.sendMessage(message);
1061									messageSent();
1062								}
1063							});
1064				}
1065			} else {
1066				if (conversation.getMucOptions().pgpKeysInUse()) {
1067					if (!conversation.getMucOptions().everybodyHasKeys()) {
1068						Toast warning = Toast
1069								.makeText(getActivity(),
1070										R.string.missing_public_keys,
1071										Toast.LENGTH_LONG);
1072						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1073						warning.show();
1074					}
1075					activity.encryptTextMessage(message);
1076					messageSent();
1077				} else {
1078					showNoPGPKeyDialog(true,
1079							new DialogInterface.OnClickListener() {
1080
1081								@Override
1082								public void onClick(DialogInterface dialog,
1083													int which) {
1084									conversation
1085											.setNextEncryption(Message.ENCRYPTION_NONE);
1086									message.setEncryption(Message.ENCRYPTION_NONE);
1087									xmppService.databaseBackend
1088											.updateConversation(conversation);
1089									xmppService.sendMessage(message);
1090									messageSent();
1091								}
1092							});
1093				}
1094			}
1095		} else {
1096			activity.showInstallPgpDialog();
1097		}
1098	}
1099
1100	public void showNoPGPKeyDialog(boolean plural,
1101								   DialogInterface.OnClickListener listener) {
1102		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1103		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1104		if (plural) {
1105			builder.setTitle(getString(R.string.no_pgp_keys));
1106			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1107		} else {
1108			builder.setTitle(getString(R.string.no_pgp_key));
1109			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1110		}
1111		builder.setNegativeButton(getString(R.string.cancel), null);
1112		builder.setPositiveButton(getString(R.string.send_unencrypted),
1113				listener);
1114		builder.create().show();
1115	}
1116
1117	protected void sendOtrMessage(final Message message) {
1118		final ConversationActivity activity = (ConversationActivity) getActivity();
1119		final XmppConnectionService xmppService = activity.xmppConnectionService;
1120		activity.selectPresence(message.getConversation(),
1121				new OnPresenceSelected() {
1122
1123					@Override
1124					public void onPresenceSelected() {
1125						message.setCounterpart(conversation.getNextCounterpart());
1126						xmppService.sendMessage(message);
1127						messageSent();
1128					}
1129				});
1130	}
1131
1132	public void appendText(String text) {
1133		if (text == null) {
1134			return;
1135		}
1136		String previous = this.mEditMessage.getText().toString();
1137		if (previous.length() != 0 && !previous.endsWith(" ")) {
1138			text = " " + text;
1139		}
1140		this.mEditMessage.append(text);
1141	}
1142
1143	@Override
1144	public boolean onEnterPressed() {
1145		if (activity.enterIsSend()) {
1146			sendMessage();
1147			return true;
1148		} else {
1149			return false;
1150		}
1151	}
1152
1153	@Override
1154	public void onTypingStarted() {
1155		Account.State status = conversation.getAccount().getStatus();
1156		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1157			activity.xmppConnectionService.sendChatState(conversation);
1158		}
1159		updateSendButton();
1160	}
1161
1162	@Override
1163	public void onTypingStopped() {
1164		Account.State status = conversation.getAccount().getStatus();
1165		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1166			activity.xmppConnectionService.sendChatState(conversation);
1167		}
1168	}
1169
1170	@Override
1171	public void onTextDeleted() {
1172		Account.State status = conversation.getAccount().getStatus();
1173		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1174			activity.xmppConnectionService.sendChatState(conversation);
1175		}
1176		updateSendButton();
1177	}
1178
1179}