1package eu.siacs.conversations.ui;
2
3import android.content.Context;
4import android.os.Handler;
5import android.util.AttributeSet;
6import android.view.KeyEvent;
7import android.widget.EditText;
8
9import eu.siacs.conversations.Config;
10
11public class EditMessage extends EditText {
12
13 public EditMessage(Context context, AttributeSet attrs) {
14 super(context, attrs);
15 }
16
17 public EditMessage(Context context) {
18 super(context);
19 }
20
21 protected Handler mTypingHandler = new Handler();
22
23 protected Runnable mTypingTimeout = new Runnable() {
24 @Override
25 public void run() {
26 if (isUserTyping && keyboardListener != null) {
27 keyboardListener.onTypingStopped();
28 isUserTyping = false;
29 }
30 }
31 };
32
33 private boolean isUserTyping = false;
34
35 private boolean lastInputWasTab = false;
36
37 protected KeyboardListener keyboardListener;
38
39 @Override
40 public boolean onKeyDown(int keyCode, KeyEvent e) {
41 if (keyCode == KeyEvent.KEYCODE_ENTER && !e.isShiftPressed()) {
42 lastInputWasTab = false;
43 if (keyboardListener != null && keyboardListener.onEnterPressed()) {
44 return true;
45 }
46 } else if (keyCode == KeyEvent.KEYCODE_TAB && !e.isAltPressed() && !e.isCtrlPressed()) {
47 if (keyboardListener != null && keyboardListener.onTabPressed(this.lastInputWasTab)) {
48 lastInputWasTab = true;
49 return true;
50 }
51 } else {
52 lastInputWasTab = false;
53 }
54 return super.onKeyDown(keyCode, e);
55 }
56
57 @Override
58 public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
59 super.onTextChanged(text,start,lengthBefore,lengthAfter);
60 lastInputWasTab = false;
61 if (this.mTypingHandler != null && this.keyboardListener != null) {
62 this.mTypingHandler.removeCallbacks(mTypingTimeout);
63 this.mTypingHandler.postDelayed(mTypingTimeout, Config.TYPING_TIMEOUT * 1000);
64 final int length = text.length();
65 if (!isUserTyping && length > 0) {
66 this.isUserTyping = true;
67 this.keyboardListener.onTypingStarted();
68 } else if (length == 0) {
69 this.isUserTyping = false;
70 this.keyboardListener.onTextDeleted();
71 }
72 this.keyboardListener.onTextChanged();
73 }
74 }
75
76 public void setKeyboardListener(KeyboardListener listener) {
77 this.keyboardListener = listener;
78 if (listener != null) {
79 this.isUserTyping = false;
80 }
81 }
82
83 public interface KeyboardListener {
84 boolean onEnterPressed();
85 void onTypingStarted();
86 void onTypingStopped();
87 void onTextDeleted();
88 void onTextChanged();
89 boolean onTabPressed(boolean repeated);
90 }
91
92}