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.IBinder;
 37import android.preference.PreferenceManager;
 38import android.text.InputType;
 39import android.util.DisplayMetrics;
 40import android.util.Log;
 41import android.view.MenuItem;
 42import android.view.View;
 43import android.view.inputmethod.InputMethodManager;
 44import android.widget.EditText;
 45import android.widget.ImageView;
 46import android.widget.Toast;
 47
 48import com.google.zxing.BarcodeFormat;
 49import com.google.zxing.EncodeHintType;
 50import com.google.zxing.WriterException;
 51import com.google.zxing.common.BitMatrix;
 52import com.google.zxing.qrcode.QRCodeWriter;
 53import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 54
 55import net.java.otr4j.session.SessionID;
 56
 57import java.io.FileNotFoundException;
 58import java.lang.ref.WeakReference;
 59import java.util.ArrayList;
 60import java.util.Hashtable;
 61import java.util.List;
 62import java.util.concurrent.RejectedExecutionException;
 63
 64import eu.siacs.conversations.Config;
 65import eu.siacs.conversations.R;
 66import eu.siacs.conversations.entities.Account;
 67import eu.siacs.conversations.entities.Contact;
 68import eu.siacs.conversations.entities.Conversation;
 69import eu.siacs.conversations.entities.Message;
 70import eu.siacs.conversations.entities.Presences;
 71import eu.siacs.conversations.services.AvatarService;
 72import eu.siacs.conversations.services.XmppConnectionService;
 73import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
 74import eu.siacs.conversations.utils.ExceptionHelper;
 75import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 76import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 77import eu.siacs.conversations.xmpp.jid.Jid;
 78
 79public abstract class XmppActivity extends Activity {
 80
 81	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
 82	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
 83
 84	public XmppConnectionService xmppConnectionService;
 85	public boolean xmppConnectionServiceBound = false;
 86	protected boolean registeredListeners = false;
 87
 88	protected int mPrimaryTextColor;
 89	protected int mSecondaryTextColor;
 90	protected int mSecondaryBackgroundColor;
 91	protected int mColorRed;
 92	protected int mColorOrange;
 93	protected int mColorGreen;
 94	protected int mPrimaryColor;
 95
 96	protected boolean mUseSubject = true;
 97
 98	private DisplayMetrics metrics;
 99	protected int mTheme;
100	protected boolean mUsingEnterKey = false;
101
102	protected interface OnValueEdited {
103		public void onValueEdited(String value);
104	}
105
106	public interface OnPresenceSelected {
107		public void onPresenceSelected();
108	}
109
110	protected ServiceConnection mConnection = new ServiceConnection() {
111
112		@Override
113		public void onServiceConnected(ComponentName className, IBinder service) {
114			XmppConnectionBinder binder = (XmppConnectionBinder) service;
115			xmppConnectionService = binder.getService();
116			xmppConnectionServiceBound = true;
117			if (!registeredListeners && shouldRegisterListeners()) {
118				registerListeners();
119				registeredListeners = true;
120			}
121			onBackendConnected();
122		}
123
124		@Override
125		public void onServiceDisconnected(ComponentName arg0) {
126			xmppConnectionServiceBound = false;
127		}
128	};
129
130	@Override
131	protected void onStart() {
132		super.onStart();
133		if (!xmppConnectionServiceBound) {
134			connectToBackend();
135		} else {
136			if (!registeredListeners) {
137				this.registerListeners();
138				this.registeredListeners = true;
139			}
140			this.onBackendConnected();
141		}
142	}
143
144	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
145	protected boolean shouldRegisterListeners() {
146		if  (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
147			return !isDestroyed() && !isFinishing();
148		} else {
149			return !isFinishing();
150		}
151	}
152
153	public void connectToBackend() {
154		Intent intent = new Intent(this, XmppConnectionService.class);
155		intent.setAction("ui");
156		startService(intent);
157		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
158	}
159
160	@Override
161	protected void onStop() {
162		super.onStop();
163		if (xmppConnectionServiceBound) {
164			if (registeredListeners) {
165				this.unregisterListeners();
166				this.registeredListeners = false;
167			}
168			unbindService(mConnection);
169			xmppConnectionServiceBound = false;
170		}
171	}
172
173	protected void hideKeyboard() {
174		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
175
176		View focus = getCurrentFocus();
177
178		if (focus != null) {
179
180			inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
181					InputMethodManager.HIDE_NOT_ALWAYS);
182		}
183	}
184
185	public boolean hasPgp() {
186		return xmppConnectionService.getPgpEngine() != null;
187	}
188
189	public void showInstallPgpDialog() {
190		Builder builder = new AlertDialog.Builder(this);
191		builder.setTitle(getString(R.string.openkeychain_required));
192		builder.setIconAttribute(android.R.attr.alertDialogIcon);
193		builder.setMessage(getText(R.string.openkeychain_required_long));
194		builder.setNegativeButton(getString(R.string.cancel), null);
195		builder.setNeutralButton(getString(R.string.restart),
196				new OnClickListener() {
197
198					@Override
199					public void onClick(DialogInterface dialog, int which) {
200						if (xmppConnectionServiceBound) {
201							unbindService(mConnection);
202							xmppConnectionServiceBound = false;
203						}
204						stopService(new Intent(XmppActivity.this,
205									XmppConnectionService.class));
206						finish();
207					}
208				});
209		builder.setPositiveButton(getString(R.string.install),
210				new OnClickListener() {
211
212					@Override
213					public void onClick(DialogInterface dialog, int which) {
214						Uri uri = Uri
215							.parse("market://details?id=org.sufficientlysecure.keychain");
216						Intent marketIntent = new Intent(Intent.ACTION_VIEW,
217								uri);
218						PackageManager manager = getApplicationContext()
219							.getPackageManager();
220						List<ResolveInfo> infos = manager
221							.queryIntentActivities(marketIntent, 0);
222						if (infos.size() > 0) {
223							startActivity(marketIntent);
224						} else {
225							uri = Uri.parse("http://www.openkeychain.org/");
226							Intent browserIntent = new Intent(
227									Intent.ACTION_VIEW, uri);
228							startActivity(browserIntent);
229						}
230						finish();
231					}
232				});
233		builder.create().show();
234	}
235
236	abstract void onBackendConnected();
237
238	protected void registerListeners() {
239		if (this instanceof XmppConnectionService.OnConversationUpdate) {
240			this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
241		}
242		if (this instanceof XmppConnectionService.OnAccountUpdate) {
243			this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
244		}
245		if (this instanceof XmppConnectionService.OnRosterUpdate) {
246			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
247		}
248		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
249			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
250		}
251		if (this instanceof OnUpdateBlocklist) {
252			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
253		}
254	}
255
256	protected void unregisterListeners() {
257		if (this instanceof XmppConnectionService.OnConversationUpdate) {
258			this.xmppConnectionService.removeOnConversationListChangedListener();
259		}
260		if (this instanceof XmppConnectionService.OnAccountUpdate) {
261			this.xmppConnectionService.removeOnAccountListChangedListener();
262		}
263		if (this instanceof XmppConnectionService.OnRosterUpdate) {
264			this.xmppConnectionService.removeOnRosterUpdateListener();
265		}
266		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
267			this.xmppConnectionService.removeOnMucRosterUpdateListener();
268		}
269		if (this instanceof OnUpdateBlocklist) {
270			this.xmppConnectionService.removeOnUpdateBlocklistListener();
271		}
272	}
273
274	@Override
275	public boolean onOptionsItemSelected(final MenuItem item) {
276		switch (item.getItemId()) {
277			case R.id.action_settings:
278				startActivity(new Intent(this, SettingsActivity.class));
279				break;
280			case R.id.action_accounts:
281				startActivity(new Intent(this, ManageAccountActivity.class));
282				break;
283			case android.R.id.home:
284				finish();
285				break;
286			case R.id.action_show_qr_code:
287				showQrCode();
288				break;
289		}
290		return super.onOptionsItemSelected(item);
291	}
292
293	@Override
294	protected void onCreate(Bundle savedInstanceState) {
295		super.onCreate(savedInstanceState);
296		metrics = getResources().getDisplayMetrics();
297		ExceptionHelper.init(getApplicationContext());
298		mPrimaryTextColor = getResources().getColor(R.color.primarytext);
299		mSecondaryTextColor = getResources().getColor(R.color.secondarytext);
300		mColorRed = getResources().getColor(R.color.red);
301		mColorOrange = getResources().getColor(R.color.orange);
302		mColorGreen = getResources().getColor(R.color.green);
303		mPrimaryColor = getResources().getColor(R.color.primary);
304		mSecondaryBackgroundColor = getResources().getColor(R.color.secondarybackground);
305		this.mTheme = findTheme();
306		setTheme(this.mTheme);
307		this.mUsingEnterKey = usingEnterKey();
308		mUseSubject = getPreferences().getBoolean("use_subject", true);
309		final ActionBar ab = getActionBar();
310		if (ab!=null) {
311			ab.setDisplayHomeAsUpEnabled(true);
312		}
313	}
314
315	protected boolean usingEnterKey() {
316		return getPreferences().getBoolean("display_enter_key", false);
317	}
318
319	protected SharedPreferences getPreferences() {
320		return PreferenceManager
321			.getDefaultSharedPreferences(getApplicationContext());
322	}
323
324	public boolean useSubjectToIdentifyConference() {
325		return mUseSubject;
326	}
327
328	public void switchToConversation(Conversation conversation) {
329		switchToConversation(conversation, null, false);
330	}
331
332	public void switchToConversation(Conversation conversation, String text,
333			boolean newTask) {
334		switchToConversation(conversation,text,null,newTask);
335	}
336
337	public void highlightInMuc(Conversation conversation, String nick) {
338		switchToConversation(conversation,null,nick,false);
339	}
340
341	private void switchToConversation(Conversation conversation, String text, String nick, boolean newTask) {
342		Intent viewConversationIntent = new Intent(this,
343				ConversationActivity.class);
344		viewConversationIntent.setAction(Intent.ACTION_VIEW);
345		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
346				conversation.getUuid());
347		if (text != null) {
348			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
349		}
350		if (nick != null) {
351			viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
352		}
353		viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
354		if (newTask) {
355			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
356					| Intent.FLAG_ACTIVITY_NEW_TASK
357					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
358		} else {
359			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
360					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
361		}
362		startActivity(viewConversationIntent);
363		finish();
364	}
365
366	public void switchToContactDetails(Contact contact) {
367		Intent intent = new Intent(this, ContactDetailsActivity.class);
368		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
369		intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
370		intent.putExtra("contact", contact.getJid().toString());
371		startActivity(intent);
372	}
373
374	public void switchToAccount(Account account) {
375		Intent intent = new Intent(this, EditAccountActivity.class);
376		intent.putExtra("jid", account.getJid().toBareJid().toString());
377		startActivity(intent);
378	}
379
380	protected void inviteToConversation(Conversation conversation) {
381		Intent intent = new Intent(getApplicationContext(),
382				ChooseContactActivity.class);
383		intent.putExtra("conversation", conversation.getUuid());
384		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
385	}
386
387	protected void announcePgp(Account account, final Conversation conversation) {
388		xmppConnectionService.getPgpEngine().generateSignature(account,
389				"online", new UiCallback<Account>() {
390
391					@Override
392					public void userInputRequried(PendingIntent pi,
393							Account account) {
394						try {
395							startIntentSenderForResult(pi.getIntentSender(),
396									REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
397						} catch (final SendIntentException ignored) {
398						}
399					}
400
401					@Override
402					public void success(Account account) {
403						xmppConnectionService.databaseBackend
404							.updateAccount(account);
405						xmppConnectionService.sendPresencePacket(account,
406								xmppConnectionService.getPresenceGenerator()
407								.sendPresence(account));
408						if (conversation != null) {
409							conversation
410								.setNextEncryption(Message.ENCRYPTION_PGP);
411							xmppConnectionService.databaseBackend
412								.updateConversation(conversation);
413						}
414					}
415
416					@Override
417					public void error(int error, Account account) {
418						displayErrorDialog(error);
419					}
420				});
421	}
422
423	protected void displayErrorDialog(final int errorCode) {
424		runOnUiThread(new Runnable() {
425
426			@Override
427			public void run() {
428				AlertDialog.Builder builder = new AlertDialog.Builder(
429						XmppActivity.this);
430				builder.setIconAttribute(android.R.attr.alertDialogIcon);
431				builder.setTitle(getString(R.string.error));
432				builder.setMessage(errorCode);
433				builder.setNeutralButton(R.string.accept, null);
434				builder.create().show();
435			}
436		});
437
438	}
439
440	protected void showAddToRosterDialog(final Conversation conversation) {
441		showAddToRosterDialog(conversation.getContact());
442	}
443
444	protected void showAddToRosterDialog(final Contact contact) {
445		AlertDialog.Builder builder = new AlertDialog.Builder(this);
446		builder.setTitle(contact.getJid().toString());
447		builder.setMessage(getString(R.string.not_in_roster));
448		builder.setNegativeButton(getString(R.string.cancel), null);
449		builder.setPositiveButton(getString(R.string.add_contact),
450				new DialogInterface.OnClickListener() {
451
452					@Override
453					public void onClick(DialogInterface dialog, int which) {
454						final Jid jid = contact.getJid();
455						Account account = contact.getAccount();
456						Contact contact = account.getRoster().getContact(jid);
457						xmppConnectionService.createContact(contact);
458					}
459				});
460		builder.create().show();
461	}
462
463	private void showAskForPresenceDialog(final Contact contact) {
464		AlertDialog.Builder builder = new AlertDialog.Builder(this);
465		builder.setTitle(contact.getJid().toString());
466		builder.setMessage(R.string.request_presence_updates);
467		builder.setNegativeButton(R.string.cancel, null);
468		builder.setPositiveButton(R.string.request_now,
469				new DialogInterface.OnClickListener() {
470
471					@Override
472					public void onClick(DialogInterface dialog, int which) {
473						if (xmppConnectionServiceBound) {
474							xmppConnectionService.sendPresencePacket(contact
475									.getAccount(), xmppConnectionService
476									.getPresenceGenerator()
477									.requestPresenceUpdatesFrom(contact));
478						}
479					}
480				});
481		builder.create().show();
482	}
483
484	private void warnMutalPresenceSubscription(final Conversation conversation,
485			final OnPresenceSelected listener) {
486		AlertDialog.Builder builder = new AlertDialog.Builder(this);
487		builder.setTitle(conversation.getContact().getJid().toString());
488		builder.setMessage(R.string.without_mutual_presence_updates);
489		builder.setNegativeButton(R.string.cancel, null);
490		builder.setPositiveButton(R.string.ignore, new OnClickListener() {
491
492			@Override
493			public void onClick(DialogInterface dialog, int which) {
494				conversation.setNextCounterpart(null);
495				if (listener != null) {
496					listener.onPresenceSelected();
497				}
498			}
499		});
500		builder.create().show();
501	}
502
503	protected void quickEdit(String previousValue, OnValueEdited callback) {
504		quickEdit(previousValue, callback, false);
505	}
506
507	protected void quickPasswordEdit(String previousValue,
508			OnValueEdited callback) {
509		quickEdit(previousValue, callback, true);
510	}
511
512	@SuppressLint("InflateParams")
513	private void quickEdit(final String previousValue,
514			final OnValueEdited callback, boolean password) {
515		AlertDialog.Builder builder = new AlertDialog.Builder(this);
516		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
517		final EditText editor = (EditText) view.findViewById(R.id.editor);
518		OnClickListener mClickListener = new OnClickListener() {
519
520			@Override
521			public void onClick(DialogInterface dialog, int which) {
522				String value = editor.getText().toString();
523				if (!previousValue.equals(value) && value.trim().length() > 0) {
524					callback.onValueEdited(value);
525				}
526			}
527		};
528		if (password) {
529			editor.setInputType(InputType.TYPE_CLASS_TEXT
530					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
531			editor.setHint(R.string.password);
532			builder.setPositiveButton(R.string.accept, mClickListener);
533		} else {
534			builder.setPositiveButton(R.string.edit, mClickListener);
535		}
536		editor.requestFocus();
537		editor.setText(previousValue);
538		builder.setView(view);
539		builder.setNegativeButton(R.string.cancel, null);
540		builder.create().show();
541	}
542
543	public void selectPresence(final Conversation conversation,
544			final OnPresenceSelected listener) {
545		final Contact contact = conversation.getContact();
546		if (conversation.hasValidOtrSession()) {
547			SessionID id = conversation.getOtrSession().getSessionID();
548			Jid jid;
549			try {
550				jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
551			} catch (InvalidJidException e) {
552				jid = null;
553			}
554			conversation.setNextCounterpart(jid);
555			listener.onPresenceSelected();
556		} else 	if (!contact.showInRoster()) {
557			showAddToRosterDialog(conversation);
558		} else {
559			Presences presences = contact.getPresences();
560			if (presences.size() == 0) {
561				if (!contact.getOption(Contact.Options.TO)
562						&& !contact.getOption(Contact.Options.ASKING)
563						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
564					showAskForPresenceDialog(contact);
565				} else if (!contact.getOption(Contact.Options.TO)
566						|| !contact.getOption(Contact.Options.FROM)) {
567					warnMutalPresenceSubscription(conversation, listener);
568				} else {
569					conversation.setNextCounterpart(null);
570					listener.onPresenceSelected();
571				}
572			} else if (presences.size() == 1) {
573				String presence = presences.asStringArray()[0];
574				try {
575					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
576				} catch (InvalidJidException e) {
577					conversation.setNextCounterpart(null);
578				}
579				listener.onPresenceSelected();
580			} else {
581				final StringBuilder presence = new StringBuilder();
582				AlertDialog.Builder builder = new AlertDialog.Builder(this);
583				builder.setTitle(getString(R.string.choose_presence));
584				final String[] presencesArray = presences.asStringArray();
585				int preselectedPresence = 0;
586				for (int i = 0; i < presencesArray.length; ++i) {
587					if (presencesArray[i].equals(contact.lastseen.presence)) {
588						preselectedPresence = i;
589						break;
590					}
591				}
592				presence.append(presencesArray[preselectedPresence]);
593				builder.setSingleChoiceItems(presencesArray,
594						preselectedPresence,
595						new DialogInterface.OnClickListener() {
596
597							@Override
598							public void onClick(DialogInterface dialog,
599									int which) {
600								presence.delete(0, presence.length());
601								presence.append(presencesArray[which]);
602							}
603						});
604				builder.setNegativeButton(R.string.cancel, null);
605				builder.setPositiveButton(R.string.ok, new OnClickListener() {
606
607					@Override
608					public void onClick(DialogInterface dialog, int which) {
609						try {
610							conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
611						} catch (InvalidJidException e) {
612							conversation.setNextCounterpart(null);
613						}
614						listener.onPresenceSelected();
615					}
616				});
617				builder.create().show();
618			}
619		}
620	}
621
622	protected void onActivityResult(int requestCode, int resultCode,
623			final Intent data) {
624		super.onActivityResult(requestCode, resultCode, data);
625		if (requestCode == REQUEST_INVITE_TO_CONVERSATION
626				&& resultCode == RESULT_OK) {
627			try {
628				Jid jid = Jid.fromString(data.getStringExtra("contact"));
629				String conversationUuid = data.getStringExtra("conversation");
630				Conversation conversation = xmppConnectionService
631					.findConversationByUuid(conversationUuid);
632				if (conversation.getMode() == Conversation.MODE_MULTI) {
633					xmppConnectionService.invite(conversation, jid);
634				} else {
635					List<Jid> jids = new ArrayList<Jid>();
636					jids.add(conversation.getJid().toBareJid());
637					jids.add(jid);
638					xmppConnectionService.createAdhocConference(conversation.getAccount(), jids, adhocCallback);
639				}
640			} catch (final InvalidJidException ignored) {
641
642			}
643				}
644	}
645
646	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
647		@Override
648		public void success(final Conversation conversation) {
649			switchToConversation(conversation);
650			runOnUiThread(new Runnable() {
651				@Override
652				public void run() {
653					Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
654				}
655			});
656		}
657
658		@Override
659		public void error(final int errorCode, Conversation object) {
660			runOnUiThread(new Runnable() {
661				@Override
662				public void run() {
663					Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
664				}
665			});
666		}
667
668		@Override
669		public void userInputRequried(PendingIntent pi, Conversation object) {
670
671		}
672	};
673
674	public int getSecondaryTextColor() {
675		return this.mSecondaryTextColor;
676	}
677
678	public int getPrimaryTextColor() {
679		return this.mPrimaryTextColor;
680	}
681
682	public int getWarningTextColor() {
683		return this.mColorRed;
684	}
685
686	public int getPrimaryColor() {
687		return this.mPrimaryColor;
688	}
689
690	public int getOnlineColor() {
691		return this.mColorGreen;
692	}
693	
694	public int getSecondaryBackgroundColor() {
695		return this.mSecondaryBackgroundColor;
696	}
697
698	public int getPixel(int dp) {
699		DisplayMetrics metrics = getResources().getDisplayMetrics();
700		return ((int) (dp * metrics.density));
701	}
702
703	public boolean copyTextToClipboard(String text, int labelResId) {
704		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
705		String label = getResources().getString(labelResId);
706		if (mClipBoardManager != null) {
707			ClipData mClipData = ClipData.newPlainText(label, text);
708			mClipBoardManager.setPrimaryClip(mClipData);
709			return true;
710		}
711		return false;
712	}
713
714	protected void registerNdefPushMessageCallback() {
715		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
716		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
717			nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
718				@Override
719				public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
720					return new NdefMessage(new NdefRecord[]{
721						NdefRecord.createUri(getShareableUri()),
722							NdefRecord.createApplicationRecord("eu.siacs.conversations")
723					});
724				}
725			}, this);
726		}
727	}
728
729	protected void unregisterNdefPushMessageCallback() {
730		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
731		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
732			nfcAdapter.setNdefPushMessageCallback(null,this);
733		}
734	}
735
736	protected String getShareableUri() {
737		return null;
738	}
739
740	@Override
741	public void onResume() {
742		super.onResume();
743		if (this.getShareableUri()!=null) {
744			this.registerNdefPushMessageCallback();
745		}
746	}
747
748	protected int findTheme() {
749		if (getPreferences().getBoolean("use_larger_font", false)) {
750			return R.style.ConversationsTheme_LargerText;
751		} else {
752			return R.style.ConversationsTheme;
753		}
754	}
755
756	@Override
757	public void onPause() {
758		super.onPause();
759		this.unregisterNdefPushMessageCallback();
760	}
761
762	protected void showQrCode() {
763		String uri = getShareableUri();
764		if (uri!=null) {
765			Point size = new Point();
766			getWindowManager().getDefaultDisplay().getSize(size);
767			final int width = (size.x < size.y ? size.x : size.y);
768			Bitmap bitmap = createQrCodeBitmap(uri, width);
769			ImageView view = new ImageView(this);
770			view.setImageBitmap(bitmap);
771			AlertDialog.Builder builder = new AlertDialog.Builder(this);
772			builder.setView(view);
773			builder.create().show();
774		}
775	}
776
777	protected Bitmap createQrCodeBitmap(String input, int size) {
778		Log.d(Config.LOGTAG,"qr code requested size: "+size);
779		try {
780			final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
781			final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
782			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
783			final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
784			final int width = result.getWidth();
785			final int height = result.getHeight();
786			final int[] pixels = new int[width * height];
787			for (int y = 0; y < height; y++) {
788				final int offset = y * width;
789				for (int x = 0; x < width; x++) {
790					pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
791				}
792			}
793			final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
794			Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
795			bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
796			return bitmap;
797		} catch (final WriterException e) {
798			return null;
799		}
800	}
801
802	public AvatarService avatarService() {
803		return xmppConnectionService.getAvatarService();
804	}
805
806	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
807		private final WeakReference<ImageView> imageViewReference;
808		private Message message = null;
809
810		public BitmapWorkerTask(ImageView imageView) {
811			imageViewReference = new WeakReference<>(imageView);
812		}
813
814		@Override
815		protected Bitmap doInBackground(Message... params) {
816			message = params[0];
817			try {
818				return xmppConnectionService.getFileBackend().getThumbnail(
819						message, (int) (metrics.density * 288), false);
820			} catch (FileNotFoundException e) {
821				return null;
822			}
823		}
824
825		@Override
826		protected void onPostExecute(Bitmap bitmap) {
827			if (bitmap != null) {
828				final ImageView imageView = imageViewReference.get();
829				if (imageView != null) {
830					imageView.setImageBitmap(bitmap);
831					imageView.setBackgroundColor(0x00000000);
832				}
833			}
834		}
835	}
836
837	public void loadBitmap(Message message, ImageView imageView) {
838		Bitmap bm;
839		try {
840			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
841					(int) (metrics.density * 288), true);
842		} catch (FileNotFoundException e) {
843			bm = null;
844		}
845		if (bm != null) {
846			imageView.setImageBitmap(bm);
847			imageView.setBackgroundColor(0x00000000);
848		} else {
849			if (cancelPotentialWork(message, imageView)) {
850				imageView.setBackgroundColor(0xff333333);
851				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
852				final AsyncDrawable asyncDrawable = new AsyncDrawable(
853						getResources(), null, task);
854				imageView.setImageDrawable(asyncDrawable);
855				try {
856					task.execute(message);
857				} catch (final RejectedExecutionException ignored) {
858				}
859			}
860		}
861	}
862
863	public static boolean cancelPotentialWork(Message message,
864			ImageView imageView) {
865		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
866
867		if (bitmapWorkerTask != null) {
868			final Message oldMessage = bitmapWorkerTask.message;
869			if (oldMessage == null || message != oldMessage) {
870				bitmapWorkerTask.cancel(true);
871			} else {
872				return false;
873			}
874		}
875		return true;
876	}
877
878	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
879		if (imageView != null) {
880			final Drawable drawable = imageView.getDrawable();
881			if (drawable instanceof AsyncDrawable) {
882				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
883				return asyncDrawable.getBitmapWorkerTask();
884			}
885		}
886		return null;
887	}
888
889	static class AsyncDrawable extends BitmapDrawable {
890		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
891
892		public AsyncDrawable(Resources res, Bitmap bitmap,
893				BitmapWorkerTask bitmapWorkerTask) {
894			super(res, bitmap);
895			bitmapWorkerTaskReference = new WeakReference<>(
896					bitmapWorkerTask);
897		}
898
899		public BitmapWorkerTask getBitmapWorkerTask() {
900			return bitmapWorkerTaskReference.get();
901		}
902	}
903}