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