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