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