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			if (conversation.getMode() == Conversation.MODE_MULTI) {
 819				otr.setVisible(false);
 820				axolotl.setVisible(false);
 821			} else if (!conversation.getAccount().getAxolotlService().isContactAxolotlCapable(conversation.getContact())) {
 822				axolotl.setEnabled(false);
 823			}
 824			switch (conversation.getNextEncryption()) {
 825				case Message.ENCRYPTION_NONE:
 826					none.setChecked(true);
 827					break;
 828				case Message.ENCRYPTION_OTR:
 829					otr.setChecked(true);
 830					break;
 831				case Message.ENCRYPTION_PGP:
 832					pgp.setChecked(true);
 833					break;
 834				case Message.ENCRYPTION_AXOLOTL:
 835					axolotl.setChecked(true);
 836					break;
 837				default:
 838					none.setChecked(true);
 839					break;
 840			}
 841			popup.show();
 842		}
 843	}
 844
 845	protected void muteConversationDialog(final Conversation conversation) {
 846		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 847		builder.setTitle(R.string.disable_notifications);
 848		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 849		builder.setItems(R.array.mute_options_descriptions,
 850				new OnClickListener() {
 851
 852					@Override
 853					public void onClick(final DialogInterface dialog, final int which) {
 854						final long till;
 855						if (durations[which] == -1) {
 856							till = Long.MAX_VALUE;
 857						} else {
 858							till = System.currentTimeMillis() + (durations[which] * 1000);
 859						}
 860						conversation.setMutedTill(till);
 861						ConversationActivity.this.xmppConnectionService.databaseBackend
 862								.updateConversation(conversation);
 863						updateConversationList();
 864						ConversationActivity.this.mConversationFragment.updateMessages();
 865						invalidateOptionsMenu();
 866					}
 867				});
 868		builder.create().show();
 869	}
 870
 871	public void unmuteConversation(final Conversation conversation) {
 872		conversation.setMutedTill(0);
 873		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 874		updateConversationList();
 875		ConversationActivity.this.mConversationFragment.updateMessages();
 876		invalidateOptionsMenu();
 877	}
 878
 879	@Override
 880	public void onBackPressed() {
 881		if (!isConversationsOverviewVisable()) {
 882			showConversationsOverview();
 883		} else {
 884			moveTaskToBack(true);
 885		}
 886	}
 887
 888	@Override
 889	public boolean onKeyUp(int key, KeyEvent event) {
 890		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 891		final int upKey;
 892		final int downKey;
 893		switch(rotation) {
 894			case Surface.ROTATION_90:
 895				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 896				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 897				break;
 898			case Surface.ROTATION_180:
 899				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 900				downKey = KeyEvent.KEYCODE_DPAD_UP;
 901				break;
 902			case Surface.ROTATION_270:
 903				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 904				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
 905				break;
 906			default:
 907				upKey = KeyEvent.KEYCODE_DPAD_UP;
 908				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
 909		}
 910		final boolean modifier = event.isCtrlPressed() || event.isAltPressed();
 911		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
 912			toggleConversationsOverview();
 913			return true;
 914		} else if (modifier && key == downKey) {
 915			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 916				showConversationsOverview();;
 917			}
 918			return selectDownConversation();
 919		} else if (modifier && key == upKey) {
 920			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 921				showConversationsOverview();
 922			}
 923			return selectUpConversation();
 924		} else if (modifier && key == KeyEvent.KEYCODE_1) {
 925			return openConversationByIndex(0);
 926		} else if (modifier && key == KeyEvent.KEYCODE_2) {
 927			return openConversationByIndex(1);
 928		} else if (modifier && key == KeyEvent.KEYCODE_3) {
 929			return openConversationByIndex(2);
 930		} else if (modifier && key == KeyEvent.KEYCODE_4) {
 931			return openConversationByIndex(3);
 932		} else if (modifier && key == KeyEvent.KEYCODE_5) {
 933			return openConversationByIndex(4);
 934		} else if (modifier && key == KeyEvent.KEYCODE_6) {
 935			return openConversationByIndex(5);
 936		} else if (modifier && key == KeyEvent.KEYCODE_7) {
 937			return openConversationByIndex(6);
 938		} else if (modifier && key == KeyEvent.KEYCODE_8) {
 939			return openConversationByIndex(7);
 940		} else if (modifier && key == KeyEvent.KEYCODE_9) {
 941			return openConversationByIndex(8);
 942		} else if (modifier && key == KeyEvent.KEYCODE_0) {
 943			return openConversationByIndex(9);
 944		} else {
 945			return super.onKeyUp(key, event);
 946		}
 947	}
 948
 949	private void toggleConversationsOverview() {
 950		if (isConversationsOverviewVisable()) {
 951			hideConversationsOverview();
 952			if (mConversationFragment != null) {
 953				mConversationFragment.setFocusOnInputField();
 954			}
 955		} else {
 956			showConversationsOverview();
 957		}
 958	}
 959
 960	private boolean selectUpConversation() {
 961		if (this.mSelectedConversation != null) {
 962			int index = this.conversationList.indexOf(this.mSelectedConversation);
 963			if (index > 0) {
 964				return openConversationByIndex(index - 1);
 965			}
 966		}
 967		return false;
 968	}
 969
 970	private boolean selectDownConversation() {
 971		if (this.mSelectedConversation != null) {
 972			int index = this.conversationList.indexOf(this.mSelectedConversation);
 973			if (index != -1 && index < this.conversationList.size() - 1) {
 974				return openConversationByIndex(index + 1);
 975			}
 976		}
 977		return false;
 978	}
 979
 980	private boolean openConversationByIndex(int index) {
 981		try {
 982			this.conversationWasSelectedByKeyboard = true;
 983			setSelectedConversation(this.conversationList.get(index));
 984			this.mConversationFragment.reInit(getSelectedConversation());
 985			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
 986				this.listView.setSelection(index);
 987			}
 988			openConversation();
 989			return true;
 990		} catch (IndexOutOfBoundsException e) {
 991			return false;
 992		}
 993	}
 994
 995	@Override
 996	protected void onNewIntent(final Intent intent) {
 997		if (xmppConnectionServiceBound) {
 998			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
 999				handleViewConversationIntent(intent);
1000			}
1001		} else {
1002			setIntent(intent);
1003		}
1004	}
1005
1006	@Override
1007	public void onStart() {
1008		super.onStart();
1009		this.mRedirected.set(false);
1010		if (this.xmppConnectionServiceBound) {
1011			this.onBackendConnected();
1012		}
1013		if (conversationList.size() >= 1) {
1014			this.onConversationUpdate();
1015		}
1016	}
1017
1018	@Override
1019	public void onPause() {
1020		listView.discardUndo();
1021		super.onPause();
1022		this.mActivityPaused = true;
1023		if (this.xmppConnectionServiceBound) {
1024			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
1025		}
1026	}
1027
1028	@Override
1029	public void onResume() {
1030		super.onResume();
1031		final int theme = findTheme();
1032		final boolean usingEnterKey = usingEnterKey();
1033		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1034			recreate();
1035		}
1036		this.mActivityPaused = false;
1037		if (this.xmppConnectionServiceBound) {
1038			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1039		}
1040
1041		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1042			sendReadMarkerIfNecessary(getSelectedConversation());
1043		}
1044
1045	}
1046
1047	@Override
1048	public void onSaveInstanceState(final Bundle savedInstanceState) {
1049		Conversation conversation = getSelectedConversation();
1050		if (conversation != null) {
1051			savedInstanceState.putString(STATE_OPEN_CONVERSATION,
1052					conversation.getUuid());
1053		}
1054		savedInstanceState.putBoolean(STATE_PANEL_OPEN,
1055				isConversationsOverviewVisable());
1056		if (this.mPendingImageUris.size() >= 1) {
1057			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1058		}
1059		super.onSaveInstanceState(savedInstanceState);
1060	}
1061
1062	@Override
1063	void onBackendConnected() {
1064		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1065		updateConversationList();
1066
1067		if (mPendingConferenceInvite != null) {
1068			mPendingConferenceInvite.execute(this);
1069			mPendingConferenceInvite = null;
1070		}
1071
1072		if (xmppConnectionService.getAccounts().size() == 0) {
1073			if (mRedirected.compareAndSet(false,true)) {
1074				if (Config.X509_VERIFICATION) {
1075					startActivity(new Intent(this, ManageAccountActivity.class));
1076				} else {
1077					startActivity(new Intent(this, EditAccountActivity.class));
1078				}
1079				finish();
1080			}
1081		} else if (conversationList.size() <= 0) {
1082			if (mRedirected.compareAndSet(false,true)) {
1083				Intent intent = new Intent(this, StartConversationActivity.class);
1084				intent.putExtra("init",true);
1085				startActivity(intent);
1086				finish();
1087			}
1088		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1089			handleViewConversationIntent(getIntent());
1090		} else if (selectConversationByUuid(mOpenConverstaion)) {
1091			if (mPanelOpen) {
1092				showConversationsOverview();
1093			} else {
1094				if (isConversationsOverviewHideable()) {
1095					openConversation();
1096				}
1097			}
1098			this.mConversationFragment.reInit(getSelectedConversation());
1099			mOpenConverstaion = null;
1100		} else if (getSelectedConversation() == null) {
1101			showConversationsOverview();
1102			mPendingImageUris.clear();
1103			mPendingFileUris.clear();
1104			mPendingGeoUri = null;
1105			setSelectedConversation(conversationList.get(0));
1106			mPostponedActivityResult = null;
1107			this.mConversationFragment.reInit(getSelectedConversation());
1108		} else {
1109			this.mConversationFragment.messageListAdapter.updatePreferences();
1110			this.mConversationFragment.messagesView.invalidateViews();
1111			this.mConversationFragment.setupIme();
1112		}
1113
1114		if (this.mPostponedActivityResult != null) {
1115			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1116		}
1117
1118		if(!forbidProcessingPendings) {
1119			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1120				Uri foo = i.next();
1121				attachImageToConversation(getSelectedConversation(), foo);
1122			}
1123
1124			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1125				attachFileToConversation(getSelectedConversation(), i.next());
1126			}
1127
1128			if (mPendingGeoUri != null) {
1129				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1130				mPendingGeoUri = null;
1131			}
1132		}
1133		forbidProcessingPendings = false;
1134
1135		ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
1136		setIntent(new Intent());
1137	}
1138
1139	private void handleViewConversationIntent(final Intent intent) {
1140		final String uuid = intent.getStringExtra(CONVERSATION);
1141		final String downloadUuid = intent.getStringExtra(MESSAGE);
1142		final String text = intent.getStringExtra(TEXT);
1143		final String nick = intent.getStringExtra(NICK);
1144		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE,false);
1145		if (selectConversationByUuid(uuid)) {
1146			this.mConversationFragment.reInit(getSelectedConversation());
1147			if (nick != null) {
1148				if (pm) {
1149					Jid jid = getSelectedConversation().getJid();
1150					try {
1151						Jid next = Jid.fromParts(jid.getLocalpart(),jid.getDomainpart(),nick);
1152						this.mConversationFragment.privateMessageWith(next);
1153					} catch (final InvalidJidException ignored) {
1154						//do nothing
1155					}
1156				} else {
1157					this.mConversationFragment.highlightInConference(nick);
1158				}
1159			} else {
1160				this.mConversationFragment.appendText(text);
1161			}
1162			hideConversationsOverview();
1163			openConversation();
1164			if (mContentView instanceof SlidingPaneLayout) {
1165				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1166			}
1167			if (downloadUuid != null) {
1168				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1169				if (message != null) {
1170					mConversationFragment.messageListAdapter.startDownloadable(message);
1171				}
1172			}
1173		}
1174	}
1175
1176	private boolean selectConversationByUuid(String uuid) {
1177		if (uuid == null) {
1178			return false;
1179		}
1180		for (Conversation aConversationList : conversationList) {
1181			if (aConversationList.getUuid().equals(uuid)) {
1182				setSelectedConversation(aConversationList);
1183				return true;
1184			}
1185		}
1186		return false;
1187	}
1188
1189	@Override
1190	protected void unregisterListeners() {
1191		super.unregisterListeners();
1192		xmppConnectionService.getNotificationService().setOpenConversation(null);
1193	}
1194
1195	@SuppressLint("NewApi")
1196	private static List<Uri> extractUriFromIntent(final Intent intent) {
1197		List<Uri> uris = new ArrayList<>();
1198		Uri uri = intent.getData();
1199		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1200			ClipData clipData = intent.getClipData();
1201			for(int i = 0; i < clipData.getItemCount(); ++i) {
1202				uris.add(clipData.getItemAt(i).getUri());
1203			}
1204		} else {
1205			uris.add(uri);
1206		}
1207		return uris;
1208	}
1209
1210	@Override
1211	protected void onActivityResult(int requestCode, int resultCode,
1212			final Intent data) {
1213		super.onActivityResult(requestCode, resultCode, data);
1214		if (resultCode == RESULT_OK) {
1215			if (requestCode == REQUEST_DECRYPT_PGP) {
1216				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1217			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1218				if (xmppConnectionServiceBound) {
1219					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1220						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1221						announcePgp(mSelectedConversation.getAccount(), null);
1222					} else {
1223						choosePgpSignId(mSelectedConversation.getAccount());
1224					}
1225					this.mPostponedActivityResult = null;
1226				} else {
1227					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1228				}
1229			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1230				if (xmppConnectionServiceBound) {
1231					announcePgp(mSelectedConversation.getAccount(), null);
1232					this.mPostponedActivityResult = null;
1233				} else {
1234					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1235				}
1236			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1237				mPendingImageUris.clear();
1238				mPendingImageUris.addAll(extractUriFromIntent(data));
1239				if (xmppConnectionServiceBound) {
1240					for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1241						attachImageToConversation(getSelectedConversation(),i.next());
1242					}
1243				}
1244			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1245				mPendingFileUris.clear();
1246				mPendingFileUris.addAll(extractUriFromIntent(data));
1247				if (xmppConnectionServiceBound) {
1248					for(Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1249						attachFileToConversation(getSelectedConversation(), i.next());
1250					}
1251				}
1252			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1253				if (mPendingImageUris.size() == 1) {
1254					Uri uri = mPendingImageUris.get(0);
1255					if (xmppConnectionServiceBound) {
1256						attachImageToConversation(getSelectedConversation(), uri);
1257						mPendingImageUris.clear();
1258					}
1259					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1260					intent.setData(uri);
1261					sendBroadcast(intent);
1262				} else {
1263					mPendingImageUris.clear();
1264				}
1265			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1266				double latitude = data.getDoubleExtra("latitude",0);
1267				double longitude = data.getDoubleExtra("longitude",0);
1268				this.mPendingGeoUri = Uri.parse("geo:"+String.valueOf(latitude)+","+String.valueOf(longitude));
1269				if (xmppConnectionServiceBound) {
1270					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1271					this.mPendingGeoUri = null;
1272				}
1273			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1274				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1275				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1276			}
1277		} else {
1278			mPendingImageUris.clear();
1279			mPendingFileUris.clear();
1280			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1281				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1282			}
1283		}
1284	}
1285
1286	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1287		if (conversation == null) {
1288			return;
1289		}
1290		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1291
1292			@Override
1293			public void success(Message message) {
1294				xmppConnectionService.sendMessage(message);
1295			}
1296
1297			@Override
1298			public void error(int errorCode, Message object) {
1299
1300			}
1301
1302			@Override
1303			public void userInputRequried(PendingIntent pi, Message object) {
1304
1305			}
1306		});
1307	}
1308
1309	private void attachFileToConversation(Conversation conversation, Uri uri) {
1310		if (conversation == null) {
1311			return;
1312		}
1313		prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1314		prepareFileToast.show();
1315		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1316			@Override
1317			public void success(Message message) {
1318				hidePrepareFileToast();
1319				xmppConnectionService.sendMessage(message);
1320			}
1321
1322			@Override
1323			public void error(int errorCode, Message message) {
1324				displayErrorDialog(errorCode);
1325			}
1326
1327			@Override
1328			public void userInputRequried(PendingIntent pi, Message message) {
1329
1330			}
1331		});
1332	}
1333
1334	private void attachImageToConversation(Conversation conversation, Uri uri) {
1335		if (conversation == null) {
1336			return;
1337		}
1338		prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1339		prepareFileToast.show();
1340		xmppConnectionService.attachImageToConversation(conversation, uri,
1341				new UiCallback<Message>() {
1342
1343					@Override
1344					public void userInputRequried(PendingIntent pi,
1345												  Message object) {
1346						hidePrepareFileToast();
1347					}
1348
1349					@Override
1350					public void success(Message message) {
1351						xmppConnectionService.sendMessage(message);
1352					}
1353
1354					@Override
1355					public void error(int error, Message message) {
1356						hidePrepareFileToast();
1357						displayErrorDialog(error);
1358					}
1359				});
1360	}
1361
1362	private void hidePrepareFileToast() {
1363		if (prepareFileToast != null) {
1364			runOnUiThread(new Runnable() {
1365
1366				@Override
1367				public void run() {
1368					prepareFileToast.cancel();
1369				}
1370			});
1371		}
1372	}
1373
1374	public void updateConversationList() {
1375		xmppConnectionService
1376			.populateWithOrderedConversations(conversationList);
1377		if (swipedConversation != null) {
1378			if (swipedConversation.isRead()) {
1379				conversationList.remove(swipedConversation);
1380			} else {
1381				listView.discardUndo();
1382			}
1383		}
1384		listAdapter.notifyDataSetChanged();
1385	}
1386
1387	public void runIntent(PendingIntent pi, int requestCode) {
1388		try {
1389			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1390					null, 0, 0, 0);
1391		} catch (final SendIntentException ignored) {
1392		}
1393	}
1394
1395	public void encryptTextMessage(Message message) {
1396		xmppConnectionService.getPgpEngine().encrypt(message,
1397				new UiCallback<Message>() {
1398
1399					@Override
1400					public void userInputRequried(PendingIntent pi,
1401												  Message message) {
1402						ConversationActivity.this.runIntent(pi,
1403								ConversationActivity.REQUEST_SEND_MESSAGE);
1404					}
1405
1406					@Override
1407					public void success(Message message) {
1408						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1409						xmppConnectionService.sendMessage(message);
1410					}
1411
1412					@Override
1413					public void error(int error, Message message) {
1414
1415					}
1416				});
1417	}
1418
1419	public boolean useSendButtonToIndicateStatus() {
1420		return getPreferences().getBoolean("send_button_status", false);
1421	}
1422
1423	public boolean indicateReceived() {
1424		return getPreferences().getBoolean("indicate_received", false);
1425	}
1426
1427	public boolean useWhiteBackground() {
1428		return getPreferences().getBoolean("use_white_background",false);
1429	}
1430
1431	protected boolean trustKeysIfNeeded(int requestCode) {
1432		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1433	}
1434
1435	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1436		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1437		boolean hasPendingKeys = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED,
1438				mSelectedConversation.getContact()).isEmpty()
1439				|| !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1440		boolean hasNoTrustedKeys = axolotlService.getNumTrustedKeys(mSelectedConversation.getContact()) == 0;
1441		if( hasPendingKeys || hasNoTrustedKeys) {
1442			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1443			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1444			intent.putExtra("contact", mSelectedConversation.getContact().getJid().toBareJid().toString());
1445			intent.putExtra("account", mSelectedConversation.getAccount().getJid().toBareJid().toString());
1446			intent.putExtra("choice", attachmentChoice);
1447			intent.putExtra("has_no_trusted", hasNoTrustedKeys);
1448			startActivityForResult(intent, requestCode);
1449			return true;
1450		} else {
1451			return false;
1452		}
1453	}
1454
1455	@Override
1456	protected void refreshUiReal() {
1457		updateConversationList();
1458		if (conversationList.size() > 0) {
1459			ConversationActivity.this.mConversationFragment.updateMessages();
1460			updateActionBarTitle();
1461			invalidateOptionsMenu();
1462		}
1463	}
1464
1465	@Override
1466	public void onAccountUpdate() {
1467		this.refreshUi();
1468	}
1469
1470	@Override
1471	public void onConversationUpdate() {
1472		this.refreshUi();
1473	}
1474
1475	@Override
1476	public void onRosterUpdate() {
1477		this.refreshUi();
1478	}
1479
1480	@Override
1481	public void OnUpdateBlocklist(Status status) {
1482		this.refreshUi();
1483	}
1484
1485	public void unblockConversation(final Blockable conversation) {
1486		xmppConnectionService.sendUnblockRequest(conversation);
1487	}
1488
1489	public boolean enterIsSend() {
1490		return getPreferences().getBoolean("enter_is_send",false);
1491	}
1492
1493	@Override
1494	public void onShowErrorToast(final int resId) {
1495		runOnUiThread(new Runnable() {
1496			@Override
1497			public void run() {
1498				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1499			}
1500		});
1501	}
1502
1503	public boolean highlightSelectedConversations() {
1504		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1505	}
1506}