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