ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import java.io.FileNotFoundException;
   4import java.lang.ref.WeakReference;
   5import java.util.ArrayList;
   6import java.util.Hashtable;
   7import java.util.List;
   8
   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.ImageProvider;
  16import eu.siacs.conversations.utils.ExceptionHelper;
  17import eu.siacs.conversations.utils.UIHelper;
  18import android.net.Uri;
  19import android.os.AsyncTask;
  20import android.os.Bundle;
  21import android.preference.PreferenceManager;
  22import android.provider.MediaStore;
  23import android.app.AlertDialog;
  24import android.app.FragmentTransaction;
  25import android.app.PendingIntent;
  26import android.content.Context;
  27import android.content.DialogInterface;
  28import android.content.DialogInterface.OnClickListener;
  29import android.content.IntentSender.SendIntentException;
  30import android.content.Intent;
  31import android.content.SharedPreferences;
  32import android.content.res.Resources;
  33import android.graphics.Bitmap;
  34import android.graphics.Color;
  35import android.graphics.Typeface;
  36import android.graphics.drawable.BitmapDrawable;
  37import android.graphics.drawable.Drawable;
  38import android.support.v4.widget.SlidingPaneLayout;
  39import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  40import android.util.DisplayMetrics;
  41import android.util.Log;
  42import android.view.KeyEvent;
  43import android.view.LayoutInflater;
  44import android.view.Menu;
  45import android.view.MenuItem;
  46import android.view.View;
  47import android.view.ViewGroup;
  48import android.widget.AdapterView;
  49import android.widget.AdapterView.OnItemClickListener;
  50import android.widget.ArrayAdapter;
  51import android.widget.CheckBox;
  52import android.widget.ListView;
  53import android.widget.PopupMenu;
  54import android.widget.PopupMenu.OnMenuItemClickListener;
  55import android.widget.TextView;
  56import android.widget.ImageView;
  57import android.widget.Toast;
  58
  59public class ConversationActivity extends XmppActivity {
  60
  61	public static final String VIEW_CONVERSATION = "viewConversation";
  62	public static final String CONVERSATION = "conversationUuid";
  63	public static final String TEXT = "text";
  64	public static final String PRESENCE = "eu.siacs.conversations.presence";
  65
  66	public static final int REQUEST_SEND_MESSAGE = 0x75441;
  67	public static final int REQUEST_DECRYPT_PGP = 0x76783;
  68	private static final int REQUEST_ATTACH_FILE_DIALOG = 0x48502;
  69	private static final int REQUEST_IMAGE_CAPTURE = 0x33788;
  70	private static final int REQUEST_RECORD_AUDIO = 0x46189;
  71	private static final int REQUEST_SEND_PGP_IMAGE = 0x53883;
  72	public static final int REQUEST_ENCRYPT_MESSAGE = 0x378018;
  73
  74	private static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x92734;
  75	private static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x84123;
  76	private static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x75291;
  77
  78	protected SlidingPaneLayout spl;
  79
  80	private List<Conversation> conversationList = new ArrayList<Conversation>();
  81	private Conversation selectedConversation = null;
  82	private ListView listView;
  83
  84	private boolean paneShouldBeOpen = true;
  85	private boolean useSubject = true;
  86	private boolean showLastseen = false;
  87	private ArrayAdapter<Conversation> listAdapter;
  88
  89	private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() {
  90
  91		@Override
  92		public void onConversationListChanged() {
  93			runOnUiThread(new Runnable() {
  94
  95				@Override
  96				public void run() {
  97					updateConversationList();
  98					if (paneShouldBeOpen) {
  99						if (conversationList.size() >= 1) {
 100							swapConversationFragment();
 101						} else {
 102							startActivity(new Intent(getApplicationContext(),
 103									ContactsActivity.class));
 104							finish();
 105						}
 106					}
 107					ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
 108							.findFragmentByTag("conversation");
 109					if (selectedFragment != null) {
 110						selectedFragment.updateMessages();
 111					}
 112				}
 113			});
 114		}
 115	};
 116
 117	protected ConversationActivity activity = this;
 118	private DisplayMetrics metrics;
 119	private Toast prepareImageToast;
 120
 121	public List<Conversation> getConversationList() {
 122		return this.conversationList;
 123	}
 124
 125	public Conversation getSelectedConversation() {
 126		return this.selectedConversation;
 127	}
 128
 129	public void setSelectedConversation(Conversation conversation) {
 130		this.selectedConversation = conversation;
 131	}
 132
 133	public ListView getConversationListView() {
 134		return this.listView;
 135	}
 136
 137	public SlidingPaneLayout getSlidingPaneLayout() {
 138		return this.spl;
 139	}
 140
 141	public boolean shouldPaneBeOpen() {
 142		return paneShouldBeOpen;
 143	}
 144
 145	@Override
 146	protected void onCreate(Bundle savedInstanceState) {
 147
 148		metrics = getResources().getDisplayMetrics();
 149
 150		super.onCreate(savedInstanceState);
 151
 152		setContentView(R.layout.fragment_conversations_overview);
 153
 154		listView = (ListView) findViewById(R.id.list);
 155
 156		this.listAdapter = new ArrayAdapter<Conversation>(this,
 157				R.layout.conversation_list_row, conversationList) {
 158			@Override
 159			public View getView(int position, View view, ViewGroup parent) {
 160				if (view == null) {
 161					LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 162					view = (View) inflater.inflate(
 163							R.layout.conversation_list_row, null);
 164				}
 165				Conversation conv;
 166				if (conversationList.size() > position) {
 167					conv = getItem(position);
 168				} else {
 169					return view;
 170				}
 171				if (!spl.isSlideable()) {
 172					if (conv == getSelectedConversation()) {
 173						view.setBackgroundColor(0xffdddddd);
 174					} else {
 175						view.setBackgroundColor(Color.TRANSPARENT);
 176					}
 177				} else {
 178					view.setBackgroundColor(Color.TRANSPARENT);
 179				}
 180				TextView convName = (TextView) view
 181						.findViewById(R.id.conversation_name);
 182				convName.setText(conv.getName(useSubject));
 183				TextView convLastMsg = (TextView) view
 184						.findViewById(R.id.conversation_lastmsg);
 185				ImageView imagePreview = (ImageView) view
 186						.findViewById(R.id.conversation_lastimage);
 187
 188				Message latestMessage = conv.getLatestMessage();
 189
 190				if (latestMessage.getType() == Message.TYPE_TEXT) {
 191					if ((latestMessage.getEncryption() != Message.ENCRYPTION_PGP)
 192							&& (latestMessage.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED)) {
 193						convLastMsg.setText(conv.getLatestMessage().getBody());
 194					} else {
 195						convLastMsg
 196								.setText(getText(R.string.encrypted_message_received));
 197					}
 198					convLastMsg.setVisibility(View.VISIBLE);
 199					imagePreview.setVisibility(View.GONE);
 200				} else if (latestMessage.getType() == Message.TYPE_IMAGE) {
 201					if (latestMessage.getStatus() >= Message.STATUS_RECIEVED) {
 202						convLastMsg.setVisibility(View.GONE);
 203						imagePreview.setVisibility(View.VISIBLE);
 204						loadBitmap(latestMessage, imagePreview);
 205					} else {
 206						convLastMsg.setVisibility(View.VISIBLE);
 207						imagePreview.setVisibility(View.GONE);
 208						if (latestMessage.getStatus() == Message.STATUS_RECEIVED_OFFER) {
 209							convLastMsg
 210									.setText(getText(R.string.image_offered_for_download));
 211						} else if (latestMessage.getStatus() == Message.STATUS_RECIEVING) {
 212							convLastMsg
 213									.setText(getText(R.string.receiving_image));
 214						} else {
 215							convLastMsg.setText("");
 216						}
 217					}
 218				}
 219
 220				if (!conv.isRead()) {
 221					convName.setTypeface(null, Typeface.BOLD);
 222					convLastMsg.setTypeface(null, Typeface.BOLD);
 223				} else {
 224					convName.setTypeface(null, Typeface.NORMAL);
 225					convLastMsg.setTypeface(null, Typeface.NORMAL);
 226				}
 227
 228				((TextView) view.findViewById(R.id.conversation_lastupdate))
 229						.setText(UIHelper.readableTimeDifference(getContext(),
 230								conv.getLatestMessage().getTimeSent()));
 231
 232				ImageView profilePicture = (ImageView) view
 233						.findViewById(R.id.conversation_image);
 234				profilePicture.setImageBitmap(UIHelper.getContactPicture(conv,
 235						56, activity.getApplicationContext(), false));
 236
 237				return view;
 238			}
 239
 240		};
 241
 242		listView.setAdapter(this.listAdapter);
 243
 244		listView.setOnItemClickListener(new OnItemClickListener() {
 245
 246			@Override
 247			public void onItemClick(AdapterView<?> arg0, View clickedView,
 248					int position, long arg3) {
 249				paneShouldBeOpen = false;
 250				if (getSelectedConversation() != conversationList.get(position)) {
 251					setSelectedConversation(conversationList.get(position));
 252					swapConversationFragment(); // .onBackendConnected(conversationList.get(position));
 253				} else {
 254					spl.closePane();
 255				}
 256			}
 257		});
 258		spl = (SlidingPaneLayout) findViewById(R.id.slidingpanelayout);
 259		spl.setParallaxDistance(150);
 260		spl.setShadowResource(R.drawable.es_slidingpane_shadow);
 261		spl.setSliderFadeColor(0);
 262		spl.setPanelSlideListener(new PanelSlideListener() {
 263
 264			@Override
 265			public void onPanelOpened(View arg0) {
 266				paneShouldBeOpen = true;
 267				getActionBar().setDisplayHomeAsUpEnabled(false);
 268				getActionBar().setHomeButtonEnabled(false);
 269				getActionBar().setTitle(R.string.app_name);
 270				invalidateOptionsMenu();
 271				hideKeyboard();
 272				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
 273						.findFragmentByTag("conversation");
 274				if (selectedFragment != null) {
 275					selectedFragment.lastSeen.setVisibility(View.GONE);
 276				}
 277			}
 278
 279			@Override
 280			public void onPanelClosed(View arg0) {
 281				paneShouldBeOpen = false;
 282				if ((conversationList.size() > 0)
 283						&& (getSelectedConversation() != null)) {
 284					getActionBar().setDisplayHomeAsUpEnabled(true);
 285					getActionBar().setHomeButtonEnabled(true);
 286					getActionBar().setTitle(
 287							getSelectedConversation().getName(useSubject));
 288					invalidateOptionsMenu();
 289					if (!getSelectedConversation().isRead()) {
 290						xmppConnectionService
 291								.markRead(getSelectedConversation());
 292						UIHelper.updateNotification(getApplicationContext(),
 293								getConversationList(), null, false);
 294						listView.invalidateViews();
 295					}
 296					ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
 297							.findFragmentByTag("conversation");
 298					if ((selectedFragment != null) && (showLastseen())) {
 299						selectedFragment.lastSeen.setVisibility(View.VISIBLE);
 300					}
 301				}
 302			}
 303
 304			@Override
 305			public void onPanelSlide(View arg0, float arg1) {
 306				// TODO Auto-generated method stub
 307
 308			}
 309		});
 310	}
 311
 312	@Override
 313	public boolean onCreateOptionsMenu(Menu menu) {
 314		getMenuInflater().inflate(R.menu.conversations, menu);
 315		MenuItem menuSecure = (MenuItem) menu.findItem(R.id.action_security);
 316		MenuItem menuArchive = (MenuItem) menu.findItem(R.id.action_archive);
 317		MenuItem menuMucDetails = (MenuItem) menu
 318				.findItem(R.id.action_muc_details);
 319		MenuItem menuContactDetails = (MenuItem) menu
 320				.findItem(R.id.action_contact_details);
 321		MenuItem menuInviteContacts = (MenuItem) menu
 322				.findItem(R.id.action_invite);
 323		MenuItem menuAttach = (MenuItem) menu.findItem(R.id.action_attach_file);
 324		MenuItem menuClearHistory = (MenuItem) menu
 325				.findItem(R.id.action_clear_history);
 326
 327		if ((spl.isOpen() && (spl.isSlideable()))) {
 328			menuArchive.setVisible(false);
 329			menuMucDetails.setVisible(false);
 330			menuContactDetails.setVisible(false);
 331			menuSecure.setVisible(false);
 332			menuInviteContacts.setVisible(false);
 333			menuAttach.setVisible(false);
 334			menuClearHistory.setVisible(false);
 335		} else {
 336			((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl
 337					.isSlideable());
 338			if (this.getSelectedConversation() != null) {
 339				if (this.getSelectedConversation().getLatestMessage()
 340						.getEncryption() != Message.ENCRYPTION_NONE) {
 341					menuSecure.setIcon(R.drawable.ic_action_secure);
 342				}
 343				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 344					menuContactDetails.setVisible(false);
 345					menuAttach.setVisible(false);
 346				} else {
 347					menuMucDetails.setVisible(false);
 348					menuInviteContacts.setVisible(false);
 349				}
 350			}
 351		}
 352		return true;
 353	}
 354
 355	private void selectPresenceToAttachFile(final int attachmentChoice) {
 356		selectPresence(getSelectedConversation(), new OnPresenceSelected() {
 357
 358			@Override
 359			public void onPresenceSelected(boolean success, String presence) {
 360				if (success) {
 361					if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO) {
 362						Intent takePictureIntent = new Intent(
 363								MediaStore.ACTION_IMAGE_CAPTURE);
 364						takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
 365								ImageProvider.getIncomingContentUri());
 366						if (takePictureIntent
 367								.resolveActivity(getPackageManager()) != null) {
 368							startActivityForResult(takePictureIntent,
 369									REQUEST_IMAGE_CAPTURE);
 370						}
 371					} else if (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
 372						Intent attachFileIntent = new Intent();
 373						attachFileIntent.setType("image/*");
 374						attachFileIntent.setAction(Intent.ACTION_GET_CONTENT);
 375						Intent chooser = Intent.createChooser(attachFileIntent,
 376								getString(R.string.attach_file));
 377						startActivityForResult(chooser,
 378								REQUEST_ATTACH_FILE_DIALOG);
 379					} else if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
 380						Intent intent = new Intent(
 381								MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 382						startActivityForResult(intent, REQUEST_RECORD_AUDIO);
 383					}
 384				}
 385			}
 386
 387			@Override
 388			public void onSendPlainTextInstead() {
 389				// TODO Auto-generated method stub
 390
 391			}
 392		}, "file");
 393	}
 394
 395	private void attachFile(final int attachmentChoice) {
 396		final Conversation conversation = getSelectedConversation();
 397		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 398			if (hasPgp()) {
 399				if (conversation.getContact().getPgpKeyId() != 0) {
 400					xmppConnectionService.getPgpEngine().hasKey(
 401							conversation.getContact(),
 402							new UiCallback<Contact>() {
 403
 404								@Override
 405								public void userInputRequried(PendingIntent pi,
 406										Contact contact) {
 407									ConversationActivity.this.runIntent(pi,
 408											attachmentChoice);
 409								}
 410
 411								@Override
 412								public void success(Contact contact) {
 413									selectPresenceToAttachFile(attachmentChoice);
 414								}
 415
 416								@Override
 417								public void error(int error, Contact contact) {
 418									displayErrorDialog(error);
 419								}
 420							});
 421				} else {
 422					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 423							.findFragmentByTag("conversation");
 424					if (fragment != null) {
 425						fragment.showNoPGPKeyDialog(false,
 426								new OnClickListener() {
 427
 428									@Override
 429									public void onClick(DialogInterface dialog,
 430											int which) {
 431										conversation
 432												.setNextEncryption(Message.ENCRYPTION_NONE);
 433										selectPresenceToAttachFile(attachmentChoice);
 434									}
 435								});
 436					}
 437				}
 438			} else {
 439				showInstallPgpDialog();
 440			}
 441		} else if (getSelectedConversation().getNextEncryption() == Message.ENCRYPTION_NONE) {
 442			selectPresenceToAttachFile(attachmentChoice);
 443		} else {
 444			AlertDialog.Builder builder = new AlertDialog.Builder(this);
 445			builder.setTitle(getString(R.string.otr_file_transfer));
 446			builder.setMessage(getString(R.string.otr_file_transfer_msg));
 447			builder.setNegativeButton(getString(R.string.cancel), null);
 448			if (conversation.getContact().getPgpKeyId() == 0) {
 449				builder.setPositiveButton(getString(R.string.send_unencrypted),
 450						new OnClickListener() {
 451
 452							@Override
 453							public void onClick(DialogInterface dialog,
 454									int which) {
 455								conversation
 456										.setNextEncryption(Message.ENCRYPTION_NONE);
 457								attachFile(attachmentChoice);
 458							}
 459						});
 460			} else {
 461				builder.setPositiveButton(
 462						getString(R.string.use_pgp_encryption),
 463						new OnClickListener() {
 464
 465							@Override
 466							public void onClick(DialogInterface dialog,
 467									int which) {
 468								conversation
 469										.setNextEncryption(Message.ENCRYPTION_PGP);
 470								attachFile(attachmentChoice);
 471							}
 472						});
 473			}
 474			builder.create().show();
 475		}
 476	}
 477
 478	@Override
 479	public boolean onOptionsItemSelected(MenuItem item) {
 480		switch (item.getItemId()) {
 481		case android.R.id.home:
 482			spl.openPane();
 483			break;
 484		case R.id.action_attach_file:
 485			View menuAttachFile = findViewById(R.id.action_attach_file);
 486			PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 487			attachFilePopup.inflate(R.menu.attachment_choices);
 488			attachFilePopup
 489					.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 490
 491						@Override
 492						public boolean onMenuItemClick(MenuItem item) {
 493							switch (item.getItemId()) {
 494							case R.id.attach_choose_picture:
 495								attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 496								break;
 497							case R.id.attach_take_picture:
 498								attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 499								break;
 500							case R.id.attach_record_voice:
 501								attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 502								break;
 503							}
 504							return false;
 505						}
 506					});
 507			attachFilePopup.show();
 508			break;
 509		case R.id.action_add:
 510			startActivity(new Intent(this, ContactsActivity.class));
 511			break;
 512		case R.id.action_archive:
 513			this.endConversation(getSelectedConversation());
 514			break;
 515		case R.id.action_contact_details:
 516			Contact contact = this.getSelectedConversation().getContact();
 517			if (contact.showInRoster()) {
 518				Intent intent = new Intent(this, ContactDetailsActivity.class);
 519				intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 520				intent.putExtra("account", this.getSelectedConversation()
 521						.getAccount().getJid());
 522				intent.putExtra("contact", contact.getJid());
 523				startActivity(intent);
 524			} else {
 525				showAddToRosterDialog(getSelectedConversation());
 526			}
 527			break;
 528		case R.id.action_muc_details:
 529			Intent intent = new Intent(this, MucDetailsActivity.class);
 530			intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
 531			intent.putExtra("uuid", getSelectedConversation().getUuid());
 532			startActivity(intent);
 533			break;
 534		case R.id.action_invite:
 535			Intent inviteIntent = new Intent(getApplicationContext(),
 536					ContactsActivity.class);
 537			inviteIntent.setAction("invite");
 538			inviteIntent.putExtra("uuid", getSelectedConversation().getUuid());
 539			startActivity(inviteIntent);
 540			break;
 541		case R.id.action_security:
 542			final Conversation conversation = getSelectedConversation();
 543			View menuItemView = findViewById(R.id.action_security);
 544			PopupMenu popup = new PopupMenu(this, menuItemView);
 545			final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 546					.findFragmentByTag("conversation");
 547			if (fragment != null) {
 548				popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 549
 550					@Override
 551					public boolean onMenuItemClick(MenuItem item) {
 552						switch (item.getItemId()) {
 553						case R.id.encryption_choice_none:
 554							conversation
 555									.setNextEncryption(Message.ENCRYPTION_NONE);
 556							item.setChecked(true);
 557							break;
 558						case R.id.encryption_choice_otr:
 559							conversation
 560									.setNextEncryption(Message.ENCRYPTION_OTR);
 561							item.setChecked(true);
 562							break;
 563						case R.id.encryption_choice_pgp:
 564							if (hasPgp()) {
 565								if (conversation.getAccount().getKeys()
 566										.has("pgp_signature")) {
 567									conversation
 568											.setNextEncryption(Message.ENCRYPTION_PGP);
 569									item.setChecked(true);
 570								} else {
 571									announcePgp(conversation.getAccount(),
 572											conversation);
 573								}
 574							} else {
 575								showInstallPgpDialog();
 576							}
 577							break;
 578						default:
 579							conversation
 580									.setNextEncryption(Message.ENCRYPTION_NONE);
 581							break;
 582						}
 583						fragment.updateChatMsgHint();
 584						return true;
 585					}
 586				});
 587				popup.inflate(R.menu.encryption_choices);
 588				MenuItem otr = popup.getMenu().findItem(
 589						R.id.encryption_choice_otr);
 590				if (conversation.getMode() == Conversation.MODE_MULTI) {
 591					otr.setEnabled(false);
 592				}
 593				switch (conversation.getNextEncryption()) {
 594				case Message.ENCRYPTION_NONE:
 595					popup.getMenu().findItem(R.id.encryption_choice_none)
 596							.setChecked(true);
 597					break;
 598				case Message.ENCRYPTION_OTR:
 599					otr.setChecked(true);
 600					break;
 601				case Message.ENCRYPTION_PGP:
 602					popup.getMenu().findItem(R.id.encryption_choice_pgp)
 603							.setChecked(true);
 604					break;
 605				default:
 606					popup.getMenu().findItem(R.id.encryption_choice_none)
 607							.setChecked(true);
 608					break;
 609				}
 610				popup.show();
 611			}
 612
 613			break;
 614		case R.id.action_clear_history:
 615			clearHistoryDialog(getSelectedConversation());
 616			break;
 617		default:
 618			break;
 619		}
 620		return super.onOptionsItemSelected(item);
 621	}
 622
 623	private void endConversation(Conversation conversation) {
 624		conversation.setStatus(Conversation.STATUS_ARCHIVED);
 625		paneShouldBeOpen = true;
 626		spl.openPane();
 627		xmppConnectionService.archiveConversation(conversation);
 628		if (conversationList.size() > 0) {
 629			setSelectedConversation(conversationList.get(0));
 630		} else {
 631			setSelectedConversation(null);
 632		}
 633	}
 634
 635	protected void clearHistoryDialog(final Conversation conversation) {
 636		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 637		builder.setTitle(getString(R.string.clear_conversation_history));
 638		View dialogView = getLayoutInflater().inflate(
 639				R.layout.dialog_clear_history, null);
 640		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 641				.findViewById(R.id.end_conversation_checkbox);
 642		builder.setView(dialogView);
 643		builder.setNegativeButton(getString(R.string.cancel), null);
 644		builder.setPositiveButton(getString(R.string.delete_messages),
 645				new OnClickListener() {
 646
 647					@Override
 648					public void onClick(DialogInterface dialog, int which) {
 649						activity.xmppConnectionService
 650								.clearConversationHistory(conversation);
 651						if (endConversationCheckBox.isChecked()) {
 652							endConversation(conversation);
 653						}
 654					}
 655				});
 656		builder.create().show();
 657	}
 658
 659	protected ConversationFragment swapConversationFragment() {
 660		ConversationFragment selectedFragment = new ConversationFragment();
 661
 662		FragmentTransaction transaction = getFragmentManager()
 663				.beginTransaction();
 664		transaction.replace(R.id.selected_conversation, selectedFragment,
 665				"conversation");
 666		transaction.commit();
 667		return selectedFragment;
 668	}
 669
 670	@Override
 671	public boolean onKeyDown(int keyCode, KeyEvent event) {
 672		if (keyCode == KeyEvent.KEYCODE_BACK) {
 673			if (!spl.isOpen()) {
 674				spl.openPane();
 675				return false;
 676			}
 677		}
 678		return super.onKeyDown(keyCode, event);
 679	}
 680
 681	@Override
 682	protected void onNewIntent(Intent intent) {
 683		if ((Intent.ACTION_VIEW.equals(intent.getAction()) && (VIEW_CONVERSATION
 684				.equals(intent.getType())))) {
 685			String convToView = (String) intent.getExtras().get(CONVERSATION);
 686			updateConversationList();
 687			for (int i = 0; i < conversationList.size(); ++i) {
 688				if (conversationList.get(i).getUuid().equals(convToView)) {
 689					setSelectedConversation(conversationList.get(i));
 690					break;
 691				}
 692			}
 693			paneShouldBeOpen = false;
 694			String text = intent.getExtras().getString(TEXT, null);
 695			swapConversationFragment().setText(text);
 696		}
 697	}
 698
 699	@Override
 700	public void onStart() {
 701		super.onStart();
 702		SharedPreferences preferences = PreferenceManager
 703				.getDefaultSharedPreferences(this);
 704		this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
 705		this.showLastseen = preferences.getBoolean("show_last_seen", false);
 706		if (this.xmppConnectionServiceBound) {
 707			this.onBackendConnected();
 708		}
 709		if (conversationList.size() >= 1) {
 710			onConvChanged.onConversationListChanged();
 711		}
 712	}
 713
 714	@Override
 715	protected void onStop() {
 716		if (xmppConnectionServiceBound) {
 717			xmppConnectionService.removeOnConversationListChangedListener();
 718		}
 719		super.onStop();
 720	}
 721
 722	@Override
 723	void onBackendConnected() {
 724		this.registerListener();
 725		if (conversationList.size() == 0) {
 726			updateConversationList();
 727		}
 728
 729		if ((getIntent().getAction() != null)
 730				&& (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
 731			if (getIntent().getType().equals(
 732					ConversationActivity.VIEW_CONVERSATION)) {
 733				handledViewIntent = true;
 734
 735				String convToView = (String) getIntent().getExtras().get(
 736						CONVERSATION);
 737
 738				for (int i = 0; i < conversationList.size(); ++i) {
 739					if (conversationList.get(i).getUuid().equals(convToView)) {
 740						setSelectedConversation(conversationList.get(i));
 741					}
 742				}
 743				paneShouldBeOpen = false;
 744				String text = getIntent().getExtras().getString(TEXT, null);
 745				swapConversationFragment().setText(text);
 746			}
 747		} else {
 748			if (xmppConnectionService.getAccounts().size() == 0) {
 749				startActivity(new Intent(this, ManageAccountActivity.class));
 750				finish();
 751			} else if (conversationList.size() <= 0) {
 752				// add no history
 753				startActivity(new Intent(this, ContactsActivity.class));
 754				finish();
 755			} else {
 756				spl.openPane();
 757				// find currently loaded fragment
 758				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
 759						.findFragmentByTag("conversation");
 760				if (selectedFragment != null) {
 761					selectedFragment.onBackendConnected();
 762				} else {
 763					setSelectedConversation(conversationList.get(0));
 764					swapConversationFragment();
 765				}
 766				ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
 767			}
 768		}
 769	}
 770
 771	public void registerListener() {
 772		if (xmppConnectionServiceBound) {
 773			xmppConnectionService
 774					.setOnConversationListChangedListener(this.onConvChanged);
 775		}
 776	}
 777
 778	@Override
 779	protected void onActivityResult(int requestCode, int resultCode,
 780			final Intent data) {
 781		super.onActivityResult(requestCode, resultCode, data);
 782		if (resultCode == RESULT_OK) {
 783			if (requestCode == REQUEST_DECRYPT_PGP) {
 784				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
 785						.findFragmentByTag("conversation");
 786				if (selectedFragment != null) {
 787					selectedFragment.hidePgpPassphraseBox();
 788				}
 789			} else if (requestCode == REQUEST_ATTACH_FILE_DIALOG) {
 790				attachImageToConversation(getSelectedConversation(),
 791						data.getData());
 792			} else if (requestCode == REQUEST_SEND_PGP_IMAGE) {
 793
 794			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
 795				attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 796			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
 797				attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 798			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
 799				announcePgp(getSelectedConversation().getAccount(),
 800						getSelectedConversation());
 801			} else if (requestCode == REQUEST_ENCRYPT_MESSAGE) {
 802				// encryptTextMessage();
 803			} else if (requestCode == REQUEST_IMAGE_CAPTURE) {
 804				attachImageToConversation(getSelectedConversation(), null);
 805			} else if (requestCode == REQUEST_RECORD_AUDIO) {
 806				Log.d("xmppService", data.getData().toString());
 807				attachAudioToConversation(getSelectedConversation(),
 808						data.getData());
 809			} else {
 810				Log.d(LOGTAG, "unknown result code:" + requestCode);
 811			}
 812		}
 813	}
 814
 815	private void attachAudioToConversation(Conversation conversation, Uri uri) {
 816
 817	}
 818
 819	private void attachImageToConversation(Conversation conversation, Uri uri) {
 820		prepareImageToast = Toast.makeText(getApplicationContext(),
 821				getText(R.string.preparing_image), Toast.LENGTH_LONG);
 822		prepareImageToast.show();
 823		xmppConnectionService.attachImageToConversation(conversation, uri,
 824				new UiCallback<Message>() {
 825
 826					@Override
 827					public void userInputRequried(PendingIntent pi,
 828							Message object) {
 829						hidePrepareImageToast();
 830						ConversationActivity.this.runIntent(pi,
 831								ConversationActivity.REQUEST_SEND_PGP_IMAGE);
 832					}
 833
 834					@Override
 835					public void success(Message message) {
 836						message.getConversation().getMessages().add(message);
 837						xmppConnectionService.databaseBackend
 838								.createMessage(message);
 839						xmppConnectionService.sendMessage(message);
 840						xmppConnectionService.updateUi(
 841								message.getConversation(), false);
 842					}
 843
 844					@Override
 845					public void error(int error, Message message) {
 846						hidePrepareImageToast();
 847						displayErrorDialog(error);
 848					}
 849				});
 850	}
 851
 852	private void hidePrepareImageToast() {
 853		if (prepareImageToast != null) {
 854			runOnUiThread(new Runnable() {
 855
 856				@Override
 857				public void run() {
 858					prepareImageToast.cancel();
 859				}
 860			});
 861		}
 862	}
 863
 864	public void updateConversationList() {
 865		conversationList.clear();
 866		conversationList.addAll(xmppConnectionService.getConversations());
 867		listView.invalidateViews();
 868	}
 869
 870	public void selectPresence(final Conversation conversation,
 871			final OnPresenceSelected listener, String reason) {
 872		Contact contact = conversation.getContact();
 873		if (contact == null) {
 874			showAddToRosterDialog(conversation);
 875			listener.onPresenceSelected(false, null);
 876		} else {
 877			Presences presences = contact.getPresences();
 878			if (presences.size() == 0) {
 879				listener.onPresenceSelected(true, null);
 880			} else if (presences.size() == 1) {
 881				String presence = (String) presences.asStringArray()[0];
 882				conversation.setNextPresence(presence);
 883				listener.onPresenceSelected(true, presence);
 884			} else {
 885				final StringBuilder presence = new StringBuilder();
 886				AlertDialog.Builder builder = new AlertDialog.Builder(this);
 887				builder.setTitle(getString(R.string.choose_presence));
 888				final String[] presencesArray = presences.asStringArray();
 889				int preselectedPresence = 0;
 890				for (int i = 0; i < presencesArray.length; ++i) {
 891					if (presencesArray[i].equals(contact.lastseen.presence)) {
 892						preselectedPresence = i;
 893						break;
 894					}
 895				}
 896				presence.append(presencesArray[preselectedPresence]);
 897				builder.setSingleChoiceItems(presencesArray,
 898						preselectedPresence,
 899						new DialogInterface.OnClickListener() {
 900
 901							@Override
 902							public void onClick(DialogInterface dialog,
 903									int which) {
 904								presence.delete(0, presence.length());
 905								presence.append(presencesArray[which]);
 906							}
 907						});
 908				builder.setNegativeButton(R.string.cancel, null);
 909				builder.setPositiveButton(R.string.ok, new OnClickListener() {
 910
 911					@Override
 912					public void onClick(DialogInterface dialog, int which) {
 913						conversation.setNextPresence(presence.toString());
 914						listener.onPresenceSelected(true, presence.toString());
 915					}
 916				});
 917				builder.create().show();
 918			}
 919		}
 920	}
 921
 922	public boolean showLastseen() {
 923		if (getSelectedConversation() == null) {
 924			return false;
 925		} else {
 926			return this.showLastseen
 927					&& getSelectedConversation().getMode() == Conversation.MODE_SINGLE;
 928		}
 929	}
 930
 931	private void showAddToRosterDialog(final Conversation conversation) {
 932		String jid = conversation.getContactJid();
 933		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 934		builder.setTitle(jid);
 935		builder.setMessage(getString(R.string.not_in_roster));
 936		builder.setNegativeButton(getString(R.string.cancel), null);
 937		builder.setPositiveButton(getString(R.string.add_contact),
 938				new DialogInterface.OnClickListener() {
 939
 940					@Override
 941					public void onClick(DialogInterface dialog, int which) {
 942						String jid = conversation.getContactJid();
 943						Account account = getSelectedConversation()
 944								.getAccount();
 945						Contact contact = account.getRoster().getContact(jid);
 946						xmppConnectionService.createContact(contact);
 947					}
 948				});
 949		builder.create().show();
 950	}
 951
 952	public void runIntent(PendingIntent pi, int requestCode) {
 953		try {
 954			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
 955					null, 0, 0, 0);
 956		} catch (SendIntentException e1) {
 957			Log.d("xmppService", "failed to start intent to send message");
 958		}
 959	}
 960
 961	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
 962		private final WeakReference<ImageView> imageViewReference;
 963		private Message message = null;
 964
 965		public BitmapWorkerTask(ImageView imageView) {
 966			imageViewReference = new WeakReference<ImageView>(imageView);
 967		}
 968
 969		@Override
 970		protected Bitmap doInBackground(Message... params) {
 971			message = params[0];
 972			try {
 973				return xmppConnectionService.getFileBackend().getThumbnail(
 974						message, (int) (metrics.density * 288), false);
 975			} catch (FileNotFoundException e) {
 976				Log.d("xmppService", "file not found!");
 977				return null;
 978			}
 979		}
 980
 981		@Override
 982		protected void onPostExecute(Bitmap bitmap) {
 983			if (imageViewReference != null && bitmap != null) {
 984				final ImageView imageView = imageViewReference.get();
 985				if (imageView != null) {
 986					imageView.setImageBitmap(bitmap);
 987					imageView.setBackgroundColor(0x00000000);
 988				}
 989			}
 990		}
 991	}
 992
 993	public void loadBitmap(Message message, ImageView imageView) {
 994		Bitmap bm;
 995		try {
 996			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
 997					(int) (metrics.density * 288), true);
 998		} catch (FileNotFoundException e) {
 999			bm = null;
1000		}
1001		if (bm != null) {
1002			imageView.setImageBitmap(bm);
1003			imageView.setBackgroundColor(0x00000000);
1004		} else {
1005			if (cancelPotentialWork(message, imageView)) {
1006				imageView.setBackgroundColor(0xff333333);
1007				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1008				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1009						getResources(), null, task);
1010				imageView.setImageDrawable(asyncDrawable);
1011				task.execute(message);
1012			}
1013		}
1014	}
1015
1016	public static boolean cancelPotentialWork(Message message,
1017			ImageView imageView) {
1018		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1019
1020		if (bitmapWorkerTask != null) {
1021			final Message oldMessage = bitmapWorkerTask.message;
1022			if (oldMessage == null || message != oldMessage) {
1023				bitmapWorkerTask.cancel(true);
1024			} else {
1025				return false;
1026			}
1027		}
1028		return true;
1029	}
1030
1031	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1032		if (imageView != null) {
1033			final Drawable drawable = imageView.getDrawable();
1034			if (drawable instanceof AsyncDrawable) {
1035				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1036				return asyncDrawable.getBitmapWorkerTask();
1037			}
1038		}
1039		return null;
1040	}
1041
1042	static class AsyncDrawable extends BitmapDrawable {
1043		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1044
1045		public AsyncDrawable(Resources res, Bitmap bitmap,
1046				BitmapWorkerTask bitmapWorkerTask) {
1047			super(res, bitmap);
1048			bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
1049					bitmapWorkerTask);
1050		}
1051
1052		public BitmapWorkerTask getBitmapWorkerTask() {
1053			return bitmapWorkerTaskReference.get();
1054		}
1055	}
1056
1057	public void encryptTextMessage(Message message) {
1058		xmppConnectionService.getPgpEngine().encrypt(message,
1059				new UiCallback<Message>() {
1060
1061					@Override
1062					public void userInputRequried(PendingIntent pi,
1063							Message message) {
1064						activity.runIntent(pi,
1065								ConversationActivity.REQUEST_SEND_MESSAGE);
1066					}
1067
1068					@Override
1069					public void success(Message message) {
1070						xmppConnectionService.sendMessage(message);
1071					}
1072
1073					@Override
1074					public void error(int error, Message message) {
1075
1076					}
1077				});
1078	}
1079}