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