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