ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.ActionBar;
   5import android.app.AlertDialog;
   6import android.app.FragmentTransaction;
   7import android.app.PendingIntent;
   8import android.content.ClipData;
   9import android.content.DialogInterface;
  10import android.content.DialogInterface.OnClickListener;
  11import android.content.Intent;
  12import android.content.IntentSender.SendIntentException;
  13import android.net.Uri;
  14import android.os.Build;
  15import android.os.Bundle;
  16import android.provider.MediaStore;
  17import android.support.v4.widget.SlidingPaneLayout;
  18import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  19import android.util.Log;
  20import android.view.Gravity;
  21import android.view.KeyEvent;
  22import android.view.Menu;
  23import android.view.MenuItem;
  24import android.view.Surface;
  25import android.view.View;
  26import android.widget.AdapterView;
  27import android.widget.AdapterView.OnItemClickListener;
  28import android.widget.ArrayAdapter;
  29import android.widget.CheckBox;
  30import android.widget.PopupMenu;
  31import android.widget.PopupMenu.OnMenuItemClickListener;
  32import android.widget.Toast;
  33
  34import net.java.otr4j.session.SessionStatus;
  35
  36import java.util.ArrayList;
  37import java.util.Iterator;
  38import java.util.List;
  39import java.util.concurrent.atomic.AtomicBoolean;
  40
  41import de.timroes.android.listview.EnhancedListView;
  42import eu.siacs.conversations.Config;
  43import eu.siacs.conversations.R;
  44import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  45import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  46import eu.siacs.conversations.entities.Account;
  47import eu.siacs.conversations.entities.Blockable;
  48import eu.siacs.conversations.entities.Contact;
  49import eu.siacs.conversations.entities.Conversation;
  50import eu.siacs.conversations.entities.Message;
  51import eu.siacs.conversations.services.XmppConnectionService;
  52import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  53import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  54import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  55import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  56import eu.siacs.conversations.utils.ExceptionHelper;
  57import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  58import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  59import eu.siacs.conversations.xmpp.jid.Jid;
  60import org.openintents.openpgp.util.OpenPgpApi;
  61
  62public class ConversationActivity extends XmppActivity
  63	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  64
  65	public static final String ACTION_DOWNLOAD = "eu.siacs.conversations.action.DOWNLOAD";
  66
  67	public static final String VIEW_CONVERSATION = "viewConversation";
  68	public static final String CONVERSATION = "conversationUuid";
  69	public static final String MESSAGE = "messageUuid";
  70	public static final String TEXT = "text";
  71	public static final String NICK = "nick";
  72	public static final String PRIVATE_MESSAGE = "pm";
  73
  74	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  75	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  76	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  77	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  78	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  79	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  80	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  81	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  82	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  83	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  84	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  85	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  86	private static final String STATE_PANEL_OPEN = "state_panel_open";
  87	private static final String STATE_PENDING_URI = "state_pending_uri";
  88
  89	private String mOpenConverstaion = null;
  90	private boolean mPanelOpen = true;
  91	final private List<Uri> mPendingImageUris = new ArrayList<>();
  92	final private List<Uri> mPendingFileUris = new ArrayList<>();
  93	private Uri mPendingGeoUri = null;
  94	private boolean forbidProcessingPendings = false;
  95
  96	private boolean conversationWasSelectedByKeyboard = false;
  97
  98	private View mContentView;
  99
 100	private List<Conversation> conversationList = new ArrayList<>();
 101	private Conversation swipedConversation = null;
 102	private Conversation mSelectedConversation = null;
 103	private EnhancedListView listView;
 104	private ConversationFragment mConversationFragment;
 105
 106	private ArrayAdapter<Conversation> listAdapter;
 107
 108	private Toast prepareFileToast;
 109
 110	private boolean mActivityPaused = false;
 111	private AtomicBoolean mRedirected = new AtomicBoolean(false);
 112
 113	public Conversation getSelectedConversation() {
 114		return this.mSelectedConversation;
 115	}
 116
 117	public void setSelectedConversation(Conversation conversation) {
 118		this.mSelectedConversation = conversation;
 119	}
 120
 121	public void showConversationsOverview() {
 122		if (mContentView instanceof SlidingPaneLayout) {
 123			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 124			mSlidingPaneLayout.openPane();
 125		}
 126	}
 127
 128	@Override
 129	protected String getShareableUri() {
 130		Conversation conversation = getSelectedConversation();
 131		if (conversation != null) {
 132			return conversation.getAccount().getShareableUri();
 133		} else {
 134			return "";
 135		}
 136	}
 137
 138	public void hideConversationsOverview() {
 139		if (mContentView instanceof SlidingPaneLayout) {
 140			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 141			mSlidingPaneLayout.closePane();
 142		}
 143	}
 144
 145	public boolean isConversationsOverviewHideable() {
 146		if (mContentView instanceof SlidingPaneLayout) {
 147			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 148			return mSlidingPaneLayout.isSlideable();
 149		} else {
 150			return false;
 151		}
 152	}
 153
 154	public boolean isConversationsOverviewVisable() {
 155		if (mContentView instanceof SlidingPaneLayout) {
 156			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 157			return mSlidingPaneLayout.isOpen();
 158		} else {
 159			return true;
 160		}
 161	}
 162
 163	@Override
 164	protected void onCreate(final Bundle savedInstanceState) {
 165		super.onCreate(savedInstanceState);
 166		if (savedInstanceState != null) {
 167			mOpenConverstaion = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 168			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 169			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 170			if (pending != null) {
 171				mPendingImageUris.clear();
 172				mPendingImageUris.add(Uri.parse(pending));
 173			}
 174		}
 175
 176		setContentView(R.layout.fragment_conversations_overview);
 177
 178		this.mConversationFragment = new ConversationFragment();
 179		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 180		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 181		transaction.commit();
 182
 183		listView = (EnhancedListView) findViewById(R.id.list);
 184		this.listAdapter = new ConversationAdapter(this, conversationList);
 185		listView.setAdapter(this.listAdapter);
 186
 187		if (getActionBar() != null) {
 188			getActionBar().setDisplayHomeAsUpEnabled(false);
 189			getActionBar().setHomeButtonEnabled(false);
 190		}
 191
 192		listView.setOnItemClickListener(new OnItemClickListener() {
 193
 194			@Override
 195			public void onItemClick(AdapterView<?> arg0, View clickedView,
 196					int position, long arg3) {
 197				if (getSelectedConversation() != conversationList.get(position)) {
 198					setSelectedConversation(conversationList.get(position));
 199					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 200					conversationWasSelectedByKeyboard = false;
 201				}
 202				hideConversationsOverview();
 203				openConversation();
 204			}
 205		});
 206
 207		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 208
 209			@Override
 210			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 211
 212				final int index = listView.getFirstVisiblePosition();
 213				View v = listView.getChildAt(0);
 214				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 215
 216				try {
 217					swipedConversation = listAdapter.getItem(position);
 218				} catch (IndexOutOfBoundsException e) {
 219					return null;
 220				}
 221				listAdapter.remove(swipedConversation);
 222				xmppConnectionService.markRead(swipedConversation);
 223
 224				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 225				if (position == 0 && listAdapter.getCount() == 0) {
 226					endConversation(swipedConversation, false, true);
 227					return null;
 228				} else if (formerlySelected) {
 229					setSelectedConversation(listAdapter.getItem(0));
 230					ConversationActivity.this.mConversationFragment
 231							.reInit(getSelectedConversation());
 232				}
 233
 234				return new EnhancedListView.Undoable() {
 235
 236					@Override
 237					public void undo() {
 238						listAdapter.insert(swipedConversation, position);
 239						if (formerlySelected) {
 240							setSelectedConversation(swipedConversation);
 241							ConversationActivity.this.mConversationFragment
 242									.reInit(getSelectedConversation());
 243						}
 244						swipedConversation = null;
 245						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 246					}
 247
 248					@Override
 249					public void discard() {
 250						if (!swipedConversation.isRead()
 251								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 252							swipedConversation = null;
 253							return;
 254						}
 255						endConversation(swipedConversation, false, false);
 256						swipedConversation = null;
 257					}
 258
 259					@Override
 260					public String getTitle() {
 261						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 262							return getResources().getString(R.string.title_undo_swipe_out_muc);
 263						} else {
 264							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 265						}
 266					}
 267				};
 268			}
 269		});
 270		listView.enableSwipeToDismiss();
 271		listView.setSwipingLayout(R.id.swipeable_item);
 272		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 273		listView.setUndoHideDelay(5000);
 274		listView.setRequireTouchBeforeDismiss(false);
 275
 276		mContentView = findViewById(R.id.content_view_spl);
 277		if (mContentView == null) {
 278			mContentView = findViewById(R.id.content_view_ll);
 279		}
 280		if (mContentView instanceof SlidingPaneLayout) {
 281			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 282			mSlidingPaneLayout.setParallaxDistance(150);
 283			mSlidingPaneLayout
 284				.setShadowResource(R.drawable.es_slidingpane_shadow);
 285			mSlidingPaneLayout.setSliderFadeColor(0);
 286			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 287
 288				@Override
 289				public void onPanelOpened(View arg0) {
 290					updateActionBarTitle();
 291					invalidateOptionsMenu();
 292					hideKeyboard();
 293					if (xmppConnectionServiceBound) {
 294						xmppConnectionService.getNotificationService()
 295							.setOpenConversation(null);
 296					}
 297					closeContextMenu();
 298				}
 299
 300				@Override
 301				public void onPanelClosed(View arg0) {
 302					listView.discardUndo();
 303					openConversation();
 304				}
 305
 306				@Override
 307				public void onPanelSlide(View arg0, float arg1) {
 308					// TODO Auto-generated method stub
 309
 310				}
 311			});
 312		}
 313	}
 314
 315	@Override
 316	public void switchToConversation(Conversation conversation) {
 317		setSelectedConversation(conversation);
 318		runOnUiThread(new Runnable() {
 319			@Override
 320			public void run() {
 321				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 322				openConversation();
 323			}
 324		});
 325	}
 326
 327	private void updateActionBarTitle() {
 328		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 329	}
 330
 331	private void updateActionBarTitle(boolean titleShouldBeName) {
 332		final ActionBar ab = getActionBar();
 333		final Conversation conversation = getSelectedConversation();
 334		if (ab != null) {
 335			if (titleShouldBeName && conversation != null) {
 336				ab.setDisplayHomeAsUpEnabled(true);
 337				ab.setHomeButtonEnabled(true);
 338				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 339					ab.setTitle(conversation.getName());
 340				} else {
 341					ab.setTitle(conversation.getJid().toBareJid().toString());
 342				}
 343			} else {
 344				ab.setDisplayHomeAsUpEnabled(false);
 345				ab.setHomeButtonEnabled(false);
 346				ab.setTitle(R.string.app_name);
 347			}
 348		}
 349	}
 350
 351	private void openConversation() {
 352		this.updateActionBarTitle();
 353		this.invalidateOptionsMenu();
 354		if (xmppConnectionServiceBound) {
 355			final Conversation conversation = getSelectedConversation();
 356			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 357			sendReadMarkerIfNecessary(conversation);
 358		}
 359		listAdapter.notifyDataSetChanged();
 360	}
 361
 362	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 363		if (!mActivityPaused && conversation != null) {
 364			if (!conversation.isRead()) {
 365				xmppConnectionService.sendReadMarker(conversation);
 366			} else {
 367				xmppConnectionService.markRead(conversation);
 368			}
 369		}
 370	}
 371
 372	@Override
 373	public boolean onCreateOptionsMenu(Menu menu) {
 374		getMenuInflater().inflate(R.menu.conversations, menu);
 375		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 376		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 377		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 378		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 379		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 380		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 381		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 382		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 383		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 384		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 385
 386		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 387			menuArchive.setVisible(false);
 388			menuMucDetails.setVisible(false);
 389			menuContactDetails.setVisible(false);
 390			menuSecure.setVisible(false);
 391			menuInviteContact.setVisible(false);
 392			menuAttach.setVisible(false);
 393			menuClearHistory.setVisible(false);
 394			menuMute.setVisible(false);
 395			menuUnmute.setVisible(false);
 396		} else {
 397			menuAdd.setVisible(!isConversationsOverviewHideable());
 398			if (this.getSelectedConversation() != null) {
 399				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 400					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 401						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 402					} else {
 403						menuSecure.setIcon(R.drawable.ic_action_secure);
 404					}
 405				}
 406				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 407					menuContactDetails.setVisible(false);
 408					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 409					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 410					menuSecure.setVisible(!Config.HIDE_PGP_IN_UI); //if pgp is hidden conferences have no choice of encryption
 411				} else {
 412					menuMucDetails.setVisible(false);
 413				}
 414				if (this.getSelectedConversation().isMuted()) {
 415					menuMute.setVisible(false);
 416				} else {
 417					menuUnmute.setVisible(false);
 418				}
 419			}
 420		}
 421		return true;
 422	}
 423
 424	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 425		final Conversation conversation = getSelectedConversation();
 426		final Account account = conversation.getAccount();
 427		final OnPresenceSelected callback = new OnPresenceSelected() {
 428
 429			@Override
 430			public void onPresenceSelected() {
 431				Intent intent = new Intent();
 432				boolean chooser = false;
 433				String fallbackPackageId = null;
 434				switch (attachmentChoice) {
 435					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 436						intent.setAction(Intent.ACTION_GET_CONTENT);
 437						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 438							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
 439						}
 440						intent.setType("image/*");
 441						chooser = true;
 442						break;
 443					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 444						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 445						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 446						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 447						mPendingImageUris.clear();
 448						mPendingImageUris.add(uri);
 449						break;
 450					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 451						chooser = true;
 452						intent.setType("*/*");
 453						intent.addCategory(Intent.CATEGORY_OPENABLE);
 454						intent.setAction(Intent.ACTION_GET_CONTENT);
 455						break;
 456					case ATTACHMENT_CHOICE_RECORD_VOICE:
 457						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 458						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 459						break;
 460					case ATTACHMENT_CHOICE_LOCATION:
 461						intent.setAction("eu.siacs.conversations.location.request");
 462						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 463						break;
 464				}
 465				if (intent.resolveActivity(getPackageManager()) != null) {
 466					if (chooser) {
 467						startActivityForResult(
 468								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 469								attachmentChoice);
 470					} else {
 471						startActivityForResult(intent, attachmentChoice);
 472					}
 473				} else if (fallbackPackageId != null) {
 474					startActivity(getInstallApkIntent(fallbackPackageId));
 475				}
 476			}
 477		};
 478		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 479			conversation.setNextCounterpart(null);
 480			callback.onPresenceSelected();
 481		} else {
 482			selectPresence(conversation, callback);
 483		}
 484	}
 485
 486	private Intent getInstallApkIntent(final String packageId) {
 487		Intent intent = new Intent(Intent.ACTION_VIEW);
 488		intent.setData(Uri.parse("market://details?id=" + packageId));
 489		if (intent.resolveActivity(getPackageManager()) != null) {
 490			return intent;
 491		} else {
 492			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 493			return intent;
 494		}
 495	}
 496
 497	public void attachFile(final int attachmentChoice) {
 498		switch (attachmentChoice) {
 499			case ATTACHMENT_CHOICE_LOCATION:
 500				getPreferences().edit().putString("recently_used_quick_action","location").apply();
 501				break;
 502			case ATTACHMENT_CHOICE_RECORD_VOICE:
 503				getPreferences().edit().putString("recently_used_quick_action","voice").apply();
 504				break;
 505			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 506				getPreferences().edit().putString("recently_used_quick_action","photo").apply();
 507				break;
 508			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 509				getPreferences().edit().putString("recently_used_quick_action","picture").apply();
 510				break;
 511		}
 512		final Conversation conversation = getSelectedConversation();
 513		final int encryption = conversation.getNextEncryption();
 514		final int mode = conversation.getMode();
 515		if (encryption == Message.ENCRYPTION_PGP) {
 516			if (hasPgp()) {
 517				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 518					xmppConnectionService.getPgpEngine().hasKey(
 519							conversation.getContact(),
 520							new UiCallback<Contact>() {
 521
 522								@Override
 523								public void userInputRequried(PendingIntent pi, Contact contact) {
 524									ConversationActivity.this.runIntent(pi, attachmentChoice);
 525								}
 526
 527								@Override
 528								public void success(Contact contact) {
 529									selectPresenceToAttachFile(attachmentChoice, encryption);
 530								}
 531
 532								@Override
 533								public void error(int error, Contact contact) {
 534									displayErrorDialog(error);
 535								}
 536							});
 537				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 538					if (!conversation.getMucOptions().everybodyHasKeys()) {
 539						Toast warning = Toast
 540								.makeText(this,
 541										R.string.missing_public_keys,
 542										Toast.LENGTH_LONG);
 543						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 544						warning.show();
 545					}
 546					selectPresenceToAttachFile(attachmentChoice, encryption);
 547				} else {
 548					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 549						.findFragmentByTag("conversation");
 550					if (fragment != null) {
 551						fragment.showNoPGPKeyDialog(false,
 552								new OnClickListener() {
 553
 554									@Override
 555									public void onClick(DialogInterface dialog,
 556											int which) {
 557										conversation
 558											.setNextEncryption(Message.ENCRYPTION_NONE);
 559										xmppConnectionService.databaseBackend
 560											.updateConversation(conversation);
 561										selectPresenceToAttachFile(attachmentChoice,Message.ENCRYPTION_NONE);
 562									}
 563								});
 564					}
 565				}
 566			} else {
 567				showInstallPgpDialog();
 568			}
 569		} else {
 570			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 571				selectPresenceToAttachFile(attachmentChoice, encryption);
 572			}
 573		}
 574	}
 575
 576	@Override
 577	public boolean onOptionsItemSelected(final MenuItem item) {
 578		if (item.getItemId() == android.R.id.home) {
 579			showConversationsOverview();
 580			return true;
 581		} else if (item.getItemId() == R.id.action_add) {
 582			startActivity(new Intent(this, StartConversationActivity.class));
 583			return true;
 584		} else if (getSelectedConversation() != null) {
 585			switch (item.getItemId()) {
 586				case R.id.action_attach_file:
 587					attachFileDialog();
 588					break;
 589				case R.id.action_archive:
 590					this.endConversation(getSelectedConversation());
 591					break;
 592				case R.id.action_contact_details:
 593					switchToContactDetails(getSelectedConversation().getContact());
 594					break;
 595				case R.id.action_muc_details:
 596					Intent intent = new Intent(this,
 597							ConferenceDetailsActivity.class);
 598					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 599					intent.putExtra("uuid", getSelectedConversation().getUuid());
 600					startActivity(intent);
 601					break;
 602				case R.id.action_invite:
 603					inviteToConversation(getSelectedConversation());
 604					break;
 605				case R.id.action_security:
 606					selectEncryptionDialog(getSelectedConversation());
 607					break;
 608				case R.id.action_clear_history:
 609					clearHistoryDialog(getSelectedConversation());
 610					break;
 611				case R.id.action_mute:
 612					muteConversationDialog(getSelectedConversation());
 613					break;
 614				case R.id.action_unmute:
 615					unmuteConversation(getSelectedConversation());
 616					break;
 617				case R.id.action_block:
 618					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 619					break;
 620				case R.id.action_unblock:
 621					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 622					break;
 623				default:
 624					break;
 625			}
 626			return super.onOptionsItemSelected(item);
 627		} else {
 628			return super.onOptionsItemSelected(item);
 629		}
 630	}
 631
 632	public void endConversation(Conversation conversation) {
 633		endConversation(conversation, true, true);
 634	}
 635
 636	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 637		if (showOverview) {
 638			showConversationsOverview();
 639		}
 640		xmppConnectionService.archiveConversation(conversation);
 641		if (reinit) {
 642			if (conversationList.size() > 0) {
 643				setSelectedConversation(conversationList.get(0));
 644				this.mConversationFragment.reInit(getSelectedConversation());
 645			} else {
 646				setSelectedConversation(null);
 647				if (mRedirected.compareAndSet(false,true)) {
 648					Intent intent = new Intent(this, StartConversationActivity.class);
 649					intent.putExtra("init",true);
 650					startActivity(intent);
 651					finish();
 652				}
 653			}
 654		}
 655	}
 656
 657	@SuppressLint("InflateParams")
 658	protected void clearHistoryDialog(final Conversation conversation) {
 659		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 660		builder.setTitle(getString(R.string.clear_conversation_history));
 661		View dialogView = getLayoutInflater().inflate(
 662				R.layout.dialog_clear_history, null);
 663		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 664			.findViewById(R.id.end_conversation_checkbox);
 665		builder.setView(dialogView);
 666		builder.setNegativeButton(getString(R.string.cancel), null);
 667		builder.setPositiveButton(getString(R.string.delete_messages),
 668				new OnClickListener() {
 669
 670					@Override
 671					public void onClick(DialogInterface dialog, int which) {
 672						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 673						if (endConversationCheckBox.isChecked()) {
 674							endConversation(conversation);
 675						} else {
 676							updateConversationList();
 677							ConversationActivity.this.mConversationFragment.updateMessages();
 678						}
 679					}
 680				});
 681		builder.create().show();
 682	}
 683
 684	protected void attachFileDialog() {
 685		View menuAttachFile = findViewById(R.id.action_attach_file);
 686		if (menuAttachFile == null) {
 687			return;
 688		}
 689		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 690		attachFilePopup.inflate(R.menu.attachment_choices);
 691		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 692			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 693		}
 694		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 695			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 696		}
 697		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 698
 699			@Override
 700			public boolean onMenuItemClick(MenuItem item) {
 701				switch (item.getItemId()) {
 702					case R.id.attach_choose_picture:
 703						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 704						break;
 705					case R.id.attach_take_picture:
 706						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 707						break;
 708					case R.id.attach_choose_file:
 709						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 710						break;
 711					case R.id.attach_record_voice:
 712						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 713						break;
 714					case R.id.attach_location:
 715						attachFile(ATTACHMENT_CHOICE_LOCATION);
 716						break;
 717				}
 718				return false;
 719			}
 720		});
 721		attachFilePopup.show();
 722	}
 723
 724	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 725		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 726			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 727			return;
 728		}
 729		if (view == null) {
 730			return;
 731		}
 732		PopupMenu popup = new PopupMenu(this, view);
 733		popup.inflate(R.menu.verification_choices);
 734		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 735			@Override
 736			public boolean onMenuItemClick(MenuItem menuItem) {
 737				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 738				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 739				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 740				intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
 741				switch (menuItem.getItemId()) {
 742					case R.id.scan_fingerprint:
 743						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 744						break;
 745					case R.id.ask_question:
 746						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 747						break;
 748					case R.id.manual_verification:
 749						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 750						break;
 751				}
 752				startActivity(intent);
 753				return true;
 754			}
 755		});
 756		popup.show();
 757	}
 758
 759	protected void selectEncryptionDialog(final Conversation conversation) {
 760		View menuItemView = findViewById(R.id.action_security);
 761		if (menuItemView == null) {
 762			return;
 763		}
 764		PopupMenu popup = new PopupMenu(this, menuItemView);
 765		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 766			.findFragmentByTag("conversation");
 767		if (fragment != null) {
 768			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 769
 770				@Override
 771				public boolean onMenuItemClick(MenuItem item) {
 772					switch (item.getItemId()) {
 773						case R.id.encryption_choice_none:
 774							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 775							item.setChecked(true);
 776							break;
 777						case R.id.encryption_choice_otr:
 778							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 779							item.setChecked(true);
 780							break;
 781						case R.id.encryption_choice_pgp:
 782							if (hasPgp()) {
 783								if (conversation.getAccount().getPgpSignature() != null) {
 784									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 785									item.setChecked(true);
 786								} else {
 787									announcePgp(conversation.getAccount(),conversation);
 788								}
 789							} else {
 790								showInstallPgpDialog();
 791							}
 792							break;
 793						case R.id.encryption_choice_axolotl:
 794							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 795									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 796							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 797							item.setChecked(true);
 798							break;
 799						default:
 800							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 801							break;
 802					}
 803					xmppConnectionService.databaseBackend.updateConversation(conversation);
 804					fragment.updateChatMsgHint();
 805					invalidateOptionsMenu();
 806					refreshUi();
 807					return true;
 808				}
 809			});
 810			popup.inflate(R.menu.encryption_choices);
 811			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 812			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 813			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 814			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 815			pgp.setVisible(!Config.HIDE_PGP_IN_UI);
 816			if (conversation.getMode() == Conversation.MODE_MULTI) {
 817				otr.setVisible(false);
 818				axolotl.setVisible(false);
 819			} else if (!conversation.getAccount().getAxolotlService().isContactAxolotlCapable(conversation.getContact())) {
 820				axolotl.setEnabled(false);
 821			}
 822			switch (conversation.getNextEncryption()) {
 823				case Message.ENCRYPTION_NONE:
 824					none.setChecked(true);
 825					break;
 826				case Message.ENCRYPTION_OTR:
 827					otr.setChecked(true);
 828					break;
 829				case Message.ENCRYPTION_PGP:
 830					pgp.setChecked(true);
 831					break;
 832				case Message.ENCRYPTION_AXOLOTL:
 833					axolotl.setChecked(true);
 834					break;
 835				default:
 836					none.setChecked(true);
 837					break;
 838			}
 839			popup.show();
 840		}
 841	}
 842
 843	protected void muteConversationDialog(final Conversation conversation) {
 844		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 845		builder.setTitle(R.string.disable_notifications);
 846		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 847		builder.setItems(R.array.mute_options_descriptions,
 848				new OnClickListener() {
 849
 850					@Override
 851					public void onClick(final DialogInterface dialog, final int which) {
 852						final long till;
 853						if (durations[which] == -1) {
 854							till = Long.MAX_VALUE;
 855						} else {
 856							till = System.currentTimeMillis() + (durations[which] * 1000);
 857						}
 858						conversation.setMutedTill(till);
 859						ConversationActivity.this.xmppConnectionService.databaseBackend
 860								.updateConversation(conversation);
 861						updateConversationList();
 862						ConversationActivity.this.mConversationFragment.updateMessages();
 863						invalidateOptionsMenu();
 864					}
 865				});
 866		builder.create().show();
 867	}
 868
 869	public void unmuteConversation(final Conversation conversation) {
 870		conversation.setMutedTill(0);
 871		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 872		updateConversationList();
 873		ConversationActivity.this.mConversationFragment.updateMessages();
 874		invalidateOptionsMenu();
 875	}
 876
 877	@Override
 878	public void onBackPressed() {
 879		if (!isConversationsOverviewVisable()) {
 880			showConversationsOverview();
 881		} else {
 882			moveTaskToBack(true);
 883		}
 884	}
 885
 886	@Override
 887	public boolean onKeyUp(int key, KeyEvent event) {
 888		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 889		final int upKey;
 890		final int downKey;
 891		switch(rotation) {
 892			case Surface.ROTATION_90:
 893				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 894				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 895				break;
 896			case Surface.ROTATION_180:
 897				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 898				downKey = KeyEvent.KEYCODE_DPAD_UP;
 899				break;
 900			case Surface.ROTATION_270:
 901				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 902				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
 903				break;
 904			default:
 905				upKey = KeyEvent.KEYCODE_DPAD_UP;
 906				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
 907		}
 908		final boolean modifier = event.isCtrlPressed() || event.isAltPressed();
 909		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
 910			toggleConversationsOverview();
 911			return true;
 912		} else if (modifier && key == downKey) {
 913			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 914				showConversationsOverview();;
 915			}
 916			return selectDownConversation();
 917		} else if (modifier && key == upKey) {
 918			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 919				showConversationsOverview();
 920			}
 921			return selectUpConversation();
 922		} else if (modifier && key == KeyEvent.KEYCODE_1) {
 923			return openConversationByIndex(0);
 924		} else if (modifier && key == KeyEvent.KEYCODE_2) {
 925			return openConversationByIndex(1);
 926		} else if (modifier && key == KeyEvent.KEYCODE_3) {
 927			return openConversationByIndex(2);
 928		} else if (modifier && key == KeyEvent.KEYCODE_4) {
 929			return openConversationByIndex(3);
 930		} else if (modifier && key == KeyEvent.KEYCODE_5) {
 931			return openConversationByIndex(4);
 932		} else if (modifier && key == KeyEvent.KEYCODE_6) {
 933			return openConversationByIndex(5);
 934		} else if (modifier && key == KeyEvent.KEYCODE_7) {
 935			return openConversationByIndex(6);
 936		} else if (modifier && key == KeyEvent.KEYCODE_8) {
 937			return openConversationByIndex(7);
 938		} else if (modifier && key == KeyEvent.KEYCODE_9) {
 939			return openConversationByIndex(8);
 940		} else if (modifier && key == KeyEvent.KEYCODE_0) {
 941			return openConversationByIndex(9);
 942		} else {
 943			return super.onKeyUp(key, event);
 944		}
 945	}
 946
 947	private void toggleConversationsOverview() {
 948		if (isConversationsOverviewVisable()) {
 949			hideConversationsOverview();
 950			if (mConversationFragment != null) {
 951				mConversationFragment.setFocusOnInputField();
 952			}
 953		} else {
 954			showConversationsOverview();
 955		}
 956	}
 957
 958	private boolean selectUpConversation() {
 959		if (this.mSelectedConversation != null) {
 960			int index = this.conversationList.indexOf(this.mSelectedConversation);
 961			if (index > 0) {
 962				return openConversationByIndex(index - 1);
 963			}
 964		}
 965		return false;
 966	}
 967
 968	private boolean selectDownConversation() {
 969		if (this.mSelectedConversation != null) {
 970			int index = this.conversationList.indexOf(this.mSelectedConversation);
 971			if (index != -1 && index < this.conversationList.size() - 1) {
 972				return openConversationByIndex(index + 1);
 973			}
 974		}
 975		return false;
 976	}
 977
 978	private boolean openConversationByIndex(int index) {
 979		try {
 980			this.conversationWasSelectedByKeyboard = true;
 981			setSelectedConversation(this.conversationList.get(index));
 982			this.mConversationFragment.reInit(getSelectedConversation());
 983			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
 984				this.listView.setSelection(index);
 985			}
 986			openConversation();
 987			return true;
 988		} catch (IndexOutOfBoundsException e) {
 989			return false;
 990		}
 991	}
 992
 993	@Override
 994	protected void onNewIntent(final Intent intent) {
 995		if (xmppConnectionServiceBound) {
 996			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
 997				handleViewConversationIntent(intent);
 998			}
 999		} else {
1000			setIntent(intent);
1001		}
1002	}
1003
1004	@Override
1005	public void onStart() {
1006		super.onStart();
1007		this.mRedirected.set(false);
1008		if (this.xmppConnectionServiceBound) {
1009			this.onBackendConnected();
1010		}
1011		if (conversationList.size() >= 1) {
1012			this.onConversationUpdate();
1013		}
1014	}
1015
1016	@Override
1017	public void onPause() {
1018		listView.discardUndo();
1019		super.onPause();
1020		this.mActivityPaused = true;
1021		if (this.xmppConnectionServiceBound) {
1022			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
1023		}
1024	}
1025
1026	@Override
1027	public void onResume() {
1028		super.onResume();
1029		final int theme = findTheme();
1030		final boolean usingEnterKey = usingEnterKey();
1031		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1032			recreate();
1033		}
1034		this.mActivityPaused = false;
1035		if (this.xmppConnectionServiceBound) {
1036			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1037		}
1038
1039		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1040			sendReadMarkerIfNecessary(getSelectedConversation());
1041		}
1042
1043	}
1044
1045	@Override
1046	public void onSaveInstanceState(final Bundle savedInstanceState) {
1047		Conversation conversation = getSelectedConversation();
1048		if (conversation != null) {
1049			savedInstanceState.putString(STATE_OPEN_CONVERSATION,
1050					conversation.getUuid());
1051		}
1052		savedInstanceState.putBoolean(STATE_PANEL_OPEN,
1053				isConversationsOverviewVisable());
1054		if (this.mPendingImageUris.size() >= 1) {
1055			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1056		}
1057		super.onSaveInstanceState(savedInstanceState);
1058	}
1059
1060	@Override
1061	void onBackendConnected() {
1062		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1063		updateConversationList();
1064
1065		if (mPendingConferenceInvite != null) {
1066			mPendingConferenceInvite.execute(this);
1067			mPendingConferenceInvite = null;
1068		}
1069
1070		if (xmppConnectionService.getAccounts().size() == 0) {
1071			if (mRedirected.compareAndSet(false,true)) {
1072				if (Config.X509_VERIFICATION) {
1073					startActivity(new Intent(this, ManageAccountActivity.class));
1074				} else {
1075					startActivity(new Intent(this, EditAccountActivity.class));
1076				}
1077				finish();
1078			}
1079		} else if (conversationList.size() <= 0) {
1080			if (mRedirected.compareAndSet(false,true)) {
1081				Intent intent = new Intent(this, StartConversationActivity.class);
1082				intent.putExtra("init",true);
1083				startActivity(intent);
1084				finish();
1085			}
1086		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1087			handleViewConversationIntent(getIntent());
1088		} else if (selectConversationByUuid(mOpenConverstaion)) {
1089			if (mPanelOpen) {
1090				showConversationsOverview();
1091			} else {
1092				if (isConversationsOverviewHideable()) {
1093					openConversation();
1094				}
1095			}
1096			this.mConversationFragment.reInit(getSelectedConversation());
1097			mOpenConverstaion = null;
1098		} else if (getSelectedConversation() == null) {
1099			showConversationsOverview();
1100			mPendingImageUris.clear();
1101			mPendingFileUris.clear();
1102			mPendingGeoUri = null;
1103			setSelectedConversation(conversationList.get(0));
1104			this.mConversationFragment.reInit(getSelectedConversation());
1105		} else {
1106			this.mConversationFragment.messageListAdapter.updatePreferences();
1107			this.mConversationFragment.messagesView.invalidateViews();
1108			this.mConversationFragment.setupIme();
1109		}
1110
1111		if(!forbidProcessingPendings) {
1112			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1113				Uri foo = i.next();
1114				attachImageToConversation(getSelectedConversation(), foo);
1115			}
1116
1117			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1118				attachFileToConversation(getSelectedConversation(), i.next());
1119			}
1120
1121			if (mPendingGeoUri != null) {
1122				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1123				mPendingGeoUri = null;
1124			}
1125		}
1126		forbidProcessingPendings = false;
1127
1128		ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
1129		setIntent(new Intent());
1130	}
1131
1132	private void handleViewConversationIntent(final Intent intent) {
1133		final String uuid = intent.getStringExtra(CONVERSATION);
1134		final String downloadUuid = intent.getStringExtra(MESSAGE);
1135		final String text = intent.getStringExtra(TEXT);
1136		final String nick = intent.getStringExtra(NICK);
1137		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE,false);
1138		if (selectConversationByUuid(uuid)) {
1139			this.mConversationFragment.reInit(getSelectedConversation());
1140			if (nick != null) {
1141				if (pm) {
1142					Jid jid = getSelectedConversation().getJid();
1143					try {
1144						Jid next = Jid.fromParts(jid.getLocalpart(),jid.getDomainpart(),nick);
1145						this.mConversationFragment.privateMessageWith(next);
1146					} catch (final InvalidJidException ignored) {
1147						//do nothing
1148					}
1149				} else {
1150					this.mConversationFragment.highlightInConference(nick);
1151				}
1152			} else {
1153				this.mConversationFragment.appendText(text);
1154			}
1155			hideConversationsOverview();
1156			openConversation();
1157			if (mContentView instanceof SlidingPaneLayout) {
1158				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1159			}
1160			if (downloadUuid != null) {
1161				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1162				if (message != null) {
1163					mConversationFragment.messageListAdapter.startDownloadable(message);
1164				}
1165			}
1166		}
1167	}
1168
1169	private boolean selectConversationByUuid(String uuid) {
1170		if (uuid == null) {
1171			return false;
1172		}
1173		for (Conversation aConversationList : conversationList) {
1174			if (aConversationList.getUuid().equals(uuid)) {
1175				setSelectedConversation(aConversationList);
1176				return true;
1177			}
1178		}
1179		return false;
1180	}
1181
1182	@Override
1183	protected void unregisterListeners() {
1184		super.unregisterListeners();
1185		xmppConnectionService.getNotificationService().setOpenConversation(null);
1186	}
1187
1188	@SuppressLint("NewApi")
1189	private static List<Uri> extractUriFromIntent(final Intent intent) {
1190		List<Uri> uris = new ArrayList<>();
1191		Uri uri = intent.getData();
1192		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1193			ClipData clipData = intent.getClipData();
1194			for(int i = 0; i < clipData.getItemCount(); ++i) {
1195				uris.add(clipData.getItemAt(i).getUri());
1196			}
1197		} else {
1198			uris.add(uri);
1199		}
1200		return uris;
1201	}
1202
1203	@Override
1204	protected void onActivityResult(int requestCode, int resultCode,
1205			final Intent data) {
1206		super.onActivityResult(requestCode, resultCode, data);
1207		if (resultCode == RESULT_OK) {
1208			if (requestCode == REQUEST_DECRYPT_PGP) {
1209				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1210			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1211				if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1212					mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1213					announcePgp(mSelectedConversation.getAccount(), null);
1214				} else {
1215					choosePgpSignId(mSelectedConversation.getAccount());
1216				}
1217			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1218				announcePgp(mSelectedConversation.getAccount(), null);
1219			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1220				mPendingImageUris.clear();
1221				mPendingImageUris.addAll(extractUriFromIntent(data));
1222				if (xmppConnectionServiceBound) {
1223					for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1224						attachImageToConversation(getSelectedConversation(),i.next());
1225					}
1226				}
1227			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1228				mPendingFileUris.clear();
1229				mPendingFileUris.addAll(extractUriFromIntent(data));
1230				if (xmppConnectionServiceBound) {
1231					for(Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1232						attachFileToConversation(getSelectedConversation(), i.next());
1233					}
1234				}
1235			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1236				if (mPendingImageUris.size() == 1) {
1237					Uri uri = mPendingImageUris.get(0);
1238					if (xmppConnectionServiceBound) {
1239						attachImageToConversation(getSelectedConversation(), uri);
1240						mPendingImageUris.clear();
1241					}
1242					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1243					intent.setData(uri);
1244					sendBroadcast(intent);
1245				} else {
1246					mPendingImageUris.clear();
1247				}
1248			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1249				double latitude = data.getDoubleExtra("latitude",0);
1250				double longitude = data.getDoubleExtra("longitude",0);
1251				this.mPendingGeoUri = Uri.parse("geo:"+String.valueOf(latitude)+","+String.valueOf(longitude));
1252				if (xmppConnectionServiceBound) {
1253					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1254					this.mPendingGeoUri = null;
1255				}
1256			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1257				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1258				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1259			}
1260		} else {
1261			mPendingImageUris.clear();
1262			mPendingFileUris.clear();
1263			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1264				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1265			}
1266		}
1267	}
1268
1269	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1270		if (conversation == null) {
1271			return;
1272		}
1273		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1274
1275			@Override
1276			public void success(Message message) {
1277				xmppConnectionService.sendMessage(message);
1278			}
1279
1280			@Override
1281			public void error(int errorCode, Message object) {
1282
1283			}
1284
1285			@Override
1286			public void userInputRequried(PendingIntent pi, Message object) {
1287
1288			}
1289		});
1290	}
1291
1292	private void attachFileToConversation(Conversation conversation, Uri uri) {
1293		if (conversation == null) {
1294			return;
1295		}
1296		prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1297		prepareFileToast.show();
1298		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1299			@Override
1300			public void success(Message message) {
1301				hidePrepareFileToast();
1302				xmppConnectionService.sendMessage(message);
1303			}
1304
1305			@Override
1306			public void error(int errorCode, Message message) {
1307				displayErrorDialog(errorCode);
1308			}
1309
1310			@Override
1311			public void userInputRequried(PendingIntent pi, Message message) {
1312
1313			}
1314		});
1315	}
1316
1317	private void attachImageToConversation(Conversation conversation, Uri uri) {
1318		if (conversation == null) {
1319			return;
1320		}
1321		prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1322		prepareFileToast.show();
1323		xmppConnectionService.attachImageToConversation(conversation, uri,
1324				new UiCallback<Message>() {
1325
1326					@Override
1327					public void userInputRequried(PendingIntent pi,
1328												  Message object) {
1329						hidePrepareFileToast();
1330					}
1331
1332					@Override
1333					public void success(Message message) {
1334						xmppConnectionService.sendMessage(message);
1335					}
1336
1337					@Override
1338					public void error(int error, Message message) {
1339						hidePrepareFileToast();
1340						displayErrorDialog(error);
1341					}
1342				});
1343	}
1344
1345	private void hidePrepareFileToast() {
1346		if (prepareFileToast != null) {
1347			runOnUiThread(new Runnable() {
1348
1349				@Override
1350				public void run() {
1351					prepareFileToast.cancel();
1352				}
1353			});
1354		}
1355	}
1356
1357	public void updateConversationList() {
1358		xmppConnectionService
1359			.populateWithOrderedConversations(conversationList);
1360		if (swipedConversation != null) {
1361			if (swipedConversation.isRead()) {
1362				conversationList.remove(swipedConversation);
1363			} else {
1364				listView.discardUndo();
1365			}
1366		}
1367		listAdapter.notifyDataSetChanged();
1368	}
1369
1370	public void runIntent(PendingIntent pi, int requestCode) {
1371		try {
1372			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1373					null, 0, 0, 0);
1374		} catch (final SendIntentException ignored) {
1375		}
1376	}
1377
1378	public void encryptTextMessage(Message message) {
1379		xmppConnectionService.getPgpEngine().encrypt(message,
1380				new UiCallback<Message>() {
1381
1382					@Override
1383					public void userInputRequried(PendingIntent pi,
1384												  Message message) {
1385						ConversationActivity.this.runIntent(pi,
1386								ConversationActivity.REQUEST_SEND_MESSAGE);
1387					}
1388
1389					@Override
1390					public void success(Message message) {
1391						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1392						xmppConnectionService.sendMessage(message);
1393					}
1394
1395					@Override
1396					public void error(int error, Message message) {
1397
1398					}
1399				});
1400	}
1401
1402	public boolean useSendButtonToIndicateStatus() {
1403		return getPreferences().getBoolean("send_button_status", false);
1404	}
1405
1406	public boolean indicateReceived() {
1407		return getPreferences().getBoolean("indicate_received", false);
1408	}
1409
1410	public boolean useWhiteBackground() {
1411		return getPreferences().getBoolean("use_white_background",false);
1412	}
1413
1414	protected boolean trustKeysIfNeeded(int requestCode) {
1415		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1416	}
1417
1418	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1419		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1420		boolean hasPendingKeys = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED,
1421				mSelectedConversation.getContact()).isEmpty()
1422				|| !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1423		boolean hasNoTrustedKeys = axolotlService.getNumTrustedKeys(mSelectedConversation.getContact()) == 0;
1424		if( hasPendingKeys || hasNoTrustedKeys) {
1425			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1426			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1427			intent.putExtra("contact", mSelectedConversation.getContact().getJid().toBareJid().toString());
1428			intent.putExtra("account", mSelectedConversation.getAccount().getJid().toBareJid().toString());
1429			intent.putExtra("choice", attachmentChoice);
1430			intent.putExtra("has_no_trusted", hasNoTrustedKeys);
1431			startActivityForResult(intent, requestCode);
1432			return true;
1433		} else {
1434			return false;
1435		}
1436	}
1437
1438	@Override
1439	protected void refreshUiReal() {
1440		updateConversationList();
1441		if (conversationList.size() > 0) {
1442			ConversationActivity.this.mConversationFragment.updateMessages();
1443			updateActionBarTitle();
1444			invalidateOptionsMenu();
1445		}
1446	}
1447
1448	@Override
1449	public void onAccountUpdate() {
1450		this.refreshUi();
1451	}
1452
1453	@Override
1454	public void onConversationUpdate() {
1455		this.refreshUi();
1456	}
1457
1458	@Override
1459	public void onRosterUpdate() {
1460		this.refreshUi();
1461	}
1462
1463	@Override
1464	public void OnUpdateBlocklist(Status status) {
1465		this.refreshUi();
1466	}
1467
1468	public void unblockConversation(final Blockable conversation) {
1469		xmppConnectionService.sendUnblockRequest(conversation);
1470	}
1471
1472	public boolean enterIsSend() {
1473		return getPreferences().getBoolean("enter_is_send",false);
1474	}
1475
1476	@Override
1477	public void onShowErrorToast(final int resId) {
1478		runOnUiThread(new Runnable() {
1479			@Override
1480			public void run() {
1481				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1482			}
1483		});
1484	}
1485
1486	public boolean highlightSelectedConversations() {
1487		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1488	}
1489}