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