XmppActivity.java

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