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