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