1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.app.AlertDialog;
5import android.app.Fragment;
6import android.app.PendingIntent;
7import android.content.ActivityNotFoundException;
8import android.content.Context;
9import android.content.DialogInterface;
10import android.content.Intent;
11import android.content.IntentSender.SendIntentException;
12import android.os.Bundle;
13import android.os.Handler;
14import android.text.InputType;
15import android.util.Log;
16import android.util.Pair;
17import android.view.ContextMenu;
18import android.view.ContextMenu.ContextMenuInfo;
19import android.view.Gravity;
20import android.view.KeyEvent;
21import android.view.LayoutInflater;
22import android.view.MenuItem;
23import android.view.View;
24import android.view.View.OnClickListener;
25import android.view.ViewGroup;
26import android.view.inputmethod.EditorInfo;
27import android.view.inputmethod.InputMethodManager;
28import android.widget.AbsListView;
29import android.widget.AbsListView.OnScrollListener;
30import android.widget.AdapterView;
31import android.widget.AdapterView.AdapterContextMenuInfo;
32import android.widget.ImageButton;
33import android.widget.ListView;
34import android.widget.RelativeLayout;
35import android.widget.TextView;
36import android.widget.TextView.OnEditorActionListener;
37import android.widget.Toast;
38
39import net.java.otr4j.session.SessionStatus;
40
41import java.util.ArrayList;
42import java.util.Collections;
43import java.util.List;
44import java.util.UUID;
45
46import eu.siacs.conversations.Config;
47import eu.siacs.conversations.R;
48import eu.siacs.conversations.entities.Account;
49import eu.siacs.conversations.entities.Contact;
50import eu.siacs.conversations.entities.Conversation;
51import eu.siacs.conversations.entities.DownloadableFile;
52import eu.siacs.conversations.entities.Message;
53import eu.siacs.conversations.entities.MucOptions;
54import eu.siacs.conversations.entities.Presence;
55import eu.siacs.conversations.entities.Transferable;
56import eu.siacs.conversations.entities.TransferablePlaceholder;
57import eu.siacs.conversations.http.HttpDownloadConnection;
58import eu.siacs.conversations.services.MessageArchiveService;
59import eu.siacs.conversations.services.XmppConnectionService;
60import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
61import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
62import eu.siacs.conversations.ui.adapter.MessageAdapter;
63import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
64import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
65import eu.siacs.conversations.ui.widget.ListSelectionManager;
66import eu.siacs.conversations.utils.GeoHelper;
67import eu.siacs.conversations.utils.UIHelper;
68import eu.siacs.conversations.xmpp.XmppConnection;
69import eu.siacs.conversations.xmpp.chatstate.ChatState;
70import eu.siacs.conversations.xmpp.jid.Jid;
71
72public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
73
74 protected Conversation conversation;
75 private OnClickListener leaveMuc = new OnClickListener() {
76
77 @Override
78 public void onClick(View v) {
79 activity.endConversation(conversation);
80 }
81 };
82 private OnClickListener joinMuc = new OnClickListener() {
83
84 @Override
85 public void onClick(View v) {
86 activity.xmppConnectionService.joinMuc(conversation);
87 }
88 };
89 private OnClickListener enterPassword = new OnClickListener() {
90
91 @Override
92 public void onClick(View v) {
93 MucOptions muc = conversation.getMucOptions();
94 String password = muc.getPassword();
95 if (password == null) {
96 password = "";
97 }
98 activity.quickPasswordEdit(password, new OnValueEdited() {
99
100 @Override
101 public void onValueEdited(String value) {
102 activity.xmppConnectionService.providePasswordForMuc(
103 conversation, value);
104 }
105 });
106 }
107 };
108 protected ListView messagesView;
109 final protected List<Message> messageList = new ArrayList<>();
110 protected MessageAdapter messageListAdapter;
111 private EditMessage mEditMessage;
112 private ImageButton mSendButton;
113 private RelativeLayout snackbar;
114 private TextView snackbarMessage;
115 private TextView snackbarAction;
116 private boolean messagesLoaded = true;
117 private Toast messageLoaderToast;
118
119 private OnScrollListener mOnScrollListener = new OnScrollListener() {
120
121 @Override
122 public void onScrollStateChanged(AbsListView view, int scrollState) {
123 // TODO Auto-generated method stub
124
125 }
126
127 @Override
128 public void onScroll(AbsListView view, int firstVisibleItem,
129 int visibleItemCount, int totalItemCount) {
130 synchronized (ConversationFragment.this.messageList) {
131 if (firstVisibleItem < 5 && messagesLoaded && messageList.size() > 0) {
132 long timestamp;
133 if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
134 timestamp = messageList.get(1).getTimeSent();
135 } else {
136 timestamp = messageList.get(0).getTimeSent();
137 }
138 messagesLoaded = false;
139 activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
140 @Override
141 public void onMoreMessagesLoaded(final int c, Conversation conversation) {
142 if (ConversationFragment.this.conversation != conversation) {
143 return;
144 }
145 activity.runOnUiThread(new Runnable() {
146 @Override
147 public void run() {
148 final int oldPosition = messagesView.getFirstVisiblePosition();
149 final Message message;
150 if (oldPosition < messageList.size()) {
151 message = messageList.get(oldPosition);
152 } else {
153 message = null;
154 }
155 String uuid = message != null ? message.getUuid() : null;
156 View v = messagesView.getChildAt(0);
157 final int pxOffset = (v == null) ? 0 : v.getTop();
158 ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
159 try {
160 updateStatusMessages();
161 } catch (IllegalStateException e) {
162 Log.d(Config.LOGTAG,"caught illegal state exception while updating status messages");
163 }
164 messageListAdapter.notifyDataSetChanged();
165 int pos = Math.max(getIndexOf(uuid,messageList),0);
166 messagesView.setSelectionFromTop(pos, pxOffset);
167 messagesLoaded = true;
168 if (messageLoaderToast != null) {
169 messageLoaderToast.cancel();
170 }
171 }
172 });
173 }
174
175 @Override
176 public void informUser(final int resId) {
177
178 activity.runOnUiThread(new Runnable() {
179 @Override
180 public void run() {
181 if (messageLoaderToast != null) {
182 messageLoaderToast.cancel();
183 }
184 if (ConversationFragment.this.conversation != conversation) {
185 return;
186 }
187 messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
188 messageLoaderToast.show();
189 }
190 });
191
192 }
193 });
194
195 }
196 }
197 }
198 };
199
200 private int getIndexOf(String uuid, List<Message> messages) {
201 if (uuid == null) {
202 return messages.size() - 1;
203 }
204 for(int i = 0; i < messages.size(); ++i) {
205 if (uuid.equals(messages.get(i).getUuid())) {
206 return i;
207 } else {
208 Message next = messages.get(i);
209 while(next != null && next.wasMergedIntoPrevious()) {
210 if (uuid.equals(next.getUuid())) {
211 return i;
212 }
213 next = next.next();
214 }
215
216 }
217 }
218 return -1;
219 }
220
221 public Pair<Integer,Integer> getScrollPosition() {
222 if (this.messagesView.getCount() == 0 ||
223 this.messagesView.getLastVisiblePosition() == this.messagesView.getCount() - 1) {
224 return null;
225 } else {
226 final int pos = messagesView.getFirstVisiblePosition();
227 final View view = messagesView.getChildAt(0);
228 if (view == null) {
229 return null;
230 } else {
231 return new Pair<>(pos, view.getTop());
232 }
233 }
234 }
235
236 public void setScrollPosition(Pair<Integer,Integer> scrollPosition) {
237 if (scrollPosition != null) {
238 this.messagesView.setSelectionFromTop(scrollPosition.first, scrollPosition.second);
239 }
240 }
241
242 protected OnClickListener clickToDecryptListener = new OnClickListener() {
243
244 @Override
245 public void onClick(View v) {
246 PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
247 if (pendingIntent != null) {
248 try {
249 activity.startIntentSenderForResult(pendingIntent.getIntentSender(),
250 ConversationActivity.REQUEST_DECRYPT_PGP,
251 null,
252 0,
253 0,
254 0);
255 } catch (SendIntentException e) {
256 Toast.makeText(activity,R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
257 conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
258 }
259 }
260 updateSnackBar(conversation);
261 }
262 };
263 protected OnClickListener clickToVerify = new OnClickListener() {
264
265 @Override
266 public void onClick(View v) {
267 activity.verifyOtrSessionDialog(conversation, v);
268 }
269 };
270 private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
271
272 @Override
273 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
274 if (actionId == EditorInfo.IME_ACTION_SEND) {
275 InputMethodManager imm = (InputMethodManager) v.getContext()
276 .getSystemService(Context.INPUT_METHOD_SERVICE);
277 if (imm.isFullscreenMode()) {
278 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
279 }
280 sendMessage();
281 return true;
282 } else {
283 return false;
284 }
285 }
286 };
287 private OnClickListener mSendButtonListener = new OnClickListener() {
288
289 @Override
290 public void onClick(View v) {
291 Object tag = v.getTag();
292 if (tag instanceof SendButtonAction) {
293 SendButtonAction action = (SendButtonAction) tag;
294 switch (action) {
295 case TAKE_PHOTO:
296 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
297 break;
298 case SEND_LOCATION:
299 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
300 break;
301 case RECORD_VOICE:
302 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
303 break;
304 case CHOOSE_PICTURE:
305 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
306 break;
307 case CANCEL:
308 if (conversation != null) {
309 if (conversation.getCorrectingMessage() != null) {
310 conversation.setCorrectingMessage(null);
311 mEditMessage.getEditableText().clear();
312 }
313 if (conversation.getMode() == Conversation.MODE_MULTI) {
314 conversation.setNextCounterpart(null);
315 }
316 updateChatMsgHint();
317 updateSendButton();
318 }
319 break;
320 default:
321 sendMessage();
322 }
323 } else {
324 sendMessage();
325 }
326 }
327 };
328 private OnClickListener clickToMuc = new OnClickListener() {
329
330 @Override
331 public void onClick(View v) {
332 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
333 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
334 intent.putExtra("uuid", conversation.getUuid());
335 startActivity(intent);
336 }
337 };
338 private ConversationActivity activity;
339 private Message selectedMessage;
340
341 public void setMessagesLoaded() {
342 this.messagesLoaded = true;
343 }
344
345 private void sendMessage() {
346 final String body = mEditMessage.getText().toString();
347 if (body.length() == 0 || this.conversation == null) {
348 return;
349 }
350 final Message message;
351 if (conversation.getCorrectingMessage() == null) {
352 message = new Message(conversation, body, conversation.getNextEncryption());
353 if (conversation.getMode() == Conversation.MODE_MULTI) {
354 if (conversation.getNextCounterpart() != null) {
355 message.setCounterpart(conversation.getNextCounterpart());
356 message.setType(Message.TYPE_PRIVATE);
357 }
358 }
359 } else {
360 message = conversation.getCorrectingMessage();
361 message.setBody(body);
362 message.setEdited(message.getUuid());
363 message.setUuid(UUID.randomUUID().toString());
364 conversation.setCorrectingMessage(null);
365 }
366 switch (conversation.getNextEncryption()) {
367 case Message.ENCRYPTION_OTR:
368 sendOtrMessage(message);
369 break;
370 case Message.ENCRYPTION_PGP:
371 sendPgpMessage(message);
372 break;
373 case Message.ENCRYPTION_AXOLOTL:
374 if(!activity.trustKeysIfNeeded(ConversationActivity.REQUEST_TRUST_KEYS_TEXT)) {
375 sendAxolotlMessage(message);
376 }
377 break;
378 default:
379 sendPlainTextMessage(message);
380 }
381 }
382
383 public void updateChatMsgHint() {
384 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
385 if (conversation.getCorrectingMessage() != null) {
386 this.mEditMessage.setHint(R.string.send_corrected_message);
387 } else if (multi && conversation.getNextCounterpart() != null) {
388 this.mEditMessage.setHint(getString(
389 R.string.send_private_message_to,
390 conversation.getNextCounterpart().getResourcepart()));
391 } else if (multi && !conversation.getMucOptions().participating()) {
392 this.mEditMessage.setHint(R.string.you_are_not_participating);
393 } else {
394 this.mEditMessage.setHint(UIHelper.getMessageHint(activity,conversation));
395 getActivity().invalidateOptionsMenu();
396 }
397 }
398
399 public void setupIme() {
400 if (activity == null) {
401 return;
402 } else if (activity.usingEnterKey() && activity.enterIsSend()) {
403 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_FLAG_MULTI_LINE));
404 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
405 } else if (activity.usingEnterKey()) {
406 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
407 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
408 } else {
409 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
410 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
411 }
412 }
413
414 @Override
415 public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
416 final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
417 view.setOnClickListener(null);
418 mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
419 mEditMessage.setOnClickListener(new OnClickListener() {
420
421 @Override
422 public void onClick(View v) {
423 if (activity != null) {
424 activity.hideConversationsOverview();
425 }
426 }
427 });
428 mEditMessage.setOnEditorActionListener(mEditorActionListener);
429
430 mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
431 mSendButton.setOnClickListener(this.mSendButtonListener);
432
433 snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
434 snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
435 snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
436
437 messagesView = (ListView) view.findViewById(R.id.messages_view);
438 messagesView.setOnScrollListener(mOnScrollListener);
439 messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
440 messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
441 messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
442
443 @Override
444 public void onContactPictureClicked(Message message) {
445 if (message.getStatus() <= Message.STATUS_RECEIVED) {
446 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
447 Jid user = message.getCounterpart();
448 if (user != null && !user.isBareJid()) {
449 if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
450 Toast.makeText(activity,activity.getString(R.string.user_has_left_conference,user.getResourcepart()),Toast.LENGTH_SHORT).show();
451 }
452 highlightInConference(user.getResourcepart());
453 }
454 } else {
455 if (!message.getContact().isSelf()) {
456 String fingerprint;
457 if (message.getEncryption() == Message.ENCRYPTION_PGP
458 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
459 fingerprint = "pgp";
460 } else {
461 fingerprint = message.getFingerprint();
462 }
463 activity.switchToContactDetails(message.getContact(), fingerprint);
464 }
465 }
466 } else {
467 Account account = message.getConversation().getAccount();
468 Intent intent;
469 if (activity.manuallyChangePresence()) {
470 intent = new Intent(activity, SetPresenceActivity.class);
471 intent.putExtra(SetPresenceActivity.EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
472 } else {
473 intent = new Intent(activity, EditAccountActivity.class);
474 intent.putExtra("jid", account.getJid().toBareJid().toString());
475 String fingerprint;
476 if (message.getEncryption() == Message.ENCRYPTION_PGP
477 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
478 fingerprint = "pgp";
479 } else {
480 fingerprint = message.getFingerprint();
481 }
482 intent.putExtra("fingerprint", fingerprint);
483 }
484 startActivity(intent);
485 }
486 }
487 });
488 messageListAdapter
489 .setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
490
491 @Override
492 public void onContactPictureLongClicked(Message message) {
493 if (message.getStatus() <= Message.STATUS_RECEIVED) {
494 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
495 Jid user = message.getCounterpart();
496 if (user != null && !user.isBareJid()) {
497 if (message.getConversation().getMucOptions().isUserInRoom(user)) {
498 privateMessageWith(user);
499 } else {
500 Toast.makeText(activity, activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
501 }
502 }
503 }
504 } else {
505 activity.showQrCode();
506 }
507 }
508 });
509 messagesView.setAdapter(messageListAdapter);
510
511 registerForContextMenu(messagesView);
512
513 return view;
514 }
515
516 @Override
517 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
518 synchronized (this.messageList) {
519 super.onCreateContextMenu(menu, v, menuInfo);
520 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
521 this.selectedMessage = this.messageList.get(acmi.position);
522 populateContextMenu(menu);
523 }
524 }
525
526 private void populateContextMenu(ContextMenu menu) {
527 final Message m = this.selectedMessage;
528 final Transferable t = m.getTransferable();
529 Message relevantForCorrection = m;
530 while(relevantForCorrection.mergeable(relevantForCorrection.next())) {
531 relevantForCorrection = relevantForCorrection.next();
532 }
533 if (m.getType() != Message.TYPE_STATUS) {
534 final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
535 && m.getType() != Message.TYPE_PRIVATE
536 && t == null;
537 activity.getMenuInflater().inflate(R.menu.message_context, menu);
538 menu.setHeaderTitle(R.string.message_options);
539 MenuItem copyText = menu.findItem(R.id.copy_text);
540 MenuItem selectText = menu.findItem(R.id.select_text);
541 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
542 MenuItem correctMessage = menu.findItem(R.id.correct_message);
543 MenuItem shareWith = menu.findItem(R.id.share_with);
544 MenuItem sendAgain = menu.findItem(R.id.send_again);
545 MenuItem copyUrl = menu.findItem(R.id.copy_url);
546 MenuItem downloadFile = menu.findItem(R.id.download_file);
547 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
548 MenuItem deleteFile = menu.findItem(R.id.delete_file);
549 if (!treatAsFile
550 && !GeoHelper.isGeoUri(m.getBody())
551 && m.treatAsDownloadable() != Message.Decision.MUST) {
552 copyText.setVisible(true);
553 selectText.setVisible(ListSelectionManager.isSupported());
554 }
555 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
556 retryDecryption.setVisible(true);
557 }
558 if (relevantForCorrection.getType() == Message.TYPE_TEXT
559 && relevantForCorrection.isLastCorrectableMessage()) {
560 correctMessage.setVisible(true);
561 }
562 if (treatAsFile || (GeoHelper.isGeoUri(m.getBody()))) {
563 shareWith.setVisible(true);
564 }
565 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
566 sendAgain.setVisible(true);
567 }
568 if (m.hasFileOnRemoteHost()
569 || GeoHelper.isGeoUri(m.getBody())
570 || m.treatAsDownloadable() == Message.Decision.MUST
571 || (t != null && t instanceof HttpDownloadConnection)) {
572 copyUrl.setVisible(true);
573 }
574 if ((m.getType() == Message.TYPE_TEXT && t == null && m.treatAsDownloadable() != Message.Decision.NEVER)
575 || (m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())){
576 downloadFile.setVisible(true);
577 downloadFile.setTitle(activity.getString(R.string.download_x_file,UIHelper.getFileDescriptionString(activity, m)));
578 }
579 boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
580 || m.getStatus() == Message.STATUS_UNSEND
581 || m.getStatus() == Message.STATUS_OFFERED;
582 if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
583 cancelTransmission.setVisible(true);
584 }
585 if (treatAsFile) {
586 String path = m.getRelativeFilePath();
587 if (path == null || !path.startsWith("/")) {
588 deleteFile.setVisible(true);
589 deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
590 }
591 }
592 }
593 }
594
595 @Override
596 public boolean onContextItemSelected(MenuItem item) {
597 switch (item.getItemId()) {
598 case R.id.share_with:
599 shareWith(selectedMessage);
600 return true;
601 case R.id.copy_text:
602 copyText(selectedMessage);
603 return true;
604 case R.id.select_text:
605 selectText(selectedMessage);
606 return true;
607 case R.id.correct_message:
608 correctMessage(selectedMessage);
609 return true;
610 case R.id.send_again:
611 resendMessage(selectedMessage);
612 return true;
613 case R.id.copy_url:
614 copyUrl(selectedMessage);
615 return true;
616 case R.id.download_file:
617 downloadFile(selectedMessage);
618 return true;
619 case R.id.cancel_transmission:
620 cancelTransmission(selectedMessage);
621 return true;
622 case R.id.retry_decryption:
623 retryDecryption(selectedMessage);
624 return true;
625 case R.id.delete_file:
626 deleteFile(selectedMessage);
627 return true;
628 default:
629 return super.onContextItemSelected(item);
630 }
631 }
632
633 private void shareWith(Message message) {
634 Intent shareIntent = new Intent();
635 shareIntent.setAction(Intent.ACTION_SEND);
636 if (GeoHelper.isGeoUri(message.getBody())) {
637 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
638 shareIntent.setType("text/plain");
639 } else {
640 shareIntent.putExtra(Intent.EXTRA_STREAM,
641 activity.xmppConnectionService.getFileBackend()
642 .getJingleFileUri(message));
643 shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
644 String mime = message.getMimeType();
645 if (mime == null) {
646 mime = "*/*";
647 }
648 shareIntent.setType(mime);
649 }
650 try {
651 activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
652 } catch (ActivityNotFoundException e) {
653 //This should happen only on faulty androids because normally chooser is always available
654 Toast.makeText(activity,R.string.no_application_found_to_open_file,Toast.LENGTH_SHORT).show();
655 }
656 }
657
658 private void copyText(Message message) {
659 if (activity.copyTextToClipboard(message.getMergedBody().toString(),
660 R.string.message_text)) {
661 Toast.makeText(activity, R.string.message_copied_to_clipboard,
662 Toast.LENGTH_SHORT).show();
663 }
664 }
665
666 private void selectText(Message message) {
667 final int index;
668 synchronized (this.messageList) {
669 index = this.messageList.indexOf(message);
670 }
671 if (index >= 0) {
672 final int first = this.messagesView.getFirstVisiblePosition();
673 final int last = first + this.messagesView.getChildCount();
674 if (index >= first && index < last) {
675 final View view = this.messagesView.getChildAt(index - first);
676 final TextView messageBody = this.messageListAdapter.getMessageBody(view);
677 if (messageBody != null) {
678 ListSelectionManager.startSelection(messageBody);
679 }
680 }
681 }
682 }
683
684 private void deleteFile(Message message) {
685 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
686 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
687 activity.updateConversationList();
688 updateMessages();
689 }
690 }
691
692 private void resendMessage(Message message) {
693 if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
694 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
695 if (!file.exists()) {
696 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
697 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
698 activity.updateConversationList();
699 updateMessages();
700 return;
701 }
702 }
703 activity.xmppConnectionService.resendFailedMessages(message);
704 }
705
706 private void copyUrl(Message message) {
707 final String url;
708 final int resId;
709 if (GeoHelper.isGeoUri(message.getBody())) {
710 resId = R.string.location;
711 url = message.getBody();
712 } else if (message.hasFileOnRemoteHost()) {
713 resId = R.string.file_url;
714 url = message.getFileParams().url.toString();
715 } else {
716 url = message.getBody().trim();
717 resId = R.string.file_url;
718 }
719 if (activity.copyTextToClipboard(url, resId)) {
720 Toast.makeText(activity, R.string.url_copied_to_clipboard,
721 Toast.LENGTH_SHORT).show();
722 }
723 }
724
725 private void downloadFile(Message message) {
726 activity.xmppConnectionService.getHttpConnectionManager()
727 .createNewDownloadConnection(message,true);
728 }
729
730 private void cancelTransmission(Message message) {
731 Transferable transferable = message.getTransferable();
732 if (transferable != null) {
733 transferable.cancel();
734 } else {
735 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
736 }
737 }
738
739 private void retryDecryption(Message message) {
740 message.setEncryption(Message.ENCRYPTION_PGP);
741 activity.updateConversationList();
742 updateMessages();
743 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
744 }
745
746 protected void privateMessageWith(final Jid counterpart) {
747 this.mEditMessage.setText("");
748 this.conversation.setNextCounterpart(counterpart);
749 updateChatMsgHint();
750 updateSendButton();
751 }
752
753 private void correctMessage(Message message) {
754 while(message.mergeable(message.next())) {
755 message = message.next();
756 }
757 this.conversation.setCorrectingMessage(message);
758 this.mEditMessage.getEditableText().clear();
759 this.mEditMessage.getEditableText().append(message.getBody());
760
761 }
762
763 protected void highlightInConference(String nick) {
764 String oldString = mEditMessage.getText().toString().trim();
765 if (oldString.isEmpty() || mEditMessage.getSelectionStart() == 0) {
766 mEditMessage.getText().insert(0, nick + ": ");
767 } else {
768 if (mEditMessage.getText().charAt(
769 mEditMessage.getSelectionStart() - 1) != ' ') {
770 nick = " " + nick;
771 }
772 mEditMessage.getText().insert(mEditMessage.getSelectionStart(),
773 nick + " ");
774 }
775 }
776
777 @Override
778 public void onStop() {
779 super.onStop();
780 if (this.conversation != null) {
781 final String msg = mEditMessage.getText().toString();
782 this.conversation.setNextMessage(msg);
783 updateChatState(this.conversation, msg);
784 }
785 }
786
787 private void updateChatState(final Conversation conversation, final String msg) {
788 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
789 Account.State status = conversation.getAccount().getStatus();
790 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
791 activity.xmppConnectionService.sendChatState(conversation);
792 }
793 }
794
795 public boolean reInit(Conversation conversation) {
796 if (conversation == null) {
797 return false;
798 }
799 this.activity = (ConversationActivity) getActivity();
800 setupIme();
801 if (this.conversation != null) {
802 final String msg = mEditMessage.getText().toString();
803 this.conversation.setNextMessage(msg);
804 if (this.conversation != conversation) {
805 updateChatState(this.conversation, msg);
806 }
807 this.conversation.trim();
808 }
809
810 this.conversation = conversation;
811 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating();
812 this.mEditMessage.setEnabled(canWrite);
813 this.mSendButton.setEnabled(canWrite);
814 this.mEditMessage.setKeyboardListener(null);
815 this.mEditMessage.setText("");
816 this.mEditMessage.append(this.conversation.getNextMessage());
817 this.mEditMessage.setKeyboardListener(this);
818 messageListAdapter.updatePreferences();
819 this.messagesView.setAdapter(messageListAdapter);
820 updateMessages();
821 this.messagesLoaded = true;
822 synchronized (this.messageList) {
823 final Message first = conversation.getFirstUnreadMessage();
824 final int bottom = Math.max(0, this.messageList.size() - 1);
825 final int pos;
826 if (first == null) {
827 pos = bottom;
828 } else {
829 int i = getIndexOf(first.getUuid(), this.messageList);
830 pos = i < 0 ? bottom : i;
831 }
832 messagesView.setSelection(pos);
833 return pos == bottom;
834 }
835 }
836
837 private OnClickListener mEnableAccountListener = new OnClickListener() {
838 @Override
839 public void onClick(View v) {
840 final Account account = conversation == null ? null : conversation.getAccount();
841 if (account != null) {
842 account.setOption(Account.OPTION_DISABLED, false);
843 activity.xmppConnectionService.updateAccount(account);
844 }
845 }
846 };
847
848 private OnClickListener mUnblockClickListener = new OnClickListener() {
849 @Override
850 public void onClick(final View v) {
851 v.post(new Runnable() {
852 @Override
853 public void run() {
854 v.setVisibility(View.INVISIBLE);
855 }
856 });
857 if (conversation.isDomainBlocked()) {
858 BlockContactDialog.show(activity, activity.xmppConnectionService, conversation);
859 } else {
860 activity.unblockConversation(conversation);
861 }
862 }
863 };
864
865 private OnClickListener mAddBackClickListener = new OnClickListener() {
866
867 @Override
868 public void onClick(View v) {
869 final Contact contact = conversation == null ? null : conversation.getContact();
870 if (contact != null) {
871 activity.xmppConnectionService.createContact(contact);
872 activity.switchToContactDetails(contact);
873 }
874 }
875 };
876
877 private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
878 @Override
879 public void onClick(View v) {
880 final Contact contact = conversation == null ? null : conversation.getContact();
881 if (contact != null) {
882 activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
883 activity.xmppConnectionService.getPresenceGenerator()
884 .sendPresenceUpdatesTo(contact));
885 hideSnackbar();
886 }
887 }
888 };
889
890 private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
891 @Override
892 public void onClick(View view) {
893 Intent intent = new Intent(activity, VerifyOTRActivity.class);
894 intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
895 intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
896 intent.putExtra(VerifyOTRActivity.EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
897 intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
898 startActivity(intent);
899 }
900 };
901
902 private void updateSnackBar(final Conversation conversation) {
903 final Account account = conversation.getAccount();
904 final Contact contact = conversation.getContact();
905 final int mode = conversation.getMode();
906 if (account.getStatus() == Account.State.DISABLED) {
907 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
908 } else if (conversation.isBlocked()) {
909 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
910 } else if (!contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
911 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
912 } else if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
913 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription);
914 } else if (mode == Conversation.MODE_MULTI
915 && !conversation.getMucOptions().online()
916 && account.getStatus() == Account.State.ONLINE) {
917 switch (conversation.getMucOptions().getError()) {
918 case NICK_IN_USE:
919 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
920 break;
921 case NO_RESPONSE:
922 showSnackbar(R.string.joining_conference, 0, null);
923 break;
924 case SERVER_NOT_FOUND:
925 showSnackbar(R.string.remote_server_not_found,R.string.leave, leaveMuc);
926 break;
927 case PASSWORD_REQUIRED:
928 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
929 break;
930 case BANNED:
931 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
932 break;
933 case MEMBERS_ONLY:
934 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
935 break;
936 case KICKED:
937 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
938 break;
939 case UNKNOWN:
940 showSnackbar(R.string.conference_unknown_error, R.string.join, joinMuc);
941 break;
942 case SHUTDOWN:
943 showSnackbar(R.string.conference_shutdown, R.string.join, joinMuc);
944 break;
945 default:
946 break;
947 }
948 } else if (account.hasPendingPgpIntent(conversation)) {
949 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
950 } else if (mode == Conversation.MODE_SINGLE
951 && conversation.smpRequested()) {
952 showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
953 } else if (mode == Conversation.MODE_SINGLE
954 && conversation.hasValidOtrSession()
955 && (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
956 && (!conversation.isOtrFingerprintVerified())) {
957 showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
958 } else {
959 hideSnackbar();
960 }
961 }
962
963 public void updateMessages() {
964 synchronized (this.messageList) {
965 if (getView() == null) {
966 return;
967 }
968 final ConversationActivity activity = (ConversationActivity) getActivity();
969 if (this.conversation != null) {
970 conversation.populateWithMessages(ConversationFragment.this.messageList);
971 updateSnackBar(conversation);
972 updateStatusMessages();
973 this.messageListAdapter.notifyDataSetChanged();
974 updateChatMsgHint();
975 if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
976 activity.sendReadMarkerIfNecessary(conversation);
977 }
978 this.updateSendButton();
979 }
980 }
981 }
982
983 protected void messageSent() {
984 mEditMessage.setText("");
985 updateChatMsgHint();
986 new Handler().post(new Runnable() {
987 @Override
988 public void run() {
989 int size = messageList.size();
990 messagesView.setSelection(size - 1);
991 }
992 });
993 }
994
995 public void setFocusOnInputField() {
996 mEditMessage.requestFocus();
997 }
998
999 enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
1000
1001 private int getSendButtonImageResource(SendButtonAction action, Presence.Status status) {
1002 switch (action) {
1003 case TEXT:
1004 switch (status) {
1005 case CHAT:
1006 case ONLINE:
1007 return R.drawable.ic_send_text_online;
1008 case AWAY:
1009 return R.drawable.ic_send_text_away;
1010 case XA:
1011 case DND:
1012 return R.drawable.ic_send_text_dnd;
1013 default:
1014 return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1015 }
1016 case TAKE_PHOTO:
1017 switch (status) {
1018 case CHAT:
1019 case ONLINE:
1020 return R.drawable.ic_send_photo_online;
1021 case AWAY:
1022 return R.drawable.ic_send_photo_away;
1023 case XA:
1024 case DND:
1025 return R.drawable.ic_send_photo_dnd;
1026 default:
1027 return activity.getThemeResource(R.attr.ic_send_photo_offline, R.drawable.ic_send_photo_offline);
1028 }
1029 case RECORD_VOICE:
1030 switch (status) {
1031 case CHAT:
1032 case ONLINE:
1033 return R.drawable.ic_send_voice_online;
1034 case AWAY:
1035 return R.drawable.ic_send_voice_away;
1036 case XA:
1037 case DND:
1038 return R.drawable.ic_send_voice_dnd;
1039 default:
1040 return activity.getThemeResource(R.attr.ic_send_voice_offline, R.drawable.ic_send_voice_offline);
1041 }
1042 case SEND_LOCATION:
1043 switch (status) {
1044 case CHAT:
1045 case ONLINE:
1046 return R.drawable.ic_send_location_online;
1047 case AWAY:
1048 return R.drawable.ic_send_location_away;
1049 case XA:
1050 case DND:
1051 return R.drawable.ic_send_location_dnd;
1052 default:
1053 return activity.getThemeResource(R.attr.ic_send_location_offline, R.drawable.ic_send_location_offline);
1054 }
1055 case CANCEL:
1056 switch (status) {
1057 case CHAT:
1058 case ONLINE:
1059 return R.drawable.ic_send_cancel_online;
1060 case AWAY:
1061 return R.drawable.ic_send_cancel_away;
1062 case XA:
1063 case DND:
1064 return R.drawable.ic_send_cancel_dnd;
1065 default:
1066 return activity.getThemeResource(R.attr.ic_send_cancel_offline, R.drawable.ic_send_cancel_offline);
1067 }
1068 case CHOOSE_PICTURE:
1069 switch (status) {
1070 case CHAT:
1071 case ONLINE:
1072 return R.drawable.ic_send_picture_online;
1073 case AWAY:
1074 return R.drawable.ic_send_picture_away;
1075 case XA:
1076 case DND:
1077 return R.drawable.ic_send_picture_dnd;
1078 default:
1079 return activity.getThemeResource(R.attr.ic_send_picture_offline, R.drawable.ic_send_picture_offline);
1080 }
1081 }
1082 return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1083 }
1084
1085 public void updateSendButton() {
1086 final Conversation c = this.conversation;
1087 final SendButtonAction action;
1088 final Presence.Status status;
1089 final String text = this.mEditMessage == null ? "" : this.mEditMessage.getText().toString();
1090 final boolean empty = text.length() == 0;
1091 final boolean conference = c.getMode() == Conversation.MODE_MULTI;
1092 if (c.getCorrectingMessage() != null && (empty || text.equals(c.getCorrectingMessage().getBody()))) {
1093 action = SendButtonAction.CANCEL;
1094 } else if (conference && !c.getAccount().httpUploadAvailable()) {
1095 if (empty && c.getNextCounterpart() != null) {
1096 action = SendButtonAction.CANCEL;
1097 } else {
1098 action = SendButtonAction.TEXT;
1099 }
1100 } else {
1101 if (empty) {
1102 if (conference && c.getNextCounterpart() != null) {
1103 action = SendButtonAction.CANCEL;
1104 } else {
1105 String setting = activity.getPreferences().getString("quick_action", "recent");
1106 if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
1107 setting = "location";
1108 } else if (setting.equals("recent")) {
1109 setting = activity.getPreferences().getString("recently_used_quick_action", "text");
1110 }
1111 switch (setting) {
1112 case "photo":
1113 action = SendButtonAction.TAKE_PHOTO;
1114 break;
1115 case "location":
1116 action = SendButtonAction.SEND_LOCATION;
1117 break;
1118 case "voice":
1119 action = SendButtonAction.RECORD_VOICE;
1120 break;
1121 case "picture":
1122 action = SendButtonAction.CHOOSE_PICTURE;
1123 break;
1124 default:
1125 action = SendButtonAction.TEXT;
1126 break;
1127 }
1128 }
1129 } else {
1130 action = SendButtonAction.TEXT;
1131 }
1132 }
1133 if (activity.useSendButtonToIndicateStatus() && c != null
1134 && c.getAccount().getStatus() == Account.State.ONLINE) {
1135 if (c.getMode() == Conversation.MODE_SINGLE) {
1136 status = c.getContact().getShownStatus();
1137 } else {
1138 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1139 }
1140 } else {
1141 status = Presence.Status.OFFLINE;
1142 }
1143 this.mSendButton.setTag(action);
1144 this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
1145 }
1146
1147 protected void updateStatusMessages() {
1148 synchronized (this.messageList) {
1149 if (showLoadMoreMessages(conversation)) {
1150 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1151 }
1152 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1153 ChatState state = conversation.getIncomingChatState();
1154 if (state == ChatState.COMPOSING) {
1155 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1156 } else if (state == ChatState.PAUSED) {
1157 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1158 } else {
1159 for (int i = this.messageList.size() - 1; i >= 0; --i) {
1160 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1161 return;
1162 } else {
1163 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1164 this.messageList.add(i + 1,
1165 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1166 return;
1167 }
1168 }
1169 }
1170 }
1171 }
1172 }
1173 }
1174
1175 private boolean showLoadMoreMessages(final Conversation c) {
1176 final boolean mam = hasMamSupport(c);
1177 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1178 return mam && (c.getLastClearHistory() != 0 || (c.countMessages() == 0 && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
1179 }
1180
1181 private boolean hasMamSupport(final Conversation c) {
1182 if (c.getMode() == Conversation.MODE_SINGLE) {
1183 final XmppConnection connection = c.getAccount().getXmppConnection();
1184 return connection != null && connection.getFeatures().mam();
1185 } else {
1186 return c.getMucOptions().mamSupport();
1187 }
1188 }
1189
1190 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
1191 snackbar.setVisibility(View.VISIBLE);
1192 snackbar.setOnClickListener(null);
1193 snackbarMessage.setText(message);
1194 snackbarMessage.setOnClickListener(null);
1195 snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
1196 if (action != 0) {
1197 snackbarAction.setText(action);
1198 }
1199 snackbarAction.setOnClickListener(clickListener);
1200 }
1201
1202 protected void hideSnackbar() {
1203 snackbar.setVisibility(View.GONE);
1204 }
1205
1206 protected void sendPlainTextMessage(Message message) {
1207 ConversationActivity activity = (ConversationActivity) getActivity();
1208 activity.xmppConnectionService.sendMessage(message);
1209 messageSent();
1210 }
1211
1212 protected void sendPgpMessage(final Message message) {
1213 final ConversationActivity activity = (ConversationActivity) getActivity();
1214 final XmppConnectionService xmppService = activity.xmppConnectionService;
1215 final Contact contact = message.getConversation().getContact();
1216 if (!activity.hasPgp()) {
1217 activity.showInstallPgpDialog();
1218 return;
1219 }
1220 if (conversation.getAccount().getPgpSignature() == null) {
1221 activity.announcePgp(conversation.getAccount(), conversation, activity.onOpenPGPKeyPublished);
1222 return;
1223 }
1224 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1225 if (contact.getPgpKeyId() != 0) {
1226 xmppService.getPgpEngine().hasKey(contact,
1227 new UiCallback<Contact>() {
1228
1229 @Override
1230 public void userInputRequried(PendingIntent pi,
1231 Contact contact) {
1232 activity.runIntent(
1233 pi,
1234 ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1235 }
1236
1237 @Override
1238 public void success(Contact contact) {
1239 activity.encryptTextMessage(message);
1240 }
1241
1242 @Override
1243 public void error(int error, Contact contact) {
1244 activity.runOnUiThread(new Runnable() {
1245 @Override
1246 public void run() {
1247 Toast.makeText(activity,
1248 R.string.unable_to_connect_to_keychain,
1249 Toast.LENGTH_SHORT
1250 ).show();
1251 }
1252 });
1253 }
1254 });
1255
1256 } else {
1257 showNoPGPKeyDialog(false,
1258 new DialogInterface.OnClickListener() {
1259
1260 @Override
1261 public void onClick(DialogInterface dialog,
1262 int which) {
1263 conversation
1264 .setNextEncryption(Message.ENCRYPTION_NONE);
1265 xmppService.updateConversation(conversation);
1266 message.setEncryption(Message.ENCRYPTION_NONE);
1267 xmppService.sendMessage(message);
1268 messageSent();
1269 }
1270 });
1271 }
1272 } else {
1273 if (conversation.getMucOptions().pgpKeysInUse()) {
1274 if (!conversation.getMucOptions().everybodyHasKeys()) {
1275 Toast warning = Toast
1276 .makeText(getActivity(),
1277 R.string.missing_public_keys,
1278 Toast.LENGTH_LONG);
1279 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1280 warning.show();
1281 }
1282 activity.encryptTextMessage(message);
1283 } else {
1284 showNoPGPKeyDialog(true,
1285 new DialogInterface.OnClickListener() {
1286
1287 @Override
1288 public void onClick(DialogInterface dialog,
1289 int which) {
1290 conversation
1291 .setNextEncryption(Message.ENCRYPTION_NONE);
1292 message.setEncryption(Message.ENCRYPTION_NONE);
1293 xmppService.updateConversation(conversation);
1294 xmppService.sendMessage(message);
1295 messageSent();
1296 }
1297 });
1298 }
1299 }
1300 }
1301
1302 public void showNoPGPKeyDialog(boolean plural,
1303 DialogInterface.OnClickListener listener) {
1304 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1305 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1306 if (plural) {
1307 builder.setTitle(getString(R.string.no_pgp_keys));
1308 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1309 } else {
1310 builder.setTitle(getString(R.string.no_pgp_key));
1311 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1312 }
1313 builder.setNegativeButton(getString(R.string.cancel), null);
1314 builder.setPositiveButton(getString(R.string.send_unencrypted),
1315 listener);
1316 builder.create().show();
1317 }
1318
1319 protected void sendAxolotlMessage(final Message message) {
1320 final ConversationActivity activity = (ConversationActivity) getActivity();
1321 final XmppConnectionService xmppService = activity.xmppConnectionService;
1322 xmppService.sendMessage(message);
1323 messageSent();
1324 }
1325
1326 protected void sendOtrMessage(final Message message) {
1327 final ConversationActivity activity = (ConversationActivity) getActivity();
1328 final XmppConnectionService xmppService = activity.xmppConnectionService;
1329 activity.selectPresence(message.getConversation(),
1330 new OnPresenceSelected() {
1331
1332 @Override
1333 public void onPresenceSelected() {
1334 message.setCounterpart(conversation.getNextCounterpart());
1335 xmppService.sendMessage(message);
1336 messageSent();
1337 }
1338 });
1339 }
1340
1341 public void appendText(String text) {
1342 if (text == null) {
1343 return;
1344 }
1345 String previous = this.mEditMessage.getText().toString();
1346 if (previous.length() != 0 && !previous.endsWith(" ")) {
1347 text = " " + text;
1348 }
1349 this.mEditMessage.append(text);
1350 }
1351
1352 @Override
1353 public boolean onEnterPressed() {
1354 if (activity.enterIsSend()) {
1355 sendMessage();
1356 return true;
1357 } else {
1358 return false;
1359 }
1360 }
1361
1362 @Override
1363 public void onTypingStarted() {
1364 Account.State status = conversation.getAccount().getStatus();
1365 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1366 activity.xmppConnectionService.sendChatState(conversation);
1367 }
1368 activity.hideConversationsOverview();
1369 updateSendButton();
1370 }
1371
1372 @Override
1373 public void onTypingStopped() {
1374 Account.State status = conversation.getAccount().getStatus();
1375 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1376 activity.xmppConnectionService.sendChatState(conversation);
1377 }
1378 }
1379
1380 @Override
1381 public void onTextDeleted() {
1382 Account.State status = conversation.getAccount().getStatus();
1383 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1384 activity.xmppConnectionService.sendChatState(conversation);
1385 }
1386 updateSendButton();
1387 }
1388
1389 @Override
1390 public void onTextChanged() {
1391 if (conversation != null && conversation.getCorrectingMessage() != null) {
1392 updateSendButton();
1393 }
1394 }
1395
1396 private int completionIndex = 0;
1397 private int lastCompletionLength = 0;
1398 private String incomplete;
1399 private int lastCompletionCursor;
1400 private boolean firstWord = false;
1401
1402 @Override
1403 public boolean onTabPressed(boolean repeated) {
1404 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
1405 return false;
1406 }
1407 if (repeated) {
1408 completionIndex++;
1409 } else {
1410 lastCompletionLength = 0;
1411 completionIndex = 0;
1412 final String content = mEditMessage.getText().toString();
1413 lastCompletionCursor = mEditMessage.getSelectionEnd();
1414 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ",lastCompletionCursor-1) + 1 : 0;
1415 firstWord = start == 0;
1416 incomplete = content.substring(start,lastCompletionCursor);
1417 }
1418 List<String> completions = new ArrayList<>();
1419 for(MucOptions.User user : conversation.getMucOptions().getUsers()) {
1420 String name = user.getName();
1421 if (name != null && name.startsWith(incomplete)) {
1422 completions.add(name+(firstWord ? ": " : " "));
1423 }
1424 }
1425 Collections.sort(completions);
1426 if (completions.size() > completionIndex) {
1427 String completion = completions.get(completionIndex).substring(incomplete.length());
1428 mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1429 mEditMessage.getEditableText().insert(lastCompletionCursor, completion);
1430 lastCompletionLength = completion.length();
1431 } else {
1432 completionIndex = -1;
1433 mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1434 lastCompletionLength = 0;
1435 }
1436 return true;
1437 }
1438
1439 @Override
1440 public void onActivityResult(int requestCode, int resultCode,
1441 final Intent data) {
1442 if (resultCode == Activity.RESULT_OK) {
1443 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1444 activity.getSelectedConversation().getAccount().getPgpDecryptionService().continueDecryption(true);
1445 } else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_TEXT) {
1446 final String body = mEditMessage.getText().toString();
1447 Message message = new Message(conversation, body, conversation.getNextEncryption());
1448 sendAxolotlMessage(message);
1449 } else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_MENU) {
1450 int choice = data.getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID);
1451 activity.selectPresenceToAttachFile(choice, conversation.getNextEncryption());
1452 }
1453 }
1454 }
1455
1456}