ConversationActivity.java

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