ConversationFragment.java

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