@Override
public boolean keyPressed(Component component, int keyCode, Keyboard.KeyLocation keyLocation) {
boolean consumed = false;
TextArea textArea = (TextArea)getComponent();
if (textArea.isEditable()) {
Document document = textArea.getDocument();
if (document != null) {
if (keyCode == Keyboard.KeyCode.ENTER) {
textArea.insertParagraph();
caretX = 0;
} else if (keyCode == Keyboard.KeyCode.DELETE) {
textArea.delete(Direction.FORWARD);
} else if (keyCode == Keyboard.KeyCode.BACKSPACE) {
textArea.delete(Direction.BACKWARD);
} else if (keyCode == Keyboard.KeyCode.LEFT) {
int selectionStart = textArea.getSelectionStart();
int selectionLength = textArea.getSelectionLength();
if (Keyboard.isPressed(Keyboard.Modifier.SHIFT)) {
// Add the previous character to the selection
if (selectionStart > 0) {
selectionStart--;
selectionLength++;
}
} else {
// Clear the selection and move the caret back by one
// character
if (selectionLength == 0
&& selectionStart > 0) {
selectionStart--;
}
selectionLength = 0;
}
textArea.setSelection(selectionStart, selectionLength);
caretX = caret.x;
consumed = true;
} else if (keyCode == Keyboard.KeyCode.RIGHT) {
int selectionStart = textArea.getSelectionStart();
int selectionLength = textArea.getSelectionLength();
if (Keyboard.isPressed(Keyboard.Modifier.SHIFT)) {
// Add the next character to the selection
if (selectionStart + selectionLength < document.getCharacterCount()) {
selectionLength++;
}
} else {
// Clear the selection and move the caret forward by one
// character
selectionStart += selectionLength;
if (selectionLength == 0
&& selectionStart < document.getCharacterCount()) {
selectionStart++;
}
selectionLength = 0;
}
textArea.setSelection(selectionStart, selectionLength);
caretX = caret.x;
consumed = true;
} else if (keyCode == Keyboard.KeyCode.UP) {
// TODO We shouldn't need a "magic" number like 2 here
int offset = documentView.getCharacterAt(caretX, caret.y - 2);
// TODO Modify selection based on SHIFT key
textArea.setSelection(offset, 0);
// TODO Make sure we scroll the next view to visible
consumed = true;
} else if (keyCode == Keyboard.KeyCode.DOWN) {
int offset = documentView.getCharacterAt(caretX, caret.y + caret.height + 1);
// TODO Modify selection based on SHIFT key
textArea.setSelection(offset, 0);
// TODO Make sure we scroll the next view to visible
consumed = true;
} else if (Keyboard.isPressed(Keyboard.Modifier.CTRL)) {
if (keyCode == Keyboard.KeyCode.A) {
textArea.setSelection(0, document.getCharacterCount());
} else if (keyCode == Keyboard.KeyCode.X) {
textArea.cut();
} else if (keyCode == Keyboard.KeyCode.C) {
textArea.copy();
} else if (keyCode == Keyboard.KeyCode.V) {
textArea.paste();
} else if (keyCode == Keyboard.KeyCode.Z) {
if (Keyboard.isPressed(Keyboard.Modifier.SHIFT)) {
textArea.undo();
} else {
textArea.redo();
}
}
} else {
consumed = super.keyPressed(component, keyCode, keyLocation);
}