ConversationActivity.java

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