-
Notifications
You must be signed in to change notification settings - Fork 19
/
TextInputControl.java
1715 lines (1531 loc) · 63 KB
/
TextInputControl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.scene.control;
import com.sun.javafx.scene.control.FormatterAccessor;
import javafx.beans.DefaultProperty;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ObjectPropertyBase;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableStringValue;
import javafx.beans.value.ObservableValue;
import javafx.beans.value.WritableValue;
import javafx.css.CssMetaData;
import javafx.css.FontCssMetaData;
import javafx.css.PseudoClass;
import javafx.css.StyleOrigin;
import javafx.css.Styleable;
import javafx.css.StyleableObjectProperty;
import javafx.css.StyleableProperty;
import javafx.scene.AccessibleAction;
import javafx.scene.AccessibleAttribute;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.text.Font;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.sun.javafx.util.Utils;
import com.sun.javafx.binding.ExpressionHelper;
import com.sun.javafx.scene.NodeHelper;
import javafx.util.StringConverter;
/**
* Abstract base class for text input controls.
* @since JavaFX 2.0
*/
@DefaultProperty("text")
public abstract class TextInputControl extends Control {
/**
* Interface representing a text input's content. Since it is an ObservableStringValue,
* you can also bind to, or observe the content.
* @since JavaFX 2.0
*/
protected interface Content extends ObservableStringValue {
/**
* Retrieves a subset of the content.
*
* @param start the start
* @param end the end
* @return a subset of the content
*/
public String get(int start, int end);
/**
* Inserts a sequence of characters into the content.
*
* @param index the index
* @param text the text string
* @param notifyListeners the notify listener flag
* @since JavaFX 2.1
*/
public void insert(int index, String text, boolean notifyListeners);
/**
* Removes a sequence of characters from the content.
*
* @param start the start
* @param end the end
* @param notifyListeners the notify listener flag
* @since JavaFX 2.1
*/
public void delete(int start, int end, boolean notifyListeners);
/**
* Returns the number of characters represented by the content.
* @return the number of characters
*/
public int length();
}
private boolean blockSelectedTextUpdate;
/* *************************************************************************
* *
* Constructors *
* *
**************************************************************************/
/**
* Creates a new TextInputControl. The content is an immutable property and
* must be specified (as non-null) at the time of construction.
*
* @param content a non-null implementation of Content.
*/
protected TextInputControl(final Content content) {
this.content = content;
// Add a listener so that whenever the Content is changed, we notify
// listeners of the text property that it is invalid.
content.addListener(observable -> {
if (content.length() > 0) {
text.textIsNull = false;
}
text.controlContentHasChanged();
});
// Bind the length to be based on the length of the text property
length.bind(new IntegerBinding() {
{ bind(text); }
@Override protected int computeValue() {
String txt = text.get();
return txt == null ? 0 : txt.length();
}
});
// Bind the selected text to be based on the selection and text properties
selection.addListener((ob, o, n) -> updateSelectedText());
text.addListener((ob, o, n) -> updateSelectedText());
focusedProperty().addListener((ob, o, n) -> {
if (n) {
if (getTextFormatter() != null) {
updateText(getTextFormatter());
}
} else {
commitValue();
}
});
// Specify the default style class
getStyleClass().add("text-input");
}
private void updateSelectedText() {
if (!blockSelectedTextUpdate) {
String txt = text.get();
IndexRange sel = selection.get();
if (txt == null || sel == null) {
selectedText.set("");
} else {
int start = sel.getStart();
int end = sel.getEnd();
int length = txt.length();
if (end > start + length) {
end = length;
}
if (start > length - 1) {
start = end = 0;
}
selectedText.set(txt.substring(start, end));
}
}
}
/* *************************************************************************
* *
* Properties *
* *
**************************************************************************/
/**
* The default font to use for text in the TextInputControl. If the TextInputControl's text is
* rich text then this font may or may not be used depending on the font
* information embedded in the rich text, but in any case where a default
* font is required, this font will be used.
* @return the font property
* @since JavaFX 8.0
*/
public final ObjectProperty<Font> fontProperty() {
if (font == null) {
font = new StyleableObjectProperty<Font>(Font.getDefault()) {
private boolean fontSetByCss = false;
@Override
public void applyStyle(StyleOrigin newOrigin, Font value) {
//
// RT-20727 - if CSS is setting the font, then make sure invalidate doesn't call NodeHelper.reapplyCSS
//
try {
// super.applyStyle calls set which might throw if value is bound.
// Have to make sure fontSetByCss is reset.
fontSetByCss = true;
super.applyStyle(newOrigin, value);
} catch(Exception e) {
throw e;
} finally {
fontSetByCss = false;
}
}
@Override
public void set(Font value) {
final Font oldValue = get();
if (value == null ? oldValue == null : value.equals(oldValue)) {
return;
}
super.set(value);
}
@Override
protected void invalidated() {
// RT-20727 - if font is changed by calling setFont, then
// css might need to be reapplied since font size affects
// calculated values for styles with relative values
if(fontSetByCss == false) {
NodeHelper.reapplyCSS(TextInputControl.this);
}
}
@Override
public CssMetaData<TextInputControl,Font> getCssMetaData() {
return StyleableProperties.FONT;
}
@Override
public Object getBean() {
return TextInputControl.this;
}
@Override
public String getName() {
return "font";
}
};
}
return font;
}
private ObjectProperty<Font> font;
public final void setFont(Font value) { fontProperty().setValue(value); }
public final Font getFont() { return font == null ? Font.getDefault() : font.getValue(); }
/**
* The prompt text to display in the {@code TextInputControl}. If set to null or an empty string, no
* prompt text is displayed.
*
* @defaultValue An empty String
* @since JavaFX 2.2
*/
private StringProperty promptText = new SimpleStringProperty(this, "promptText", "") {
@Override protected void invalidated() {
// Strip out newlines
String txt = get();
if (txt != null && txt.contains("\n")) {
txt = txt.replace("\n", "");
set(txt);
}
}
};
public final StringProperty promptTextProperty() { return promptText; }
public final String getPromptText() { return promptText.get(); }
public final void setPromptText(String value) { promptText.set(value); }
/**
* The property contains currently attached {@link TextFormatter}.
* Since the value is part of the {@code Formatter}, changing the TextFormatter will update the text based on the new textFormatter.
*
* @defaultValue null
* @since JavaFX 8u40
*/
private final ObjectProperty<TextFormatter<?>> textFormatter = new ObjectPropertyBase<TextFormatter<?>>() {
private TextFormatter<?> oldFormatter = null;
@Override
public Object getBean() {
return TextInputControl.this;
}
@Override
public String getName() {
return "textFormatter";
}
@Override
protected void invalidated() {
final TextFormatter<?> formatter = get();
try {
if (formatter != null) {
try {
formatter.bindToControl(f -> updateText(f));
} catch (IllegalStateException e) {
if (isBound()) {
unbind();
}
set(null);
throw e;
}
if (!isFocused()) {
updateText(get());
}
}
if (oldFormatter != null) {
oldFormatter.unbindFromControl();
}
} finally {
oldFormatter = formatter;
}
}
};
public final ObjectProperty<TextFormatter<?>> textFormatterProperty() { return textFormatter; }
public final TextFormatter<?> getTextFormatter() { return textFormatter.get(); }
public final void setTextFormatter(TextFormatter<?> value) { textFormatter.set(value); }
private final Content content;
/**
* Returns the text input's content model.
* @return the text input's content model
*/
protected final Content getContent() {
return content;
}
/**
* The textual content of this TextInputControl.
*/
private TextProperty text = new TextProperty();
public final String getText() { return text.get(); }
public final void setText(String value) { text.set(value); }
public final StringProperty textProperty() { return text; }
/**
* The number of characters in the text input.
*/
private ReadOnlyIntegerWrapper length = new ReadOnlyIntegerWrapper(this, "length");
public final int getLength() { return length.get(); }
public final ReadOnlyIntegerProperty lengthProperty() { return length.getReadOnlyProperty(); }
/**
* Indicates whether this TextInputControl can be edited by the user.
*/
private BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) {
@Override protected void invalidated() {
pseudoClassStateChanged(PSEUDO_CLASS_READONLY, ! get());
}
};
public final boolean isEditable() { return editable.getValue(); }
public final void setEditable(boolean value) { editable.setValue(value); }
public final BooleanProperty editableProperty() { return editable; }
/**
* The current selection.
*/
private ReadOnlyObjectWrapper<IndexRange> selection = new ReadOnlyObjectWrapper<IndexRange>(this, "selection", new IndexRange(0, 0));
public final IndexRange getSelection() { return selection.getValue(); }
public final ReadOnlyObjectProperty<IndexRange> selectionProperty() { return selection.getReadOnlyProperty(); }
/**
* Defines the characters in the TextInputControl which are selected
*/
private ReadOnlyStringWrapper selectedText = new ReadOnlyStringWrapper(this, "selectedText");
public final String getSelectedText() { return selectedText.get(); }
public final ReadOnlyStringProperty selectedTextProperty() { return selectedText.getReadOnlyProperty(); }
/**
* The <code>anchor</code> of the text selection.
* The <code>anchor</code> and <code>caretPosition</code> make up the selection
* range. Selection must always be specified in terms of begin <= end, but
* <code>anchor</code> may be less than, equal to, or greater than the
* <code>caretPosition</code>. Depending on how the user selects text,
* the anchor might represent the lower or upper bound of the selection.
*/
private ReadOnlyIntegerWrapper anchor = new ReadOnlyIntegerWrapper(this, "anchor", 0);
public final int getAnchor() { return anchor.get(); }
public final ReadOnlyIntegerProperty anchorProperty() { return anchor.getReadOnlyProperty(); }
/**
* The current position of the caret within the text.
* The <code>anchor</code> and <code>caretPosition</code> make up the selection
* range. Selection must always be specified in terms of begin <= end, but
* <code>anchor</code> may be less than, equal to, or greater than the
* <code>caretPosition</code>. Depending on how the user selects text,
* the caretPosition might represent the lower or upper bound of the selection.
*/
private ReadOnlyIntegerWrapper caretPosition = new ReadOnlyIntegerWrapper(this, "caretPosition", 0);
public final int getCaretPosition() { return caretPosition.get(); }
public final ReadOnlyIntegerProperty caretPositionProperty() { return caretPosition.getReadOnlyProperty(); }
private UndoRedoChange undoChangeHead = new UndoRedoChange();
private UndoRedoChange undoChange = undoChangeHead;
private boolean createNewUndoRecord = false;
/**
* The property describes if it's currently possible to undo the latest change of the content that was done.
* @defaultValue false
* @since JavaFX 8u40
*/
private final ReadOnlyBooleanWrapper undoable = new ReadOnlyBooleanWrapper(this, "undoable", false);
public final boolean isUndoable() { return undoable.get(); }
public final ReadOnlyBooleanProperty undoableProperty() { return undoable.getReadOnlyProperty(); }
/**
* The property describes if it's currently possible to redo the latest change of the content that was undone.
* @defaultValue false
* @since JavaFX 8u40
*/
private final ReadOnlyBooleanWrapper redoable = new ReadOnlyBooleanWrapper(this, "redoable", false);
public final boolean isRedoable() { return redoable.get(); }
public final ReadOnlyBooleanProperty redoableProperty() { return redoable.getReadOnlyProperty(); }
/* *************************************************************************
* *
* Methods *
* *
**************************************************************************/
/**
* Returns a subset of the text input's content.
*
* @param start must be a value between 0 and end - 1.
* @param end must be less than or equal to the length
* @return the subset of the text input's content
*/
public String getText(int start, int end) {
if (start > end) {
throw new IllegalArgumentException("The start must be <= the end");
}
if (start < 0
|| end > getLength()) {
throw new IndexOutOfBoundsException();
}
return getContent().get(start, end);
}
/**
* Appends a sequence of characters to the content.
*
* @param text a non null String
*/
public void appendText(String text) {
insertText(getLength(), text);
}
/**
* Inserts a sequence of characters into the content.
*
* @param index The location to insert the text.
* @param text The text to insert.
*/
public void insertText(int index, String text) {
replaceText(index, index, text);
}
/**
* Removes a range of characters from the content.
*
* @param range The range of text to delete. The range object must not be null.
*
* @see #deleteText(int, int)
*/
public void deleteText(IndexRange range) {
replaceText(range, "");
}
/**
* Removes a range of characters from the content.
*
* @param start The starting index in the range, inclusive. This must be >= 0 and < the end.
* @param end The ending index in the range, exclusive. This is one-past the last character to
* delete (consistent with the String manipulation methods). This must be > the start,
* and <= the length of the text.
*/
public void deleteText(int start, int end) {
replaceText(start, end, "");
}
/**
* Replaces a range of characters with the given text.
*
* @param range The range of text to replace. The range object must not be null.
* @param text The text that is to replace the range. This must not be null.
*
* @see #replaceText(int, int, String)
*/
public void replaceText(IndexRange range, String text) {
final int start = range.getStart();
final int end = start + range.getLength();
replaceText(start, end, text);
}
/**
* Replaces a range of characters with the given text.
*
* @param start The starting index in the range, inclusive. This must be >= 0 and < the end.
* @param end The ending index in the range, exclusive. This is one-past the last character to
* delete (consistent with the String manipulation methods). This must be > the start,
* and <= the length of the text.
* @param text The text that is to replace the range. This must not be null.
*/
public void replaceText(final int start, final int end, final String text) {
if (start > end) {
throw new IllegalArgumentException();
}
if (text == null) {
throw new NullPointerException();
}
if (start < 0
|| end > getLength()) {
throw new IndexOutOfBoundsException();
}
if (!this.text.isBound()) {
final int oldLength = getLength();
TextFormatter<?> formatter = getTextFormatter();
TextFormatter.Change change;
if (formatter != null && formatter.getFilter() != null) {
change = new TextFormatter.Change(this, getFormatterAccessor(), start, end, text);
change = formatter.getFilter().apply(change);
if (change == null) {
return;
}
} else {
change = new TextFormatter.Change(this, getFormatterAccessor(), start, end, filterInput(text));
}
// Update the content
updateContent(change, oldLength == 0);
}
}
private void updateContent(TextFormatter.Change change, boolean forceNewUndoRecord) {
final boolean nonEmptySelection = getSelection().getLength() > 0;
String oldText = getText(change.start, change.end);
int adjustmentAmount = replaceText(change.start, change.end, change.text, change.getAnchor(), change.getCaretPosition());
String newText = getText(change.start, change.start + change.text.length() - adjustmentAmount);
if (newText.equals(oldText)) {
// Undo record not required as there is no change in the text.
return;
}
/*
* A new undo record is created, if
* 1. createNewUndoRecord is true, currently it is set to true for paste operation
* 2. Text is selected and a character is typed
* 3. This is the first operation to be added to undo record
* 4. forceNewUndoRecord is true, currently it is set to true if there is no text present
* 5. Space character is typed
* 6. 2500 milliseconds are elapsed since the undo record was created
* 7. Cursor position is changed and a character is typed
* 8. A range of text is replaced programmatically using replaceText()
* Otherwise, the last undo record is updated or discarded.
*/
int endOfUndoChange = undoChange == undoChangeHead ? -1 : undoChange.start + undoChange.newText.length();
boolean isNewSpaceChar = false;
if (newText.equals(" ")) {
if (!UndoRedoChange.isSpaceCharSequence()) {
isNewSpaceChar = true;
UndoRedoChange.setSpaceCharSequence(true);
}
} else {
UndoRedoChange.setSpaceCharSequence(false);
}
if (createNewUndoRecord || nonEmptySelection || endOfUndoChange == -1 || forceNewUndoRecord ||
isNewSpaceChar || UndoRedoChange.hasChangeDurationElapsed() ||
(endOfUndoChange != change.start && endOfUndoChange != change.end) || change.end - change.start > 0) {
undoChange = undoChange.add(change.start, oldText, newText);
} else if (change.start != change.end && change.text.isEmpty()) {
// I know I am deleting, and am located at the end of the range of the current undo record
if (undoChange.newText.length() > 0) {
undoChange.newText = undoChange.newText.substring(0, change.start - undoChange.start);
if (undoChange.newText.isEmpty()) {
// throw away this undo change record
undoChange = undoChange.discard();
}
} else {
if (change.start == endOfUndoChange) {
undoChange.oldText += oldText;
} else { // end == endOfUndoChange
undoChange.oldText = oldText + undoChange.oldText;
undoChange.start--;
}
}
} else {
// I know I am adding, and am located at the end of the range of the current undo record
undoChange.newText += newText;
}
updateUndoRedoState();
}
/**
* Transfers the currently selected range in the text to the clipboard,
* removing the current selection.
*/
public void cut() {
copy();
IndexRange selection = getSelection();
deleteText(selection.getStart(), selection.getEnd());
}
/**
* Transfers the currently selected range in the text to the clipboard,
* leaving the current selection.
*/
public void copy() {
final String selectedText = getSelectedText();
if (selectedText.length() > 0) {
final ClipboardContent content = new ClipboardContent();
content.putString(selectedText);
Clipboard.getSystemClipboard().setContent(content);
}
}
/**
* Transfers the contents in the clipboard into this text,
* replacing the current selection. If there is no selection, the contents
* in the clipboard is inserted at the current caret position.
*/
public void paste() {
final Clipboard clipboard = Clipboard.getSystemClipboard();
if (clipboard.hasString()) {
final String text = clipboard.getString();
if (text != null) {
createNewUndoRecord = true;
try {
replaceSelection(text);
} finally {
createNewUndoRecord = false;
}
}
}
}
/**
* Moves the selection backward one char in the text. This may have the
* effect of deselecting, depending on the location of the anchor relative
* to the caretPosition. This function effectively just moves the caretPosition.
*/
public void selectBackward() {
if (getCaretPosition() > 0 && getLength() > 0) {
// because the anchor stays put, by moving the caret to the left
// we ensure that a selection is registered and that it is correct
if (charIterator == null) {
charIterator = BreakIterator.getCharacterInstance();
}
charIterator.setText(getText());
selectRange(getAnchor(), charIterator.preceding(getCaretPosition()));
}
}
/**
* Moves the selection forward one char in the text. This may have the
* effect of deselecting, depending on the location of the anchor relative
* to the caretPosition. This function effectively just moves the caret forward.
*/
public void selectForward() {
final int textLength = getLength();
if (textLength > 0 && getCaretPosition() < textLength) {
if (charIterator == null) {
charIterator = BreakIterator.getCharacterInstance();
}
charIterator.setText(getText());
selectRange(getAnchor(), charIterator.following(getCaretPosition()));
}
}
/**
* The break iterator instances for navigation over words and complex characters.
*/
private BreakIterator charIterator;
private BreakIterator wordIterator;
/**
* Moves the caret to the beginning of previous word. This function
* also has the effect of clearing the selection.
*/
public void previousWord() {
previousWord(false);
}
/**
* Moves the caret to the beginning of next word. This function
* also has the effect of clearing the selection.
*/
public void nextWord() {
nextWord(false);
}
/**
* Moves the caret to the end of the next word. This function
* also has the effect of clearing the selection.
*/
public void endOfNextWord() {
endOfNextWord(false);
}
/**
* Moves the caret to the beginning of previous word. This does not cause
* the selection to be cleared. Rather, the anchor stays put and the caretPosition is
* moved to the beginning of previous word.
*/
public void selectPreviousWord() {
previousWord(true);
}
/**
* Moves the caret to the beginning of next word. This does not cause
* the selection to be cleared. Rather, the anchor stays put and the caretPosition is
* moved to the beginning of next word.
*/
public void selectNextWord() {
nextWord(true);
}
/**
* Moves the caret to the end of the next word. This does not cause
* the selection to be cleared.
*/
public void selectEndOfNextWord() {
endOfNextWord(true);
}
private void previousWord(boolean select) {
final int textLength = getLength();
final String text = getText();
if (textLength <= 0) {
return;
}
if (wordIterator == null) {
wordIterator = BreakIterator.getWordInstance();
}
wordIterator.setText(text);
int pos = wordIterator.preceding(Utils.clamp(0, getCaretPosition(), textLength));
// Skip the non-word region, then move/select to the beginning of the word.
while (pos != BreakIterator.DONE &&
!Character.isLetterOrDigit(text.charAt(Utils.clamp(0, pos, textLength-1)))) {
pos = wordIterator.preceding(Utils.clamp(0, pos, textLength));
}
// move/select
selectRange(select ? getAnchor() : pos, pos);
}
private void nextWord(boolean select) {
final int textLength = getLength();
final String text = getText();
if (textLength <= 0) {
return;
}
if (wordIterator == null) {
wordIterator = BreakIterator.getWordInstance();
}
wordIterator.setText(text);
int last = wordIterator.following(Utils.clamp(0, getCaretPosition(), textLength-1));
int current = wordIterator.next();
// Skip whitespace characters to the beginning of next word, but
// stop at newline. Then move the caret or select a range.
while (current != BreakIterator.DONE) {
for (int p=last; p<=current; p++) {
char ch = text.charAt(Utils.clamp(0, p, textLength-1));
// Avoid using Character.isSpaceChar() and Character.isWhitespace(),
// because they include LINE_SEPARATOR, PARAGRAPH_SEPARATOR, etc.
if (ch != ' ' && ch != '\t') {
if (select) {
selectRange(getAnchor(), p);
} else {
selectRange(p, p);
}
return;
}
}
last = current;
current = wordIterator.next();
}
// move/select to the end
if (select) {
selectRange(getAnchor(), textLength);
} else {
end();
}
}
private void endOfNextWord(boolean select) {
final int textLength = getLength();
final String text = getText();
if (textLength <= 0) {
return;
}
if (wordIterator == null) {
wordIterator = BreakIterator.getWordInstance();
}
wordIterator.setText(text);
int last = wordIterator.following(Utils.clamp(0, getCaretPosition(), textLength));
int current = wordIterator.next();
// skip the non-word region, then move/select to the end of the word.
while (current != BreakIterator.DONE) {
for (int p=last; p<=current; p++) {
if (!Character.isLetterOrDigit(text.charAt(Utils.clamp(0, p, textLength-1)))) {
if (select) {
selectRange(getAnchor(), p);
} else {
selectRange(p, p);
}
return;
}
}
last = current;
current = wordIterator.next();
}
// move/select to the end
if (select) {
selectRange(getAnchor(), textLength);
} else {
end();
}
}
/**
* Selects all text in the text input.
*/
public void selectAll() {
selectRange(0, getLength());
}
/**
* Moves the caret to before the first char of the text. This function
* also has the effect of clearing the selection.
*/
public void home() {
// user wants to go to start
selectRange(0, 0);
}
/**
* Moves the caret to after the last char of the text. This function
* also has the effect of clearing the selection.
*/
public void end() {
// user wants to go to end
final int textLength = getLength();
if (textLength > 0) {
selectRange(textLength, textLength);
}
}
/**
* Moves the caret to before the first char of text. This does not cause
* the selection to be cleared. Rather, the anchor stays put and the
* caretPosition is moved to before the first char.
*/
public void selectHome() {
selectRange(getAnchor(), 0);
}
/**
* Moves the caret to after the last char of text. This does not cause
* the selection to be cleared. Rather, the anchor stays put and the
* caretPosition is moved to after the last char.
*/
public void selectEnd() {
final int textLength = getLength();
if (textLength > 0) selectRange(getAnchor(), textLength);
}
/**
* Deletes the character that precedes the current caret position from the
* text if there is no selection, or deletes the selection if there is one.
* This function returns true if the deletion succeeded, false otherwise.
* @return true if the deletion succeeded, false otherwise
*/
public boolean deletePreviousChar() {
boolean failed = true;
if (isEditable() && !isDisabled()) {
final String text = getText();
final int dot = getCaretPosition();
final int mark = getAnchor();
if (dot != mark) {
// there is a selection of text to remove
replaceSelection("");
failed = false;
} else if (dot > 0) {
// The caret is not at the beginning, so remove some characters.
// Typically you'd only be removing a single character, but
// in some cases you must remove two depending on the unicode
// characters
// Note: Do not use charIterator here, because we do want to
// break up clusters when deleting backwards.
int p = Character.offsetByCodePoints(text, dot, -1);
deleteText(p, dot);
failed = false;
}
}
return !failed;
}
/**
* Deletes the character that follows the current caret position from the
* text if there is no selection, or deletes the selection if there is one.
* This function returns true if the deletion succeeded, false otherwise.
* @return true if the deletion succeeded, false otherwise
*/
public boolean deleteNextChar() {
boolean failed = true;
if (isEditable() && !isDisabled()) {
final int textLength = getLength();
final String text = getText();
final int dot = getCaretPosition();
final int mark = getAnchor();
if (dot != mark) {
// there is a selection of text to remove
replaceSelection("");
failed = false;
} else if (textLength > 0 && dot < textLength) {
// The caret is not at the end, so remove some characters.
// Typically you'd only be removing a single character, but
// in some cases you must remove two depending on the unicode
// characters
if (charIterator == null) {
charIterator = BreakIterator.getCharacterInstance();
}
charIterator.setText(text);
int p = charIterator.following(dot);
deleteText(dot, p);
failed = false;
}
}
return !failed;
}
/**
* Moves the caret position forward. If there is no selection, then the
* caret position is moved one character forward. If there is a selection,
* then the caret position is moved to the end of the selection and
* the selection cleared.
*/
public void forward() {
// user has moved caret to the right
final int textLength = getLength();
final int dot = getCaretPosition();
final int mark = getAnchor();
if (dot != mark) {
int pos = Math.max(dot, mark);
selectRange(pos, pos);
} else if (dot < textLength && textLength > 0) {