1package eu.siacs.conversations.ui.widget;
2
3import android.content.ClipData;
4import android.content.ClipboardManager;
5import android.content.Context;
6import android.support.v7.widget.AppCompatTextView;
7import android.util.AttributeSet;
8
9public class CopyTextView extends AppCompatTextView {
10
11 public CopyTextView(Context context) {
12 super(context);
13 }
14
15 public CopyTextView(Context context, AttributeSet attrs) {
16 super(context, attrs);
17 }
18
19 public CopyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
20 super(context, attrs, defStyleAttr);
21 }
22
23 public interface CopyHandler {
24 String transformTextForCopy(CharSequence text, int start, int end);
25 }
26
27 private CopyHandler copyHandler;
28
29 public void setCopyHandler(CopyHandler copyHandler) {
30 this.copyHandler = copyHandler;
31 }
32
33 @Override
34 public boolean onTextContextMenuItem(int id) {
35 final CharSequence text = getText();
36 int min = 0;
37 int max = text.length();
38 if (isFocused()) {
39 final int selStart = getSelectionStart();
40 final int selEnd = getSelectionEnd();
41 min = Math.max(0, Math.min(selStart, selEnd));
42 max = Math.max(0, Math.max(selStart, selEnd));
43 }
44 String textForCopy = null;
45 if (id == android.R.id.copy && copyHandler != null) {
46 textForCopy = copyHandler.transformTextForCopy(getText(), min, max);
47 }
48 try {
49 return super.onTextContextMenuItem(id);
50 } finally {
51 if (textForCopy != null) {
52 ClipboardManager clipboard = (ClipboardManager) getContext().
53 getSystemService(Context.CLIPBOARD_SERVICE);
54 clipboard.setPrimaryClip(ClipData.newPlainText(null, textForCopy));
55 }
56 }
57 }
58}