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