XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.annotation.TargetApi;
   5import android.app.ActionBar;
   6import android.app.Activity;
   7import android.app.AlertDialog;
   8import android.app.AlertDialog.Builder;
   9import android.app.PendingIntent;
  10import android.content.ClipData;
  11import android.content.ClipboardManager;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.DialogInterface;
  15import android.content.DialogInterface.OnClickListener;
  16import android.content.Intent;
  17import android.content.IntentSender.SendIntentException;
  18import android.content.ServiceConnection;
  19import android.content.SharedPreferences;
  20import android.content.pm.PackageManager;
  21import android.content.pm.ResolveInfo;
  22import android.content.res.Resources;
  23import android.graphics.Bitmap;
  24import android.graphics.Color;
  25import android.graphics.Point;
  26import android.graphics.drawable.BitmapDrawable;
  27import android.graphics.drawable.Drawable;
  28import android.net.Uri;
  29import android.nfc.NdefMessage;
  30import android.nfc.NdefRecord;
  31import android.nfc.NfcAdapter;
  32import android.nfc.NfcEvent;
  33import android.os.AsyncTask;
  34import android.os.Build;
  35import android.os.Bundle;
  36import android.os.Handler;
  37import android.os.IBinder;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.text.InputType;
  41import android.util.DisplayMetrics;
  42import android.util.Log;
  43import android.view.MenuItem;
  44import android.view.View;
  45import android.view.inputmethod.InputMethodManager;
  46import android.widget.CompoundButton;
  47import android.widget.EditText;
  48import android.widget.ImageView;
  49import android.widget.LinearLayout;
  50import android.widget.TextView;
  51import android.widget.Toast;
  52
  53import com.google.zxing.BarcodeFormat;
  54import com.google.zxing.EncodeHintType;
  55import com.google.zxing.WriterException;
  56import com.google.zxing.common.BitMatrix;
  57import com.google.zxing.qrcode.QRCodeWriter;
  58import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  59
  60import net.java.otr4j.session.SessionID;
  61
  62import org.whispersystems.libaxolotl.IdentityKey;
  63
  64import java.io.FileNotFoundException;
  65import java.lang.ref.WeakReference;
  66import java.util.ArrayList;
  67import java.util.Hashtable;
  68import java.util.List;
  69import java.util.concurrent.RejectedExecutionException;
  70
  71import eu.siacs.conversations.Config;
  72import eu.siacs.conversations.R;
  73import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  74import eu.siacs.conversations.entities.Account;
  75import eu.siacs.conversations.entities.Contact;
  76import eu.siacs.conversations.entities.Conversation;
  77import eu.siacs.conversations.entities.Message;
  78import eu.siacs.conversations.entities.MucOptions;
  79import eu.siacs.conversations.entities.Presences;
  80import eu.siacs.conversations.services.AvatarService;
  81import eu.siacs.conversations.services.XmppConnectionService;
  82import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  83import eu.siacs.conversations.ui.widget.Switch;
  84import eu.siacs.conversations.utils.CryptoHelper;
  85import eu.siacs.conversations.utils.ExceptionHelper;
  86import eu.siacs.conversations.xmpp.OnNewKeysAvailable;
  87import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  88import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  89import eu.siacs.conversations.xmpp.jid.Jid;
  90
  91public abstract class XmppActivity extends Activity {
  92
  93	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  94	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  95
  96	public XmppConnectionService xmppConnectionService;
  97	public boolean xmppConnectionServiceBound = false;
  98	protected boolean registeredListeners = false;
  99
 100	protected int mPrimaryTextColor;
 101	protected int mSecondaryTextColor;
 102	protected int mPrimaryBackgroundColor;
 103	protected int mSecondaryBackgroundColor;
 104	protected int mColorRed;
 105	protected int mColorOrange;
 106	protected int mColorGreen;
 107	protected int mPrimaryColor;
 108
 109	protected boolean mUseSubject = true;
 110
 111	private DisplayMetrics metrics;
 112	protected int mTheme;
 113	protected boolean mUsingEnterKey = false;
 114
 115	private long mLastUiRefresh = 0;
 116	private Handler mRefreshUiHandler = new Handler();
 117	private Runnable mRefreshUiRunnable = new Runnable() {
 118		@Override
 119		public void run() {
 120			mLastUiRefresh = SystemClock.elapsedRealtime();
 121			refreshUiReal();
 122		}
 123	};
 124
 125	protected ConferenceInvite mPendingConferenceInvite = null;
 126
 127
 128	protected final void refreshUi() {
 129		final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 130		if (diff > Config.REFRESH_UI_INTERVAL) {
 131			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 132			runOnUiThread(mRefreshUiRunnable);
 133		} else {
 134			final long next = Config.REFRESH_UI_INTERVAL - diff;
 135			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 136			mRefreshUiHandler.postDelayed(mRefreshUiRunnable,next);
 137		}
 138	}
 139
 140	abstract protected void refreshUiReal();
 141
 142	protected interface OnValueEdited {
 143		public void onValueEdited(String value);
 144	}
 145
 146	public interface OnPresenceSelected {
 147		public void onPresenceSelected();
 148	}
 149
 150	protected ServiceConnection mConnection = new ServiceConnection() {
 151
 152		@Override
 153		public void onServiceConnected(ComponentName className, IBinder service) {
 154			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 155			xmppConnectionService = binder.getService();
 156			xmppConnectionServiceBound = true;
 157			if (!registeredListeners && shouldRegisterListeners()) {
 158				registerListeners();
 159				registeredListeners = true;
 160			}
 161			onBackendConnected();
 162		}
 163
 164		@Override
 165		public void onServiceDisconnected(ComponentName arg0) {
 166			xmppConnectionServiceBound = false;
 167		}
 168	};
 169
 170	@Override
 171	protected void onStart() {
 172		super.onStart();
 173		if (!xmppConnectionServiceBound) {
 174			connectToBackend();
 175		} else {
 176			if (!registeredListeners) {
 177				this.registerListeners();
 178				this.registeredListeners = true;
 179			}
 180			this.onBackendConnected();
 181		}
 182	}
 183
 184	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
 185	protected boolean shouldRegisterListeners() {
 186		if  (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
 187			return !isDestroyed() && !isFinishing();
 188		} else {
 189			return !isFinishing();
 190		}
 191	}
 192
 193	public void connectToBackend() {
 194		Intent intent = new Intent(this, XmppConnectionService.class);
 195		intent.setAction("ui");
 196		startService(intent);
 197		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 198	}
 199
 200	@Override
 201	protected void onStop() {
 202		super.onStop();
 203		if (xmppConnectionServiceBound) {
 204			if (registeredListeners) {
 205				this.unregisterListeners();
 206				this.registeredListeners = false;
 207			}
 208			unbindService(mConnection);
 209			xmppConnectionServiceBound = false;
 210		}
 211	}
 212
 213	protected void hideKeyboard() {
 214		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 215
 216		View focus = getCurrentFocus();
 217
 218		if (focus != null) {
 219
 220			inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
 221					InputMethodManager.HIDE_NOT_ALWAYS);
 222		}
 223	}
 224
 225	public boolean hasPgp() {
 226		return xmppConnectionService.getPgpEngine() != null;
 227	}
 228
 229	public void showInstallPgpDialog() {
 230		Builder builder = new AlertDialog.Builder(this);
 231		builder.setTitle(getString(R.string.openkeychain_required));
 232		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 233		builder.setMessage(getText(R.string.openkeychain_required_long));
 234		builder.setNegativeButton(getString(R.string.cancel), null);
 235		builder.setNeutralButton(getString(R.string.restart),
 236				new OnClickListener() {
 237
 238					@Override
 239					public void onClick(DialogInterface dialog, int which) {
 240						if (xmppConnectionServiceBound) {
 241							unbindService(mConnection);
 242							xmppConnectionServiceBound = false;
 243						}
 244						stopService(new Intent(XmppActivity.this,
 245									XmppConnectionService.class));
 246						finish();
 247					}
 248				});
 249		builder.setPositiveButton(getString(R.string.install),
 250				new OnClickListener() {
 251
 252					@Override
 253					public void onClick(DialogInterface dialog, int which) {
 254						Uri uri = Uri
 255							.parse("market://details?id=org.sufficientlysecure.keychain");
 256						Intent marketIntent = new Intent(Intent.ACTION_VIEW,
 257								uri);
 258						PackageManager manager = getApplicationContext()
 259							.getPackageManager();
 260						List<ResolveInfo> infos = manager
 261							.queryIntentActivities(marketIntent, 0);
 262						if (infos.size() > 0) {
 263							startActivity(marketIntent);
 264						} else {
 265							uri = Uri.parse("http://www.openkeychain.org/");
 266							Intent browserIntent = new Intent(
 267									Intent.ACTION_VIEW, uri);
 268							startActivity(browserIntent);
 269						}
 270						finish();
 271					}
 272				});
 273		builder.create().show();
 274	}
 275
 276	abstract void onBackendConnected();
 277
 278	protected void registerListeners() {
 279		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 280			this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 281		}
 282		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 283			this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 284		}
 285		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 286			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 287		}
 288		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 289			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 290		}
 291		if (this instanceof OnUpdateBlocklist) {
 292			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 293		}
 294		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 295			this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 296		}
 297		if (this instanceof OnNewKeysAvailable) {
 298			this.xmppConnectionService.setOnNewKeysAvailableListener((OnNewKeysAvailable) this);
 299		}
 300	}
 301
 302	protected void unregisterListeners() {
 303		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 304			this.xmppConnectionService.removeOnConversationListChangedListener();
 305		}
 306		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 307			this.xmppConnectionService.removeOnAccountListChangedListener();
 308		}
 309		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 310			this.xmppConnectionService.removeOnRosterUpdateListener();
 311		}
 312		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 313			this.xmppConnectionService.removeOnMucRosterUpdateListener();
 314		}
 315		if (this instanceof OnUpdateBlocklist) {
 316			this.xmppConnectionService.removeOnUpdateBlocklistListener();
 317		}
 318		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 319			this.xmppConnectionService.removeOnShowErrorToastListener();
 320		}
 321		if (this instanceof OnNewKeysAvailable) {
 322			this.xmppConnectionService.removeOnNewKeysAvailableListener();
 323		}
 324	}
 325
 326	@Override
 327	public boolean onOptionsItemSelected(final MenuItem item) {
 328		switch (item.getItemId()) {
 329			case R.id.action_settings:
 330				startActivity(new Intent(this, SettingsActivity.class));
 331				break;
 332			case R.id.action_accounts:
 333				startActivity(new Intent(this, ManageAccountActivity.class));
 334				break;
 335			case android.R.id.home:
 336				finish();
 337				break;
 338			case R.id.action_show_qr_code:
 339				showQrCode();
 340				break;
 341		}
 342		return super.onOptionsItemSelected(item);
 343	}
 344
 345	@Override
 346	protected void onCreate(Bundle savedInstanceState) {
 347		super.onCreate(savedInstanceState);
 348		metrics = getResources().getDisplayMetrics();
 349		ExceptionHelper.init(getApplicationContext());
 350		mPrimaryTextColor = getResources().getColor(R.color.black87);
 351		mSecondaryTextColor = getResources().getColor(R.color.black54);
 352		mColorRed = getResources().getColor(R.color.red500);
 353		mColorOrange = getResources().getColor(R.color.orange500);
 354		mColorGreen = getResources().getColor(R.color.green500);
 355		mPrimaryColor = getResources().getColor(R.color.green500);
 356		mPrimaryBackgroundColor = getResources().getColor(R.color.grey50);
 357		mSecondaryBackgroundColor = getResources().getColor(R.color.grey200);
 358		this.mTheme = findTheme();
 359		setTheme(this.mTheme);
 360		this.mUsingEnterKey = usingEnterKey();
 361		mUseSubject = getPreferences().getBoolean("use_subject", true);
 362		final ActionBar ab = getActionBar();
 363		if (ab!=null) {
 364			ab.setDisplayHomeAsUpEnabled(true);
 365		}
 366	}
 367
 368	protected boolean usingEnterKey() {
 369		return getPreferences().getBoolean("display_enter_key", false);
 370	}
 371
 372	protected SharedPreferences getPreferences() {
 373		return PreferenceManager
 374			.getDefaultSharedPreferences(getApplicationContext());
 375	}
 376
 377	public boolean useSubjectToIdentifyConference() {
 378		return mUseSubject;
 379	}
 380
 381	public void switchToConversation(Conversation conversation) {
 382		switchToConversation(conversation, null, false);
 383	}
 384
 385	public void switchToConversation(Conversation conversation, String text,
 386			boolean newTask) {
 387		switchToConversation(conversation,text,null,false,newTask);
 388	}
 389
 390	public void highlightInMuc(Conversation conversation, String nick) {
 391		switchToConversation(conversation, null, nick, false, false);
 392	}
 393
 394	public void privateMsgInMuc(Conversation conversation, String nick) {
 395		switchToConversation(conversation, null, nick, true, false);
 396	}
 397
 398	private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
 399		Intent viewConversationIntent = new Intent(this,
 400				ConversationActivity.class);
 401		viewConversationIntent.setAction(Intent.ACTION_VIEW);
 402		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
 403				conversation.getUuid());
 404		if (text != null) {
 405			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
 406		}
 407		if (nick != null) {
 408			viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
 409			viewConversationIntent.putExtra(ConversationActivity.PRIVATE_MESSAGE,pm);
 410		}
 411		viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
 412		if (newTask) {
 413			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 414					| Intent.FLAG_ACTIVITY_NEW_TASK
 415					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
 416		} else {
 417			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 418					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
 419		}
 420		startActivity(viewConversationIntent);
 421		finish();
 422	}
 423
 424	public void switchToContactDetails(Contact contact) {
 425		Intent intent = new Intent(this, ContactDetailsActivity.class);
 426		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 427		intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
 428		intent.putExtra("contact", contact.getJid().toString());
 429		startActivity(intent);
 430	}
 431
 432	public void switchToAccount(Account account) {
 433		Intent intent = new Intent(this, EditAccountActivity.class);
 434		intent.putExtra("jid", account.getJid().toBareJid().toString());
 435		startActivity(intent);
 436	}
 437
 438	protected void inviteToConversation(Conversation conversation) {
 439		Intent intent = new Intent(getApplicationContext(),
 440				ChooseContactActivity.class);
 441		List<String> contacts = new ArrayList<>();
 442		if (conversation.getMode() == Conversation.MODE_MULTI) {
 443			for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
 444				Jid jid = user.getJid();
 445				if (jid != null) {
 446					contacts.add(jid.toBareJid().toString());
 447				}
 448			}
 449		} else {
 450			contacts.add(conversation.getJid().toBareJid().toString());
 451		}
 452		intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
 453		intent.putExtra("conversation", conversation.getUuid());
 454		intent.putExtra("multiple", true);
 455		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
 456	}
 457
 458	protected void announcePgp(Account account, final Conversation conversation) {
 459		xmppConnectionService.getPgpEngine().generateSignature(account,
 460				"online", new UiCallback<Account>() {
 461
 462					@Override
 463					public void userInputRequried(PendingIntent pi,
 464												  Account account) {
 465						try {
 466							startIntentSenderForResult(pi.getIntentSender(),
 467									REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 468						} catch (final SendIntentException ignored) {
 469						}
 470					}
 471
 472					@Override
 473					public void success(Account account) {
 474						xmppConnectionService.databaseBackend.updateAccount(account);
 475						xmppConnectionService.sendPresence(account);
 476						if (conversation != null) {
 477							conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 478							xmppConnectionService.databaseBackend.updateConversation(conversation);
 479						}
 480					}
 481
 482					@Override
 483					public void error(int error, Account account) {
 484						displayErrorDialog(error);
 485					}
 486				});
 487	}
 488
 489	protected void displayErrorDialog(final int errorCode) {
 490		runOnUiThread(new Runnable() {
 491
 492			@Override
 493			public void run() {
 494				AlertDialog.Builder builder = new AlertDialog.Builder(
 495						XmppActivity.this);
 496				builder.setIconAttribute(android.R.attr.alertDialogIcon);
 497				builder.setTitle(getString(R.string.error));
 498				builder.setMessage(errorCode);
 499				builder.setNeutralButton(R.string.accept, null);
 500				builder.create().show();
 501			}
 502		});
 503
 504	}
 505
 506	protected void showAddToRosterDialog(final Conversation conversation) {
 507		showAddToRosterDialog(conversation.getContact());
 508	}
 509
 510	protected void showAddToRosterDialog(final Contact contact) {
 511		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 512		builder.setTitle(contact.getJid().toString());
 513		builder.setMessage(getString(R.string.not_in_roster));
 514		builder.setNegativeButton(getString(R.string.cancel), null);
 515		builder.setPositiveButton(getString(R.string.add_contact),
 516				new DialogInterface.OnClickListener() {
 517
 518					@Override
 519					public void onClick(DialogInterface dialog, int which) {
 520						final Jid jid = contact.getJid();
 521						Account account = contact.getAccount();
 522						Contact contact = account.getRoster().getContact(jid);
 523						xmppConnectionService.createContact(contact);
 524					}
 525				});
 526		builder.create().show();
 527	}
 528
 529	private void showAskForPresenceDialog(final Contact contact) {
 530		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 531		builder.setTitle(contact.getJid().toString());
 532		builder.setMessage(R.string.request_presence_updates);
 533		builder.setNegativeButton(R.string.cancel, null);
 534		builder.setPositiveButton(R.string.request_now,
 535				new DialogInterface.OnClickListener() {
 536
 537					@Override
 538					public void onClick(DialogInterface dialog, int which) {
 539						if (xmppConnectionServiceBound) {
 540							xmppConnectionService.sendPresencePacket(contact
 541									.getAccount(), xmppConnectionService
 542									.getPresenceGenerator()
 543									.requestPresenceUpdatesFrom(contact));
 544						}
 545					}
 546				});
 547		builder.create().show();
 548	}
 549
 550	private void warnMutalPresenceSubscription(final Conversation conversation,
 551			final OnPresenceSelected listener) {
 552		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 553		builder.setTitle(conversation.getContact().getJid().toString());
 554		builder.setMessage(R.string.without_mutual_presence_updates);
 555		builder.setNegativeButton(R.string.cancel, null);
 556		builder.setPositiveButton(R.string.ignore, new OnClickListener() {
 557
 558			@Override
 559			public void onClick(DialogInterface dialog, int which) {
 560				conversation.setNextCounterpart(null);
 561				if (listener != null) {
 562					listener.onPresenceSelected();
 563				}
 564			}
 565		});
 566		builder.create().show();
 567	}
 568
 569	protected void quickEdit(String previousValue, OnValueEdited callback) {
 570		quickEdit(previousValue, callback, false);
 571	}
 572
 573	protected void quickPasswordEdit(String previousValue,
 574			OnValueEdited callback) {
 575		quickEdit(previousValue, callback, true);
 576	}
 577
 578	@SuppressLint("InflateParams")
 579	private void quickEdit(final String previousValue,
 580			final OnValueEdited callback, boolean password) {
 581		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 582		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
 583		final EditText editor = (EditText) view.findViewById(R.id.editor);
 584		OnClickListener mClickListener = new OnClickListener() {
 585
 586			@Override
 587			public void onClick(DialogInterface dialog, int which) {
 588				String value = editor.getText().toString();
 589				if (!previousValue.equals(value) && value.trim().length() > 0) {
 590					callback.onValueEdited(value);
 591				}
 592			}
 593		};
 594		if (password) {
 595			editor.setInputType(InputType.TYPE_CLASS_TEXT
 596					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
 597			editor.setHint(R.string.password);
 598			builder.setPositiveButton(R.string.accept, mClickListener);
 599		} else {
 600			builder.setPositiveButton(R.string.edit, mClickListener);
 601		}
 602		editor.requestFocus();
 603		editor.setText(previousValue);
 604		builder.setView(view);
 605		builder.setNegativeButton(R.string.cancel, null);
 606		builder.create().show();
 607	}
 608
 609	protected boolean addFingerprintRow(LinearLayout keys, final Account account, IdentityKey identityKey) {
 610		final String fingerprint = identityKey.getFingerprint().replaceAll("\\s", "");
 611		final AxolotlService.SQLiteAxolotlStore.Trust trust = account.getAxolotlService()
 612				.getFingerprintTrust(fingerprint);
 613		return addFingerprintRowWithListeners(keys, account, identityKey, trust, true,
 614				new CompoundButton.OnCheckedChangeListener() {
 615					@Override
 616					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 617						if (isChecked != (trust == AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED)) {
 618							account.getAxolotlService().setFingerprintTrust(fingerprint,
 619									(isChecked) ? AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED :
 620											AxolotlService.SQLiteAxolotlStore.Trust.UNTRUSTED);
 621						}
 622						refreshUi();
 623						xmppConnectionService.updateAccountUi();
 624						xmppConnectionService.updateConversationUi();
 625					}
 626				},
 627				new View.OnClickListener() {
 628					@Override
 629					public void onClick(View v) {
 630						account.getAxolotlService().setFingerprintTrust(fingerprint,
 631								AxolotlService.SQLiteAxolotlStore.Trust.UNTRUSTED);
 632						refreshUi();
 633						xmppConnectionService.updateAccountUi();
 634						xmppConnectionService.updateConversationUi();
 635					}
 636				}
 637
 638		);
 639	}
 640
 641	protected boolean addFingerprintRowWithListeners(LinearLayout keys, final Account account,
 642	                                              final IdentityKey identityKey,
 643	                                              AxolotlService.SQLiteAxolotlStore.Trust trust,
 644	                                              boolean showTag,
 645	                                              CompoundButton.OnCheckedChangeListener
 646			                                             onCheckedChangeListener,
 647	                                              View.OnClickListener onClickListener) {
 648		if (trust == AxolotlService.SQLiteAxolotlStore.Trust.COMPROMISED) {
 649			return false;
 650		}
 651		View view = getLayoutInflater().inflate(R.layout.contact_key, keys, false);
 652		TextView key = (TextView) view.findViewById(R.id.key);
 653		TextView keyType = (TextView) view.findViewById(R.id.key_type);
 654		Switch trustToggle = (Switch) view.findViewById(R.id.tgl_trust);
 655		trustToggle.setVisibility(View.VISIBLE);
 656		trustToggle.setOnCheckedChangeListener(onCheckedChangeListener);
 657		trustToggle.setOnClickListener(onClickListener);
 658		view.setOnLongClickListener(new View.OnLongClickListener() {
 659			@Override
 660			public boolean onLongClick(View v) {
 661				showPurgeKeyDialog(account, identityKey);
 662				return true;
 663			}
 664		});
 665
 666		switch (trust) {
 667			case UNTRUSTED:
 668			case TRUSTED:
 669				trustToggle.setChecked(trust == AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED, false);
 670				trustToggle.setEnabled(true);
 671				break;
 672			case UNDECIDED:
 673				trustToggle.setChecked(false, false);
 674				trustToggle.setEnabled(false);
 675				break;
 676		}
 677
 678		if (showTag) {
 679			keyType.setText(getString(R.string.axolotl_fingerprint));
 680		} else {
 681			keyType.setVisibility(View.GONE);
 682		}
 683
 684		key.setText(CryptoHelper.prettifyFingerprint(identityKey.getFingerprint()));
 685		keys.addView(view);
 686		return true;
 687	}
 688
 689	public void showPurgeKeyDialog(final Account account, final IdentityKey identityKey) {
 690		Builder builder = new Builder(this);
 691		builder.setTitle(getString(R.string.purge_key));
 692		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 693		builder.setMessage(getString(R.string.purge_key_desc_part1)
 694				+ "\n\n" + CryptoHelper.prettifyFingerprint(identityKey.getFingerprint())
 695				+ "\n\n" + getString(R.string.purge_key_desc_part2));
 696		builder.setNegativeButton(getString(R.string.cancel), null);
 697		builder.setPositiveButton(getString(R.string.accept),
 698				new DialogInterface.OnClickListener() {
 699					@Override
 700					public void onClick(DialogInterface dialog, int which) {
 701						account.getAxolotlService().purgeKey(identityKey);
 702						refreshUi();
 703					}
 704				});
 705		builder.create().show();
 706	}
 707
 708	public void selectPresence(final Conversation conversation,
 709			final OnPresenceSelected listener) {
 710		final Contact contact = conversation.getContact();
 711		if (conversation.hasValidOtrSession()) {
 712			SessionID id = conversation.getOtrSession().getSessionID();
 713			Jid jid;
 714			try {
 715				jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
 716			} catch (InvalidJidException e) {
 717				jid = null;
 718			}
 719			conversation.setNextCounterpart(jid);
 720			listener.onPresenceSelected();
 721		} else 	if (!contact.showInRoster()) {
 722			showAddToRosterDialog(conversation);
 723		} else {
 724			Presences presences = contact.getPresences();
 725			if (presences.size() == 0) {
 726				if (!contact.getOption(Contact.Options.TO)
 727						&& !contact.getOption(Contact.Options.ASKING)
 728						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 729					showAskForPresenceDialog(contact);
 730				} else if (!contact.getOption(Contact.Options.TO)
 731						|| !contact.getOption(Contact.Options.FROM)) {
 732					warnMutalPresenceSubscription(conversation, listener);
 733				} else {
 734					conversation.setNextCounterpart(null);
 735					listener.onPresenceSelected();
 736				}
 737			} else if (presences.size() == 1) {
 738				String presence = presences.asStringArray()[0];
 739				try {
 740					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
 741				} catch (InvalidJidException e) {
 742					conversation.setNextCounterpart(null);
 743				}
 744				listener.onPresenceSelected();
 745			} else {
 746				final StringBuilder presence = new StringBuilder();
 747				AlertDialog.Builder builder = new AlertDialog.Builder(this);
 748				builder.setTitle(getString(R.string.choose_presence));
 749				final String[] presencesArray = presences.asStringArray();
 750				int preselectedPresence = 0;
 751				for (int i = 0; i < presencesArray.length; ++i) {
 752					if (presencesArray[i].equals(contact.lastseen.presence)) {
 753						preselectedPresence = i;
 754						break;
 755					}
 756				}
 757				presence.append(presencesArray[preselectedPresence]);
 758				builder.setSingleChoiceItems(presencesArray,
 759						preselectedPresence,
 760						new DialogInterface.OnClickListener() {
 761
 762							@Override
 763							public void onClick(DialogInterface dialog,
 764									int which) {
 765								presence.delete(0, presence.length());
 766								presence.append(presencesArray[which]);
 767							}
 768						});
 769				builder.setNegativeButton(R.string.cancel, null);
 770				builder.setPositiveButton(R.string.ok, new OnClickListener() {
 771
 772					@Override
 773					public void onClick(DialogInterface dialog, int which) {
 774						try {
 775							conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
 776						} catch (InvalidJidException e) {
 777							conversation.setNextCounterpart(null);
 778						}
 779						listener.onPresenceSelected();
 780					}
 781				});
 782				builder.create().show();
 783			}
 784		}
 785	}
 786
 787	protected void onActivityResult(int requestCode, int resultCode,
 788			final Intent data) {
 789		super.onActivityResult(requestCode, resultCode, data);
 790		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 791			mPendingConferenceInvite = ConferenceInvite.parse(data);
 792			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 793				mPendingConferenceInvite.execute(this);
 794				mPendingConferenceInvite = null;
 795			}
 796		}
 797	}
 798
 799	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 800		@Override
 801		public void success(final Conversation conversation) {
 802			switchToConversation(conversation);
 803			runOnUiThread(new Runnable() {
 804				@Override
 805				public void run() {
 806					Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
 807				}
 808			});
 809		}
 810
 811		@Override
 812		public void error(final int errorCode, Conversation object) {
 813			runOnUiThread(new Runnable() {
 814				@Override
 815				public void run() {
 816					Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
 817				}
 818			});
 819		}
 820
 821		@Override
 822		public void userInputRequried(PendingIntent pi, Conversation object) {
 823
 824		}
 825	};
 826
 827	public int getSecondaryTextColor() {
 828		return this.mSecondaryTextColor;
 829	}
 830
 831	public int getPrimaryTextColor() {
 832		return this.mPrimaryTextColor;
 833	}
 834
 835	public int getWarningTextColor() {
 836		return this.mColorRed;
 837	}
 838
 839	public int getOnlineColor() {
 840		return this.mColorGreen;
 841	}
 842
 843	public int getPrimaryBackgroundColor() {
 844		return this.mPrimaryBackgroundColor;
 845	}
 846
 847	public int getSecondaryBackgroundColor() {
 848		return this.mSecondaryBackgroundColor;
 849	}
 850
 851	public int getPixel(int dp) {
 852		DisplayMetrics metrics = getResources().getDisplayMetrics();
 853		return ((int) (dp * metrics.density));
 854	}
 855
 856	public boolean copyTextToClipboard(String text, int labelResId) {
 857		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 858		String label = getResources().getString(labelResId);
 859		if (mClipBoardManager != null) {
 860			ClipData mClipData = ClipData.newPlainText(label, text);
 861			mClipBoardManager.setPrimaryClip(mClipData);
 862			return true;
 863		}
 864		return false;
 865	}
 866
 867	protected void registerNdefPushMessageCallback() {
 868		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 869		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 870			nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
 871				@Override
 872				public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
 873					return new NdefMessage(new NdefRecord[]{
 874						NdefRecord.createUri(getShareableUri()),
 875							NdefRecord.createApplicationRecord("eu.siacs.conversations")
 876					});
 877				}
 878			}, this);
 879		}
 880	}
 881
 882	protected void unregisterNdefPushMessageCallback() {
 883		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 884		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 885			nfcAdapter.setNdefPushMessageCallback(null,this);
 886		}
 887	}
 888
 889	protected String getShareableUri() {
 890		return null;
 891	}
 892
 893	@Override
 894	public void onResume() {
 895		super.onResume();
 896		if (this.getShareableUri()!=null) {
 897			this.registerNdefPushMessageCallback();
 898		}
 899	}
 900
 901	protected int findTheme() {
 902		if (getPreferences().getBoolean("use_larger_font", false)) {
 903			return R.style.ConversationsTheme_LargerText;
 904		} else {
 905			return R.style.ConversationsTheme;
 906		}
 907	}
 908
 909	@Override
 910	public void onPause() {
 911		super.onPause();
 912		this.unregisterNdefPushMessageCallback();
 913	}
 914
 915	protected void showQrCode() {
 916		String uri = getShareableUri();
 917		if (uri!=null) {
 918			Point size = new Point();
 919			getWindowManager().getDefaultDisplay().getSize(size);
 920			final int width = (size.x < size.y ? size.x : size.y);
 921			Bitmap bitmap = createQrCodeBitmap(uri, width);
 922			ImageView view = new ImageView(this);
 923			view.setImageBitmap(bitmap);
 924			AlertDialog.Builder builder = new AlertDialog.Builder(this);
 925			builder.setView(view);
 926			builder.create().show();
 927		}
 928	}
 929
 930	protected Bitmap createQrCodeBitmap(String input, int size) {
 931		Log.d(Config.LOGTAG,"qr code requested size: "+size);
 932		try {
 933			final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
 934			final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
 935			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
 936			final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
 937			final int width = result.getWidth();
 938			final int height = result.getHeight();
 939			final int[] pixels = new int[width * height];
 940			for (int y = 0; y < height; y++) {
 941				final int offset = y * width;
 942				for (int x = 0; x < width; x++) {
 943					pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
 944				}
 945			}
 946			final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
 947			Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
 948			bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
 949			return bitmap;
 950		} catch (final WriterException e) {
 951			return null;
 952		}
 953	}
 954
 955	public static class ConferenceInvite {
 956		private String uuid;
 957		private List<Jid> jids = new ArrayList<>();
 958
 959		public static ConferenceInvite parse(Intent data) {
 960			ConferenceInvite invite = new ConferenceInvite();
 961			invite.uuid = data.getStringExtra("conversation");
 962			if (invite.uuid == null) {
 963				return null;
 964			}
 965			try {
 966				if (data.getBooleanExtra("multiple", false)) {
 967					String[] toAdd = data.getStringArrayExtra("contacts");
 968					for (String item : toAdd) {
 969						invite.jids.add(Jid.fromString(item));
 970					}
 971				} else {
 972					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
 973				}
 974			} catch (final InvalidJidException ignored) {
 975				return null;
 976			}
 977			return invite;
 978		}
 979
 980		public void execute(XmppActivity activity) {
 981			XmppConnectionService service = activity.xmppConnectionService;
 982			Conversation conversation = service.findConversationByUuid(this.uuid);
 983			if (conversation == null) {
 984				return;
 985			}
 986			if (conversation.getMode() == Conversation.MODE_MULTI) {
 987				for (Jid jid : jids) {
 988					service.invite(conversation, jid);
 989				}
 990			} else {
 991				jids.add(conversation.getJid().toBareJid());
 992				service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
 993			}
 994		}
 995	}
 996
 997	public AvatarService avatarService() {
 998		return xmppConnectionService.getAvatarService();
 999	}
