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.net.URLConnection;
  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.Downloadable;
  50import eu.siacs.conversations.entities.DownloadableFile;
  51import eu.siacs.conversations.entities.DownloadablePlaceholder;
  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 downloadImage = menu.findItem(R.id.download_image);
 441			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
 442			if ((m.getType() != Message.TYPE_TEXT && m.getType() != Message.TYPE_PRIVATE)
 443					|| m.getDownloadable() != null || GeoHelper.isGeoUri(m.getBody())) {
 444				copyText.setVisible(false);
 445			}
 446			if ((m.getType() == Message.TYPE_TEXT
 447					|| m.getType() == Message.TYPE_PRIVATE
 448					|| m.getDownloadable() != null)
 449					&& (!GeoHelper.isGeoUri(m.getBody()))) {
 450				shareWith.setVisible(false);
 451			}
 452			if (m.getStatus() != Message.STATUS_SEND_FAILED) {
 453				sendAgain.setVisible(false);
 454			}
 455			if (!m.hasFileOnRemoteHost() && !GeoHelper.isGeoUri(m.getBody())) {
 456				copyUrl.setVisible(false);
 457			}
 458			if (m.getType() != Message.TYPE_TEXT
 459					|| m.getDownloadable() != null
 460					|| m.treatAsDownloadable() == Message.Decision.NO) {
 461				downloadImage.setVisible(false);
 462			}
 463			if (!((m.getDownloadable() != null && !(m.getDownloadable() instanceof DownloadablePlaceholder))
 464					|| (m.isFileOrImage() && (m.getStatus() == Message.STATUS_WAITING
 465					|| m.getStatus() == Message.STATUS_OFFERED)))) {
 466				cancelTransmission.setVisible(false);
 467			}
 468		}
 469	}
 470
 471	@Override
 472	public boolean onContextItemSelected(MenuItem item) {
 473		switch (item.getItemId()) {
 474			case R.id.share_with:
 475				shareWith(selectedMessage);
 476				return true;
 477			case R.id.copy_text:
 478				copyText(selectedMessage);
 479				return true;
 480			case R.id.send_again:
 481				resendMessage(selectedMessage);
 482				return true;
 483			case R.id.copy_url:
 484				copyUrl(selectedMessage);
 485				return true;
 486			case R.id.download_image:
 487				downloadImage(selectedMessage);
 488				return true;
 489			case R.id.cancel_transmission:
 490				cancelTransmission(selectedMessage);
 491				return true;
 492			default:
 493				return super.onContextItemSelected(item);
 494		}
 495	}
 496
 497	private void shareWith(Message message) {
 498		Intent shareIntent = new Intent();
 499		shareIntent.setAction(Intent.ACTION_SEND);
 500		if (GeoHelper.isGeoUri(message.getBody())) {
 501			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
 502			shareIntent.setType("text/plain");
 503		} else {
 504			shareIntent.putExtra(Intent.EXTRA_STREAM,
 505					activity.xmppConnectionService.getFileBackend()
 506							.getJingleFileUri(message));
 507			shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 508			String path = message.getRelativeFilePath();
 509			String mime = path == null ? null : URLConnection.guessContentTypeFromName(path);
 510			if (mime == null) {
 511				mime = "image/webp";
 512			}
 513			shareIntent.setType(mime);
 514		}
 515		activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
 516	}
 517
 518	private void copyText(Message message) {
 519		if (activity.copyTextToClipboard(message.getMergedBody(),
 520				R.string.message_text)) {
 521			Toast.makeText(activity, R.string.message_copied_to_clipboard,
 522					Toast.LENGTH_SHORT).show();
 523		}
 524	}
 525
 526	private void resendMessage(Message message) {
 527		if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
 528			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 529			if (!file.exists()) {
 530				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
 531				message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
 532				return;
 533			}
 534		}
 535		activity.xmppConnectionService.resendFailedMessages(message);
 536	}
 537
 538	private void copyUrl(Message message) {
 539		final String url;
 540		final int resId;
 541		if (GeoHelper.isGeoUri(message.getBody())) {
 542			resId = R.string.location;
 543			url = message.getBody();
 544		} else {
 545			resId = R.string.image_url;
 546			url = message.getFileParams().url.toString();
 547		}
 548		if (activity.copyTextToClipboard(url, resId)) {
 549			Toast.makeText(activity, R.string.url_copied_to_clipboard,
 550					Toast.LENGTH_SHORT).show();
 551		}
 552	}
 553
 554	private void downloadImage(Message message) {
 555		activity.xmppConnectionService.getHttpConnectionManager()
 556				.createNewConnection(message);
 557	}
 558
 559	private void cancelTransmission(Message message) {
 560		Downloadable downloadable = message.getDownloadable();
 561		if (downloadable != null) {
 562			downloadable.cancel();
 563		} else {
 564			activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 565		}
 566	}
 567
 568	protected void privateMessageWith(final Jid counterpart) {
 569		this.mEditMessage.setText("");
 570		this.conversation.setNextCounterpart(counterpart);
 571		updateChatMsgHint();
 572		updateSendButton();
 573	}
 574
 575	protected void highlightInConference(String nick) {
 576		String oldString = mEditMessage.getText().toString().trim();
 577		if (oldString.isEmpty() || mEditMessage.getSelectionStart() == 0) {
 578			mEditMessage.getText().insert(0, nick + ": ");
 579		} else {
 580			if (mEditMessage.getText().charAt(
 581					mEditMessage.getSelectionStart() - 1) != ' ') {
 582				nick = " " + nick;
 583			}
 584			mEditMessage.getText().insert(mEditMessage.getSelectionStart(),
 585					nick + " ");
 586		}
 587	}
 588
 589	@Override
 590	public void onStop() {
 591		mDecryptJobRunning = false;
 592		super.onStop();
 593		if (this.conversation != null) {
 594			final String msg = mEditMessage.getText().toString();
 595			this.conversation.setNextMessage(msg);
 596			updateChatState(this.conversation, msg);
 597		}
 598	}
 599
 600	private void updateChatState(final Conversation conversation, final String msg) {
 601		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
 602		Account.State status = conversation.getAccount().getStatus();
 603		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
 604			activity.xmppConnectionService.sendChatState(conversation);
 605		}
 606	}
 607
 608	public void reInit(Conversation conversation) {
 609		if (conversation == null) {
 610			return;
 611		}
 612
 613		this.activity = (ConversationActivity) getActivity();
 614
 615		if (this.conversation != null) {
 616			final String msg = mEditMessage.getText().toString();
 617			this.conversation.setNextMessage(msg);
 618			if (this.conversation != conversation) {
 619				updateChatState(this.conversation, msg);
 620			}
 621			this.conversation.trim();
 622		}
 623
 624		this.askForPassphraseIntent = null;
 625		this.conversation = conversation;
 626		this.mDecryptJobRunning = false;
 627		this.mEncryptedMessages.clear();
 628		if (this.conversation.getMode() == Conversation.MODE_MULTI) {
 629			this.conversation.setNextCounterpart(null);
 630		}
 631		this.mEditMessage.setKeyboardListener(null);
 632		this.mEditMessage.setText("");
 633		this.mEditMessage.append(this.conversation.getNextMessage());
 634		this.mEditMessage.setKeyboardListener(this);
 635		this.messagesView.setAdapter(messageListAdapter);
 636		updateMessages();
 637		this.messagesLoaded = true;
 638		int size = this.messageList.size();
 639		if (size > 0) {
 640			messagesView.setSelection(size - 1);
 641		}
 642	}
 643
 644	private OnClickListener mUnblockClickListener = new OnClickListener() {
 645		@Override
 646		public void onClick(final View v) {
 647			v.post(new Runnable() {
 648				@Override
 649				public void run() {
 650					v.setVisibility(View.INVISIBLE);
 651				}
 652			});
 653			if (conversation.isDomainBlocked()) {
 654				BlockContactDialog.show(activity, activity.xmppConnectionService, conversation);
 655			} else {
 656				activity.unblockConversation(conversation);
 657			}
 658		}
 659	};
 660
 661	private OnClickListener mAddBackClickListener = new OnClickListener() {
 662
 663		@Override
 664		public void onClick(View v) {
 665			final Contact contact = conversation == null ? null : conversation.getContact();
 666			if (contact != null) {
 667				activity.xmppConnectionService.createContact(contact);
 668				activity.switchToContactDetails(contact);
 669			}
 670		}
 671	};
 672
 673	private OnClickListener mUnmuteClickListener = new OnClickListener() {
 674
 675		@Override
 676		public void onClick(final View v) {
 677			activity.unmuteConversation(conversation);
 678		}
 679	};
 680
 681	private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
 682		@Override
 683		public void onClick(View view) {
 684			Intent intent = new Intent(activity, VerifyOTRActivity.class);
 685			intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 686			intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 687			intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
 688			intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
 689			startActivity(intent);
 690		}
 691	};
 692
 693	private void updateSnackBar(final Conversation conversation) {
 694		final Account account = conversation.getAccount();
 695		final Contact contact = conversation.getContact();
 696		final int mode = conversation.getMode();
 697		if (conversation.isBlocked()) {
 698			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
 699		} else if (!contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
 700			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
 701		} else if (mode == Conversation.MODE_MULTI
 702				&& !conversation.getMucOptions().online()
 703				&& account.getStatus() == Account.State.ONLINE) {
 704			switch (conversation.getMucOptions().getError()) {
 705				case MucOptions.ERROR_NICK_IN_USE:
 706					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
 707					break;
 708				case MucOptions.ERROR_UNKNOWN:
 709					showSnackbar(R.string.conference_not_found, R.string.leave, leaveMuc);
 710					break;
 711				case MucOptions.ERROR_PASSWORD_REQUIRED:
 712					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
 713					break;
 714				case MucOptions.ERROR_BANNED:
 715					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
 716					break;
 717				case MucOptions.ERROR_MEMBERS_ONLY:
 718					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
 719					break;
 720				case MucOptions.KICKED_FROM_ROOM:
 721					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
 722					break;
 723				default:
 724					break;
 725			}
 726		} else if (askForPassphraseIntent != null) {
 727			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
 728		} else if (mode == Conversation.MODE_SINGLE
 729				&& conversation.smpRequested()) {
 730			showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
 731		} else if (mode == Conversation.MODE_SINGLE
 732				&& conversation.hasValidOtrSession()
 733				&& (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
 734				&& (!conversation.isOtrFingerprintVerified())) {
 735			showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
 736		} else if (conversation.isMuted()) {
 737			showSnackbar(R.string.notifications_disabled, R.string.enable, this.mUnmuteClickListener);
 738		} else {
 739			hideSnackbar();
 740		}
 741	}
 742
 743	public void updateMessages() {
 744		synchronized (this.messageList) {
 745			if (getView() == null) {
 746				return;
 747			}
 748			final ConversationActivity activity = (ConversationActivity) getActivity();
 749			if (this.conversation != null) {
 750				updateSnackBar(this.conversation);
 751				conversation.populateWithMessages(ConversationFragment.this.messageList);
 752				for (final Message message : this.messageList) {
 753					if (message.getEncryption() == Message.ENCRYPTION_PGP
 754							&& (message.getStatus() == Message.STATUS_RECEIVED || message
 755							.getStatus() >= Message.STATUS_SEND)
 756							&& message.getDownloadable() == null) {
 757						if (!mEncryptedMessages.contains(message)) {
 758							mEncryptedMessages.add(message);
 759						}
 760					}
 761				}
 762				decryptNext();
 763				updateStatusMessages();
 764				this.messageListAdapter.notifyDataSetChanged();
 765				updateChatMsgHint();
 766				if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
 767					activity.sendReadMarkerIfNecessary(conversation);
 768				}
 769				this.updateSendButton();
 770			}
 771		}
 772	}
 773
 774	private void decryptNext() {
 775		Message next = this.mEncryptedMessages.peek();
 776		PgpEngine engine = activity.xmppConnectionService.getPgpEngine();
 777
 778		if (next != null && engine != null && !mDecryptJobRunning) {
 779			mDecryptJobRunning = true;
 780			engine.decrypt(next, new UiCallback<Message>() {
 781
 782				@Override
 783				public void userInputRequried(PendingIntent pi, Message message) {
 784					mDecryptJobRunning = false;
 785					askForPassphraseIntent = pi.getIntentSender();
 786					updateSnackBar(conversation);
 787				}
 788
 789				@Override
 790				public void success(Message message) {
 791					mDecryptJobRunning = false;
 792					try {
 793						mEncryptedMessages.remove();
 794					} catch (final NoSuchElementException ignored) {
 795
 796					}
 797					askForPassphraseIntent = null;
 798					activity.xmppConnectionService.updateMessage(message);
 799				}
 800
 801				@Override
 802				public void error(int error, Message message) {
 803					message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
 804					mDecryptJobRunning = false;
 805					try {
 806						mEncryptedMessages.remove();
 807					} catch (final NoSuchElementException ignored) {
 808
 809					}
 810					activity.xmppConnectionService.updateConversationUi();
 811				}
 812			});
 813		}
 814	}
 815
 816	private void messageSent() {
 817		int size = this.messageList.size();
 818		messagesView.setSelection(size - 1);
 819		mEditMessage.setText("");
 820		updateChatMsgHint();
 821	}
 822
 823	enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
 824
 825	private int getSendButtonImageResource(SendButtonAction action, int status) {
 826		switch (action) {
 827			case TEXT:
 828				switch (status) {
 829					case Presences.CHAT:
 830					case Presences.ONLINE:
 831						return R.drawable.ic_send_text_online;
 832					case Presences.AWAY:
 833						return R.drawable.ic_send_text_away;
 834					case Presences.XA:
 835					case Presences.DND:
 836						return R.drawable.ic_send_text_dnd;
 837					default:
 838						return R.drawable.ic_send_text_offline;
 839				}
 840			case TAKE_PHOTO:
 841				switch (status) {
 842					case Presences.CHAT:
 843					case Presences.ONLINE:
 844						return R.drawable.ic_send_photo_online;
 845					case Presences.AWAY:
 846						return R.drawable.ic_send_photo_away;
 847					case Presences.XA:
 848					case Presences.DND:
 849						return R.drawable.ic_send_photo_dnd;
 850					default:
 851						return R.drawable.ic_send_photo_offline;
 852				}
 853			case RECORD_VOICE:
 854				switch (status) {
 855					case Presences.CHAT:
 856					case Presences.ONLINE:
 857						return R.drawable.ic_send_voice_online;
 858					case Presences.AWAY:
 859						return R.drawable.ic_send_voice_away;
 860					case Presences.XA:
 861					case Presences.DND:
 862						return R.drawable.ic_send_voice_dnd;
 863					default:
 864						return R.drawable.ic_send_voice_offline;
 865				}
 866			case SEND_LOCATION:
 867				switch (status) {
 868					case Presences.CHAT:
 869					case Presences.ONLINE:
 870						return R.drawable.ic_send_location_online;
 871					case Presences.AWAY:
 872						return R.drawable.ic_send_location_away;
 873					case Presences.XA:
 874					case Presences.DND:
 875						return R.drawable.ic_send_location_dnd;
 876					default:
 877						return R.drawable.ic_send_location_offline;
 878				}
 879			case CANCEL:
 880				switch (status) {
 881					case Presences.CHAT:
 882					case Presences.ONLINE:
 883						return R.drawable.ic_send_cancel_online;
 884					case Presences.AWAY:
 885						return R.drawable.ic_send_cancel_away;
 886					case Presences.XA:
 887					case Presences.DND:
 888						return R.drawable.ic_send_cancel_dnd;
 889					default:
 890						return R.drawable.ic_send_cancel_offline;
 891				}
 892			case CHOOSE_PICTURE:
 893				switch (status) {
 894					case Presences.CHAT:
 895					case Presences.ONLINE:
 896						return R.drawable.ic_send_picture_online;
 897					case Presences.AWAY:
 898						return R.drawable.ic_send_picture_away;
 899					case Presences.XA:
 900					case Presences.DND:
 901						return R.drawable.ic_send_picture_dnd;
 902					default:
 903						return R.drawable.ic_send_picture_offline;
 904				}
 905		}
 906		return R.drawable.ic_send_text_offline;
 907	}
 908
 909	public void updateSendButton() {
 910		final Conversation c = this.conversation;
 911		final SendButtonAction action;
 912		final int status;
 913		final boolean empty = this.mEditMessage == null || this.mEditMessage.getText().length() == 0;
 914		final boolean conference = c.getMode() == Conversation.MODE_MULTI;
 915		if (conference && !c.getAccount().httpUploadAvailable()) {
 916			if (empty && c.getNextCounterpart() != null) {
 917				action = SendButtonAction.CANCEL;
 918			} else {
 919				action = SendButtonAction.TEXT;
 920			}
 921		} else {
 922			if (empty) {
 923				if (conference && c.getNextCounterpart() != null) {
 924					action = SendButtonAction.CANCEL;
 925				} else {
 926					String setting = activity.getPreferences().getString("quick_action", "recent");
 927					if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
 928						setting = "location";
 929					} else if (setting.equals("recent")) {
 930						setting = activity.getPreferences().getString("recently_used_quick_action", "text");
 931					}
 932					switch (setting) {
 933						case "photo":
 934							action = SendButtonAction.TAKE_PHOTO;
 935							break;
 936						case "location":
 937							action = SendButtonAction.SEND_LOCATION;
 938							break;
 939						case "voice":
 940							action = SendButtonAction.RECORD_VOICE;
 941							break;
 942						case "picture":
 943							action = SendButtonAction.CHOOSE_PICTURE;
 944							break;
 945						default:
 946							action = SendButtonAction.TEXT;
 947							break;
 948					}
 949				}
 950			} else {
 951				action = SendButtonAction.TEXT;
 952			}
 953		}
 954		if (activity.useSendButtonToIndicateStatus() && c != null
 955				&& c.getAccount().getStatus() == Account.State.ONLINE) {
 956			if (c.getMode() == Conversation.MODE_SINGLE) {
 957				status = c.getContact().getMostAvailableStatus();
 958			} else {
 959				status = c.getMucOptions().online() ? Presences.ONLINE : Presences.OFFLINE;
 960			}
 961		} else {
 962			status = Presences.OFFLINE;
 963		}
 964		this.mSendButton.setTag(action);
 965		this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
 966	}
 967
 968	protected void updateStatusMessages() {
 969		synchronized (this.messageList) {
 970			if (conversation.getMode() == Conversation.MODE_SINGLE) {
 971				ChatState state = conversation.getIncomingChatState();
 972				if (state == ChatState.COMPOSING) {
 973					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
 974				} else if (state == ChatState.PAUSED) {
 975					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
 976				} else {
 977					for (int i = this.messageList.size() - 1; i >= 0; --i) {
 978						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
 979							return;
 980						} else {
 981							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
 982								this.messageList.add(i + 1,
 983										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
 984								return;
 985							}
 986						}
 987					}
 988				}
 989			}
 990		}
 991	}
 992
 993	protected void showSnackbar(final int message, final int action,
 994								final OnClickListener clickListener) {
 995		snackbar.setVisibility(View.VISIBLE);
 996		snackbar.setOnClickListener(null);
 997		snackbarMessage.setText(message);
 998		snackbarMessage.setOnClickListener(null);
 999		snackbarAction.setVisibility(View.VISIBLE);
1000		snackbarAction.setText(action);
1001		snackbarAction.setOnClickListener(clickListener);
1002	}
1003
1004	protected void hideSnackbar() {
1005		snackbar.setVisibility(View.GONE);
1006	}
1007
1008	protected void sendPlainTextMessage(Message message) {
1009		ConversationActivity activity = (ConversationActivity) getActivity();
1010		activity.xmppConnectionService.sendMessage(message);
1011		messageSent();
1012	}
1013
1014	protected void sendPgpMessage(final Message message) {
1015		final ConversationActivity activity = (ConversationActivity) getActivity();
1016		final XmppConnectionService xmppService = activity.xmppConnectionService;
1017		final Contact contact = message.getConversation().getContact();
1018		if (activity.hasPgp()) {
1019			if (conversation.getMode() == Conversation.MODE_SINGLE) {
1020				if (contact.getPgpKeyId() != 0) {
1021					xmppService.getPgpEngine().hasKey(contact,
1022							new UiCallback<Contact>() {
1023
1024								@Override
1025								public void userInputRequried(PendingIntent pi,
1026															  Contact contact) {
1027									activity.runIntent(
1028											pi,
1029											ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1030								}
1031
1032								@Override
1033								public void success(Contact contact) {
1034									messageSent();
1035									activity.encryptTextMessage(message);
1036								}
1037
1038								@Override
1039								public void error(int error, Contact contact) {
1040
1041								}
1042							});
1043
1044				} else {
1045					showNoPGPKeyDialog(false,
1046							new DialogInterface.OnClickListener() {
1047
1048								@Override
1049								public void onClick(DialogInterface dialog,
1050													int which) {
1051									conversation
1052											.setNextEncryption(Message.ENCRYPTION_NONE);
1053									xmppService.databaseBackend
1054											.updateConversation(conversation);
1055									message.setEncryption(Message.ENCRYPTION_NONE);
1056									xmppService.sendMessage(message);
1057									messageSent();
1058								}
1059							});
1060				}
1061			} else {
1062				if (conversation.getMucOptions().pgpKeysInUse()) {
1063					if (!conversation.getMucOptions().everybodyHasKeys()) {
1064						Toast warning = Toast
1065								.makeText(getActivity(),
1066										R.string.missing_public_keys,
1067										Toast.LENGTH_LONG);
1068						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1069						warning.show();
1070					}
1071					activity.encryptTextMessage(message);
1072					messageSent();
1073				} else {
1074					showNoPGPKeyDialog(true,
1075							new DialogInterface.OnClickListener() {
1076
1077								@Override
1078								public void onClick(DialogInterface dialog,
1079													int which) {
1080									conversation
1081											.setNextEncryption(Message.ENCRYPTION_NONE);
1082									message.setEncryption(Message.ENCRYPTION_NONE);
1083									xmppService.databaseBackend
1084											.updateConversation(conversation);
1085									xmppService.sendMessage(message);
1086									messageSent();
1087								}
1088							});
1089				}
1090			}
1091		} else {
1092			activity.showInstallPgpDialog();
1093		}
1094	}
1095
1096	public void showNoPGPKeyDialog(boolean plural,
1097								   DialogInterface.OnClickListener listener) {
1098		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1099		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1100		if (plural) {
1101			builder.setTitle(getString(R.string.no_pgp_keys));
1102			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1103		} else {
1104			builder.setTitle(getString(R.string.no_pgp_key));
1105			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1106		}
1107		builder.setNegativeButton(getString(R.string.cancel), null);
1108		builder.setPositiveButton(getString(R.string.send_unencrypted),
1109				listener);
1110		builder.create().show();
1111	}
1112
1113	protected void sendOtrMessage(final Message message) {
1114		final ConversationActivity activity = (ConversationActivity) getActivity();
1115		final XmppConnectionService xmppService = activity.xmppConnectionService;
1116		activity.selectPresence(message.getConversation(),
1117				new OnPresenceSelected() {
1118
1119					@Override
1120					public void onPresenceSelected() {
1121						message.setCounterpart(conversation.getNextCounterpart());
1122						xmppService.sendMessage(message);
1123						messageSent();
1124					}
1125				});
1126	}
1127
1128	public void appendText(String text) {
1129		if (text == null) {
1130			return;
1131		}
1132		String previous = this.mEditMessage.getText().toString();
1133		if (previous.length() != 0 && !previous.endsWith(" ")) {
1134			text = " " + text;
1135		}
1136		this.mEditMessage.append(text);
1137	}
1138
1139	@Override
1140	public boolean onEnterPressed() {
1141		if (activity.enterIsSend()) {
1142			sendMessage();
1143			return true;
1144		} else {
1145			return false;
1146		}
1147	}
1148
1149	@Override
1150	public void onTypingStarted() {
1151		Account.State status = conversation.getAccount().getStatus();
1152		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1153			activity.xmppConnectionService.sendChatState(conversation);
1154		}
1155		updateSendButton();
1156	}
1157
1158	@Override
1159	public void onTypingStopped() {
1160		Account.State status = conversation.getAccount().getStatus();
1161		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1162			activity.xmppConnectionService.sendChatState(conversation);
1163		}
1164	}
1165
1166	@Override
1167	public void onTextDeleted() {
1168		Account.State status = conversation.getAccount().getStatus();
1169		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1170			activity.xmppConnectionService.sendChatState(conversation);
1171		}
1172		updateSendButton();
1173	}
1174
1175}