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 protected int mTheme;
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 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
246 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
247 }
248 }
249
250 protected void unregisterListeners() {
251 if (this instanceof XmppConnectionService.OnConversationUpdate) {
252 this.xmppConnectionService.removeOnConversationListChangedListener();
253 }
254 if (this instanceof XmppConnectionService.OnAccountUpdate) {
255 this.xmppConnectionService.removeOnAccountListChangedListener();
256 }
257 if (this instanceof XmppConnectionService.OnRosterUpdate) {
258 this.xmppConnectionService.removeOnRosterUpdateListener();
259 }
260 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
261 this.xmppConnectionService.removeOnMucRosterUpdateListener();
262 }
263 }
264
265 public boolean onOptionsItemSelected(MenuItem item) {
266 switch (item.getItemId()) {
267 case R.id.action_settings:
268 startActivity(new Intent(this, SettingsActivity.class));
269 break;
270 case R.id.action_accounts:
271 startActivity(new Intent(this, ManageAccountActivity.class));
272 break;
273 case android.R.id.home:
274 finish();
275 break;
276 case R.id.action_show_qr_code:
277 showQrCode();
278 break;
279 }
280 return super.onOptionsItemSelected(item);
281 }
282
283 @Override
284 protected void onCreate(Bundle savedInstanceState) {
285 super.onCreate(savedInstanceState);
286 metrics = getResources().getDisplayMetrics();
287 ExceptionHelper.init(getApplicationContext());
288 mPrimaryTextColor = getResources().getColor(R.color.primarytext);
289 mSecondaryTextColor = getResources().getColor(R.color.secondarytext);
290 mColorRed = getResources().getColor(R.color.red);
291 mColorOrange = getResources().getColor(R.color.orange);
292 mColorGreen = getResources().getColor(R.color.green);
293 mPrimaryColor = getResources().getColor(R.color.primary);
294 mSecondaryBackgroundColor = getResources().getColor(
295 R.color.secondarybackground);
296 this.mTheme = findTheme();
297 setTheme(this.mTheme);
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 protected int findTheme() {
725 if (getPreferences().getBoolean("use_larger_font", false)) {
726 return R.style.ConversationsTheme_LargerText;
727 } else {
728 return R.style.ConversationsTheme;
729 }
730 }
731
732 @Override
733 public void onPause() {
734 super.onPause();
735 this.unregisterNdefPushMessageCallback();
736 }
737
738 protected void showQrCode() {
739 String uri = getShareableUri();
740 if (uri!=null) {
741 Point size = new Point();
742 getWindowManager().getDefaultDisplay().getSize(size);
743 final int width = (size.x < size.y ? size.x : size.y);
744 Bitmap bitmap = createQrCodeBitmap(uri, width);
745 ImageView view = new ImageView(this);
746 view.setImageBitmap(bitmap);
747 AlertDialog.Builder builder = new AlertDialog.Builder(this);
748 builder.setView(view);
749 builder.create().show();
750 }
751 }
752
753 protected Bitmap createQrCodeBitmap(String input, int size) {
754 Log.d(Config.LOGTAG,"qr code requested size: "+size);
755 try {
756 final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
757 final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
758 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
759 final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
760 final int width = result.getWidth();
761 final int height = result.getHeight();
762 final int[] pixels = new int[width * height];
763 for (int y = 0; y < height; y++) {
764 final int offset = y * width;
765 for (int x = 0; x < width; x++) {
766 pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
767 }
768 }
769 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
770 Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
771 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
772 return bitmap;
773 } catch (final WriterException e) {
774 return null;
775 }
776 }
777
778 public AvatarService avatarService() {
779 return xmppConnectionService.getAvatarService();
780 }
781
782 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
783 private final WeakReference<ImageView> imageViewReference;
784 private Message message = null;
785
786 public BitmapWorkerTask(ImageView imageView) {
787 imageViewReference = new WeakReference<>(imageView);
788 }
789
790 @Override
791 protected Bitmap doInBackground(Message... params) {
792 message = params[0];
793 try {
794 return xmppConnectionService.getFileBackend().getThumbnail(
795 message, (int) (metrics.density * 288), false);
796 } catch (FileNotFoundException e) {
797 return null;
798 }
799 }
800
801 @Override
802 protected void onPostExecute(Bitmap bitmap) {
803 if (bitmap != null) {
804 final ImageView imageView = imageViewReference.get();
805 if (imageView != null) {
806 imageView.setImageBitmap(bitmap);
807 imageView.setBackgroundColor(0x00000000);
808 }
809 }
810 }
811 }
812
813 public void loadBitmap(Message message, ImageView imageView) {
814 Bitmap bm;
815 try {
816 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
817 (int) (metrics.density * 288), true);
818 } catch (FileNotFoundException e) {
819 bm = null;
820 }
821 if (bm != null) {
822 imageView.setImageBitmap(bm);
823 imageView.setBackgroundColor(0x00000000);
824 } else {
825 if (cancelPotentialWork(message, imageView)) {
826 imageView.setBackgroundColor(0xff333333);
827 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
828 final AsyncDrawable asyncDrawable = new AsyncDrawable(
829 getResources(), null, task);
830 imageView.setImageDrawable(asyncDrawable);
831 try {
832 task.execute(message);
833 } catch (final RejectedExecutionException ignored) {
834 }
835 }
836 }
837 }
838
839 public static boolean cancelPotentialWork(Message message,
840 ImageView imageView) {
841 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
842
843 if (bitmapWorkerTask != null) {
844 final Message oldMessage = bitmapWorkerTask.message;
845 if (oldMessage == null || message != oldMessage) {
846 bitmapWorkerTask.cancel(true);
847 } else {
848 return false;
849 }
850 }
851 return true;
852 }
853
854 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
855 if (imageView != null) {
856 final Drawable drawable = imageView.getDrawable();
857 if (drawable instanceof AsyncDrawable) {
858 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
859 return asyncDrawable.getBitmapWorkerTask();
860 }
861 }
862 return null;
863 }
864
865 static class AsyncDrawable extends BitmapDrawable {
866 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
867
868 public AsyncDrawable(Resources res, Bitmap bitmap,
869 BitmapWorkerTask bitmapWorkerTask) {
870 super(res, bitmap);
871 bitmapWorkerTaskReference = new WeakReference<>(
872 bitmapWorkerTask);
873 }
874
875 public BitmapWorkerTask getBitmapWorkerTask() {
876 return bitmapWorkerTaskReference.get();
877 }
878 }
879}