1000
1001	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1002		private final WeakReference<ImageView> imageViewReference;
1003		private Message message = null;
1004
1005		public BitmapWorkerTask(ImageView imageView) {
1006			imageViewReference = new WeakReference<>(imageView);
1007		}
1008
1009		@Override
1010		protected Bitmap doInBackground(Message... params) {
1011			message = params[0];
1012			try {
1013				return xmppConnectionService.getFileBackend().getThumbnail(
1014						message, (int) (metrics.density * 288), false);
1015			} catch (FileNotFoundException e) {
1016				return null;
1017			}
1018		}
1019
1020		@Override
1021		protected void onPostExecute(Bitmap bitmap) {
1022			if (bitmap != null) {
1023				final ImageView imageView = imageViewReference.get();
1024				if (imageView != null) {
1025					imageView.setImageBitmap(bitmap);
1026					imageView.setBackgroundColor(0x00000000);
1027				}
1028			}
1029		}
1030	}
1031
1032	public void loadBitmap(Message message, ImageView imageView) {
1033		Bitmap bm;
1034		try {
1035			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1036					(int) (metrics.density * 288), true);
1037		} catch (FileNotFoundException e) {
1038			bm = null;
1039		}
1040		if (bm != null) {
1041			imageView.setImageBitmap(bm);
1042			imageView.setBackgroundColor(0x00000000);
1043		} else {
1044			if (cancelPotentialWork(message, imageView)) {
1045				imageView.setBackgroundColor(0xff333333);
1046				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1047				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1048						getResources(), null, task);
1049				imageView.setImageDrawable(asyncDrawable);
1050				try {
1051					task.execute(message);
1052				} catch (final RejectedExecutionException ignored) {
1053				}
1054			}
1055		}
1056	}
1057
1058	public static boolean cancelPotentialWork(Message message,
1059			ImageView imageView) {
1060		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1061
1062		if (bitmapWorkerTask != null) {
1063			final Message oldMessage = bitmapWorkerTask.message;
1064			if (oldMessage == null || message != oldMessage) {
1065				bitmapWorkerTask.cancel(true);
1066			} else {
1067				return false;
1068			}
1069		}
1070		return true;
1071	}
1072
1073	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1074		if (imageView != null) {
1075			final Drawable drawable = imageView.getDrawable();
1076			if (drawable instanceof AsyncDrawable) {
1077				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1078				return asyncDrawable.getBitmapWorkerTask();
1079			}
1080		}
1081		return null;
1082	}
1083
1084	static class AsyncDrawable extends BitmapDrawable {
1085		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1086
1087		public AsyncDrawable(Resources res, Bitmap bitmap,
1088				BitmapWorkerTask bitmapWorkerTask) {
1089			super(res, bitmap);
1090			bitmapWorkerTaskReference = new WeakReference<>(
1091					bitmapWorkerTask);
1092		}
1093
1094		public BitmapWorkerTask getBitmapWorkerTask() {
1095			return bitmapWorkerTaskReference.get();
1096		}
1097	}
1098}