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