ConversationFragment.java

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