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