ConversationActivity.java

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