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