/
FormattedTextField.java
2152 lines (1987 loc) · 86.4 KB
/
FormattedTextField.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) 2002-2015, JIDE Software Inc. 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.
*/
package jidefx.scene.control.field;
import com.sun.javafx.scene.control.skin.TextFieldSkin;
import com.sun.javafx.scene.text.HitInfo;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.css.PseudoClass;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Cell;
import javafx.scene.control.IndexRange;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.shape.Shape;
import javafx.util.Callback;
import javafx.util.StringConverter;
import jidefx.scene.control.decoration.DecorationDelegate;
import jidefx.scene.control.decoration.DecorationPane;
import jidefx.scene.control.decoration.DecorationSupport;
import jidefx.scene.control.decoration.DecorationUtils;
import jidefx.scene.control.decoration.Decorator;
import jidefx.scene.control.decoration.PredefinedDecorators;
import jidefx.scene.control.editor.Editor;
import jidefx.scene.control.field.verifier.IntegerRangePatternVerifier;
import jidefx.scene.control.field.verifier.PatternVerifier;
import jidefx.utils.AutoRepeatButtonUtils;
import jidefx.utils.CommonUtils;
import jidefx.utils.PredefinedShapes;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* {@code FormattedTextField} is a {@code TextField} that can restrict the user input by applying a pattern to separate
* the input string into groups, then define PatternVerifiers to verify/restrict the input for each group.
* <p>
* Let's start by looking an example for an IPv4 address field.
* <pre>{@code
* FormattedTextField<String> field = new FormattedTextField<>();
* field.setPattern("h.h.h.h");
* field.getPatternVerifiers().put('h', new IntegerRangeGroupVerifier(0, 255));
* }</pre>
* <p>
* The pattern is "h.h.h.h", it means there are four groups, separated by dots. It doesn?t really matter which letter or
* letters you use here because it is just a name for the group. In this case, four groups have the same name "h". Then
* in the PatternVerifiers map, we added a verifier for the group named "h". The verifier will enforce the input string
* for the group is a number and it must be between 0 and 255.
*
* @param <T> the data type of the value in the {@code FormattedTextField}
*/
@SuppressWarnings({"Convert2Lambda", "SpellCheckingInspection", "UnusedDeclaration"})
public class FormattedTextField<T> extends TextField implements DecorationSupport, Editor<T> {
private static final String STYLE_CLASS_DEFAULT = "formatted-text-field"; //NON-NLS
private static final String STYLE_CLASS_NO_BACKGROUND_BUTTON = "no-background-button"; //NON-NLS
private static final String STYLE_CLASS_INCREASE_BUTTON_ = "increase-button"; //NON-NLS
private static final String STYLE_CLASS_DECREASE_BUTTON = "decrease-button"; //NON-NLS
private static final String PROPERTY_FORMATTED_TEXT_FIELD_ADJUSTMENT_MOUSE_HANDLER = "FormattedTextField.AdjustmentMouseHandler"; //NON-NLS
private StringProperty _patternProperty;
private StringProperty _regularExpressionProperty;
private BooleanProperty _autoAdvanceProperty;
private BooleanProperty _autoReformatProperty;
private BooleanProperty _autoSelectAllProperty;
private boolean _internalAutoSelectAll = true;
private ObjectProperty<T> _valueProperty;
private ObjectProperty<T> _defaultValueProperty;
private ObjectProperty<StringConverter<T>> _stringConverterProperty;
private BooleanProperty _clearbuttonVisibleProperty;
private Decorator<Button> _clearButtonDecorator;
private BooleanProperty _spinnersVisibleProperty;
private ObservableMap<String, Callback<String, Boolean>> _patternVerifiers;
private String _fixedText;
private DecorationPane _decorationPane;
private Decorator<Button> _increaseDecorator;
private Decorator<Button> _decreaseDecorator;
private Button _decreaseSpinnerButton;
private Button _increaseSpinnerButton;
/**
* Creates a {@code FormattedTextField} with a null value. This constrcutor will call {@link #initializePattern()},
* {@link #initializeTextField()}, {@link #initializeStyle()}, {@link #registerListeners()} in order, at last, the
* setValue(null) method. Subclass can override those methods to do its own initialization.
*/
public FormattedTextField() {
this(null);
}
/**
* Creates a {@code FormattedTextField} with an initial value. This constrcutor will call {@link
* #initializeStyle()}, {@link #initializePattern()}, {@link #initializeTextField()}, {@link #registerListeners()}
* in order, at last, the setValue method. Subclass can override those methods to do its own initialization.
*
* @param value the initial value.
*/
public FormattedTextField(T value) {
initializePattern();
initializeTextField();
initializeStyle();
registerListeners();
setValue(value);
}
/**
* Adds or removes style from the getStyleClass. Subclass should call super if you want to keep the existing
* styles.
*/
protected void initializeStyle() {
getStyleClass().addAll(STYLE_CLASS_DEFAULT, DecorationSupport.STYLE_CLASS_DECORATION_SUPPORT);
}
/**
* Do some initialization of the text field, such as set the PopupContentFactory. Subclass should call supper
* first.
*/
protected void initializeTextField() {
// setContentFilter(new Callback<ContentChange, ContentChange>() {
// @Override
// public ContentChange call(ContentChange param) {
// return param;
// }
// });
}
/**
* Subclass can override this method to initializes the pattern, pattern verifiers and the StringConverter. Subclass
* should call supper first.
*/
protected void initializePattern() {
InvalidationListener verifierListener = new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
if (getPattern() != null) {
_fixedText = null;
updateText(getValue());
}
}
};
getPatternVerifiers().addListener(verifierListener);
}
/**
* Gets the verifiers for the group. The verifier is a callback which will verify the input String and return true
* or false. True means the input String is valid for the group, false means invalid.
*
* @return the verifiers for the group.
*/
public ObservableMap<String, Callback<String, Boolean>> getPatternVerifiers() {
if (_patternVerifiers == null) {
_patternVerifiers = FXCollections.observableHashMap();
}
return _patternVerifiers;
}
// TODO: not used yet. The original purpose is to enforce setText call so that it is formatted.
private boolean enforcing = true;
private String comboBoxStyleClass = "combo-box-field"; //NON-NLS
private String textInputStyleClass = "text-input"; //NON-NLS
protected void registerListeners() {
addEventFilter(ScrollEvent.ANY, new EventHandler<ScrollEvent>() {
@Override
public void handle(ScrollEvent event) {
if (!isFocused()) {
requestFocus();
}
MouseEvent e = new MouseEvent(event.getSource(), event.getTarget(), MouseEvent.MOUSE_CLICKED,
event.getX(), event.getY(), event.getScreenX(), event.getScreenY(), MouseButton.PRIMARY, 1, false, false, false, false, true, false, false, true, false, true,
null);
// Note: if you are using JDK8u40 or earlier, please use the first line below and comment out the second line
// HitInfo hitInfo = ((TextFieldSkin) getSkin()).getIndex(e);
HitInfo hitInfo = ((TextFieldSkin) getSkin()).getIndex(e.getX(), e.getY());
if (getCaretPosition() != hitInfo.getCharIndex()) {
((TextFieldSkin) getSkin()).positionCaret(hitInfo, false);
}
int count = event.isShiftDown() ? 10 : 1;
for (int i = 0; i < count; i++) {
if (event.getDeltaY() > 0) {
increaseValue();
}
else if (event.getDeltaY() < 0) {
decreaseValue();
}
}
}
});
addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.TAB && !event.isControlDown()) {
boolean forward = !event.isShiftDown();
if (forward && selectNextGroup()) {
event.consume();
}
if (!forward && selectPreviousGroup()) {
event.consume();
}
}
else if (event.getCode() == KeyCode.ENTER) {
if (commitEdit()) {
if (!(getParent() instanceof Cell)) {
event.consume();
}
}
else if (cancelEditing()) {
event.consume();
}
}
else if (event.getCode() == KeyCode.ESCAPE) {
if (cancelEditing()) {
event.consume();
}
}
if (!event.isConsumed()) {
if (processKeyCode(event)) {
event.consume();
}
}
}
});
editableProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (isComboBoxLike()) {
if (newValue) {
getStyleClass().remove(comboBoxStyleClass);
getStyleClass().add(textInputStyleClass);
}
else {
getStyleClass().add(comboBoxStyleClass);
getStyleClass().remove(textInputStyleClass);
}
}
configPseudoClassState(newValue);
}
});
focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (_decorationPane != null && _decorationPane.getParent() != null && !isEditable()) {
if (newValue) {
pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), false);
_decorationPane.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), true);
}
else {
_decorationPane.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), false);
}
}
if (!newValue) {
if (!commitEdit()) {
cancelEditing();
}
}
}
});
heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
configDecorationPane();
}
});
spinnerStyleProperty().addListener(new ChangeListener<SpinnerStyle>() {
@Override
public void changed(ObservableValue<? extends SpinnerStyle> observable, SpinnerStyle oldValue, SpinnerStyle newValue) {
hideSpinners();
_increaseDecorator = null;
_decreaseDecorator = null;
configDecorationPane();
if (isSpinnersVisible()) {
showSpinners();
requestLayout();
}
}
});
}
private void configPseudoClassState(Boolean newValue) {
if (_decorationPane != null) {
pseudoClassStateChanged(PseudoClass.getPseudoClass("readonly"), !newValue); //NON-NLS
}
else if (newValue) {
pseudoClassStateChanged(PseudoClass.getPseudoClass("readonly"), false); //NON-NLS
}
}
private void configDecorationPane() {
if (_decorationPane != null) {
_decorationPane.getStyleClass().removeAll("combo-box-base"); //NON-NLS
_decorationPane.getStyleClass().addAll("combo-box-base"); //NON-NLS
double increaseWidth = _increaseSpinnerButton == null || _increaseSpinnerButton.getPrefWidth() == 0 ? spinnerButtonSize : _increaseSpinnerButton.getPrefWidth();
double increaseHeight = _increaseSpinnerButton == null || _increaseSpinnerButton.getPrefHeight() == 0 ? spinnerButtonSize : _increaseSpinnerButton.getPrefHeight();
double decreaseWidth = _decreaseSpinnerButton == null || _decreaseSpinnerButton.getPrefWidth() == 0 ? spinnerButtonSize : _decreaseSpinnerButton.getPrefWidth();
double decreaseHeight = _decreaseSpinnerButton == null || _decreaseSpinnerButton.getPrefHeight() == 0 ? spinnerButtonSize : _decreaseSpinnerButton.getPrefHeight();
double maxWidth = Math.max(increaseWidth, decreaseWidth);
double maxHeight = Math.max(increaseHeight, decreaseHeight);
double groupedVerticalPadding = maxHeight > getHeight() ? maxHeight / 2 - getHeight() / 2 : 0;
double verticalPadding = maxHeight * 2 - getHeight() <= 0 ? 0 : maxHeight - getHeight() / 2;
switch (getSpinnerStyle()) {
case OUTSIDE_LEFT_HORIZONTAL:
_decorationPane.setPadding(new Insets(groupedVerticalPadding, 0, groupedVerticalPadding, maxWidth * horizontalTotalWidthRatio));
break;
case OUTSIDE_LEFT_VERTICAL:
_decorationPane.setPadding(new Insets(verticalPadding, 0, verticalPadding, maxWidth * verticalTotalWidthRatio));
break;
case OUTSIDE_CENTER_HORIZONTAL:
_decorationPane.setPadding(new Insets(groupedVerticalPadding, maxWidth * verticalTotalWidthRatio, groupedVerticalPadding, maxWidth * verticalTotalWidthRatio));
break;
case OUTSIDE_CENTER_VERTICAL:
_decorationPane.setPadding(new Insets(maxHeight * 0.9, 0, maxHeight * 0.9, 0));
break;
case OUTSIDE_RIGHT_HORIZONTAL:
_decorationPane.setPadding(new Insets(groupedVerticalPadding, maxWidth * horizontalTotalWidthRatio, groupedVerticalPadding, 0));
break;
case OUTSIDE_RIGHT_VERTICAL:
_decorationPane.setPadding(new Insets(verticalPadding, maxWidth * verticalTotalWidthRatio, verticalPadding, 0));
break;
default:
_decorationPane.setPadding(new Insets(0));
break;
}
}
}
/**
* Set the value to the default value or null if the default value was not set.
*/
@Override
public void clear() {
setValue(getDefaultValue());
}
private void setTextWithoutChecking(String text) {
try {
enforcing = false;
setText(text);
}
finally {
enforcing = true;
}
}
/**
* Cancels the edit to reset the text using the previous value.
* <p>
* This method was named cancelEdit and had to be renamed to cancelEditing since JDK8u40 because it introduced a
* final cancelEdit() method in the TextInputControl.
*
* @return true if canceled. False if not canceled because the previous value is null or the current value is the
* same as the previous cancel (or you can think it as the value was just canceled and now you cancel it again).
*/
public boolean cancelEditing() {
T value = getValue();
if (value != null) {
String groupName = getCurrentGroupName();
enforcing = false;
try {
String oldText = getText();
String newText = toString(value);
if (!CommonUtils.equals(oldText, newText)) {
setTextWithoutChecking(newText);
}
else {
return false;
}
}
finally {
enforcing = false;
}
if (groupName != null) {
IndexRange range = getGroupRangeAt(groupName);
if (range != null) {
selectRange(range.getStart(), range.getEnd());
}
}
return true;
}
else {
return false;
}
}
/**
* Commits the edit and set the value.
*
* @return true if commited. False if not commited because the text format is incorrect.
*/
public boolean commitEdit() {
if (!supportFromString()) {
return true;
}
T value = fromString(getText());
if (value == null) {
return false;
}
setValue(value);
return true;
}
protected String toString(T value) {
StringConverter<T> objectConverter = getStringConverter();
if (objectConverter != null) {
return objectConverter.toString(value);
}
return null;
}
protected T fromString(String text) {
StringConverter<T> objectConverter = getStringConverter();
if (objectConverter != null) {
try {
return objectConverter.fromString(text);
}
catch (Exception e) {
CommonUtils.ignoreException(e);
}
}
return null;
}
protected boolean supportFromString() {
return getStringConverter() != null;
}
/**
* Moves the caret to the beginning of the current group or the end of the previous group. This function also has
* the effect of clearing the selection.
*/
@Override
public void previousWord() {
IndexRange range = previousRange(true);
if (range != null) {
if (getCaretPosition() <= range.getEnd()) {
positionCaret(range.getStart());
}
else {
positionCaret(range.getEnd());
}
}
}
/**
* Moves the caret to the end of the current group or beginning of next group. This function also has the effect of
* clearing the selection.
*/
@Override
public void nextWord() {
IndexRange range = nextRange(true);
if (range != null) {
if (getCaretPosition() >= range.getStart()) {
positionCaret(range.getEnd());
}
else {
positionCaret(range.getStart());
}
}
}
/**
* Moves the caret to the end of the current group or beginning of next group. This function also has the effect of
* clearing the selection. It is the same as {@link #nextWord()}.
*/
@Override
public void endOfNextWord() {
nextWord();
}
/**
* Moves the caret to the beginning of current group or the end of the previous group. This does not cause the
* selection to be cleared. Rather, the anchor stays put and the caretPosition is moved.
*/
@Override
public void selectPreviousWord() {
IndexRange range = previousRange(true);
if (range != null) {
if (getCaretPosition() <= range.getEnd()) {
selectPositionCaret(range.getStart());
}
else {
selectPositionCaret(range.getEnd());
}
}
}
/**
* For the grouped-based field, it will move the caret to the end of current group or the beginning of the next
* group. This does not cause the selection to be cleared. Rather, the anchor stays put and the caretPosition is
* moved.
* <p>
* For position-based field, it will simply call super.
*/
@Override
public void selectNextWord() {
IndexRange range = nextRange(true);
if (range != null) {
if (getCaretPosition() >= range.getStart()) {
selectPositionCaret(range.getEnd());
}
else {
selectPositionCaret(range.getStart());
}
}
}
/**
* For the grouped-based field, it will move the caret to the end of current group or the beginning of the next
* group. This does not cause the selection to be cleared. Rather, the anchor stays put and the caretPosition is
* moved. It is the same as {@link #selectNextWord()}.
* <p>
* For position-based field, it will simply call super.
*/
@Override
public void selectEndOfNextWord() {
selectNextWord();
}
private IndexRange nextRange(boolean checkEnd) {
IndexRange range = getGroupRangeAt(getCaretPosition());
if (range != null) {
if (checkEnd && range.getEnd() != getCaretPosition()) { // not at the end of the range yet
return range;
}
else if (!checkEnd && range.getStart() != getCaretPosition()) { // not at the start of the range yet
return range;
}
else {
IndexRange nextRange = findNextRange(range.getEnd());
return nextRange == null ? new IndexRange(range.getEnd(), range.getEnd()) : nextRange;
}
}
else return null;
}
private IndexRange findNextRange(int rangeEnd) {
for (int i = rangeEnd + 1; i < getText().length(); i++) {
IndexRange nextRange = getGroupRangeAt(i);
if (nextRange != null && nextRange.getEnd() != rangeEnd) {
return nextRange;
}
}
return null;
}
private IndexRange previousRange(boolean checkStart) {
IndexRange range = getGroupRangeAt(getCaretPosition());
if (range != null) {
if (checkStart && range.getStart() != getCaretPosition()) { // not at the start of the range yet
return range;
}
else if (!checkStart && range.getEnd() != getCaretPosition()) { // not at the end of the range yet
return range;
}
else {
IndexRange previousRange = findPreviousRange(range.getStart());
return previousRange == null ? new IndexRange(range.getStart(), range.getStart()) : previousRange;
}
}
else return null;
}
private IndexRange findPreviousRange(int rangeStart) {
for (int i = rangeStart - 1; i >= 0; i--) {
IndexRange previousRange = getGroupRangeAt(i);
if (previousRange != null && previousRange.getStart() != rangeStart) {
return previousRange;
}
}
return null;
}
/**
* Selects the next group. Commits the edit before selecting.
* <p>
* Valid only for the group-based field.
*
* @return true if succeed, false if not selected.
*/
public boolean selectPreviousGroup() {
commitWithoutSelectAll();
int caretPosition = getCaretPosition();
IndexRange range = getGroupRangeAt(caretPosition);
if (caretPosition > 0) {
for (int i = caretPosition - 1; i >= 0; i--) {
IndexRange newRange = getGroupRangeAt(i);
if (newRange != null && !newRange.equals(range)) {
selectRange(newRange.getStart(), newRange.getEnd());
return true;
}
}
}
return false;
}
/**
* Selects the next group. Commits the edit before selecting.
* <p>
* Valid only for the group-based field.
*
* @return true if succeed, false if not selected.
*/
public boolean selectNextGroup() {
commitWithoutSelectAll();
int caretPosition = getCaretPosition();
IndexRange range = getGroupRangeAt(caretPosition);
if (caretPosition < getText().length()) {
for (int i = caretPosition + 1; i <= getText().length(); i++) {
IndexRange newRange = getGroupRangeAt(i);
if (newRange != null && !newRange.equals(range)) {
selectRange(newRange.getStart(), newRange.getEnd());
return true;
}
}
}
return false;
}
private void commitWithoutSelectAll() {
_internalAutoSelectAll = false;
try {
if (!commitEdit()) {
cancelEditing();
}
}
finally {
_internalAutoSelectAll = true;
}
}
/**
* Selects the group.
*
* @return true if succeed, false if not selected.
*/
public boolean selectCurrentGroup() {
IndexRange range = getGroupRangeAt(getCaretPosition());
if (range != null) {
selectRange(range.getStart(), range.getEnd());
return true;
}
return false;
}
/**
* Increases or decreases the value in the current group. The current group text will be selected.
*
* @param event the KeyEvent.
* @return true if the value is adjusted, otherwise false. If the text in the current group is not number, it will
* return false.
*/
@SuppressWarnings("unchecked")
public boolean processKeyCode(KeyEvent event) {
if (!event.getCode().isNavigationKey()
|| event.getCode() == KeyCode.LEFT || event.getCode() == KeyCode.RIGHT
|| (!event.isShortcutDown() && (event.getCode() == KeyCode.HOME || event.getCode() == KeyCode.END)))
return false;
if (event.getEventType() == KeyEvent.KEY_PRESSED) {
// find a group from the current caret position
String name = getCurrentGroupName();
if (name == null || name.trim().isEmpty()) {
int caretPosition = getCaretPosition();
int length = getText().length();
for (int i = 0; i < length; i++) {
int caret = (i + caretPosition) % length;
positionCaret(caret);
name = getCurrentGroupName();
if (name != null && !name.trim().isEmpty()) break;
}
}
String text = getCurrentGroupText();
if (text != null) {
try {
Callback<String, Boolean> verifier = getPatternVerifiers().get(name);
if (verifier != null) {
if (verifier instanceof PatternVerifier.Adjustable && verifier instanceof PatternVerifier.Formatter && verifier instanceof PatternVerifier.Parser) {
if (verifier instanceof PatternVerifier.Value) {
try {
((PatternVerifier.Value) verifier).setFieldValue(fromString(getText()));
}
catch (Exception e) {
// setFieldValue will not accept any null value so we will explain to user why it happens.
e.printStackTrace();
}
}
Object newValue = null;
Object value = ((PatternVerifier.Parser) verifier).parse(text);
switch (event.getCode()) {
case UP:
newValue = ((PatternVerifier.Adjustable) verifier).getNextValue(value, !event.isShiftDown());
break;
case DOWN:
newValue = ((PatternVerifier.Adjustable) verifier).getPreviousValue(value, !event.isShiftDown());
break;
case PAGE_UP:
newValue = ((PatternVerifier.Adjustable) verifier).getNextPage(value, !event.isShiftDown());
break;
case PAGE_DOWN:
newValue = ((PatternVerifier.Adjustable) verifier).getPreviousPage(value, !event.isShiftDown());
break;
case HOME:
if (event.isShortcutDown()) {
newValue = ((PatternVerifier.Adjustable) verifier).getHome(value);
}
break;
case END:
if (event.isShortcutDown()) {
newValue = ((PatternVerifier.Adjustable) verifier).getEnd(value);
}
break;
}
if (verifier instanceof PatternVerifier.Value && newValue == null) {
T newFieldValue = ((PatternVerifier.Value<T, ?>) verifier).getFieldValue();
String newWholeText = toString(newFieldValue);
if (newWholeText != null) {
setValue(newFieldValue);
}
IndexRange range = getGroupRangeAt(name);
selectRange(range.getStart(), range.getEnd());
return true;
}
else if (newValue != null) {
String newText = ((PatternVerifier.Formatter) verifier).format(newValue);
int groupStart = getGroupStart(getCaretPosition());
if (verifier.call(newText)) {
super.replaceText(groupStart, groupStart + text.length(), newText);
commitWithoutSelectAll();
selectRange(groupStart, groupStart + newText.length());
}
return true;
}
}
}
}
catch (NumberFormatException e) {
CommonUtils.ignoreException(e);
}
}
}
return false;
}
/**
* Increases the value of the current group by a unit. Only valid for the group-based field.
*/
public void increaseValue() {
if (getCurrentGroupName() == null || getCurrentGroupName().trim().isEmpty()) {
for (int i = 0; i < getText().length(); i++) {
positionCaret(i);
if (getCurrentGroupName() != null && !getCurrentGroupName().trim().isEmpty()) break;
}
}
requestFocus();
processKeyCode(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.UP, true, false, false, false));
}
/**
* Decreases the value of the current group by a unit. Only valid for the group-based field.
*/
public void decreaseValue() {
if (getCurrentGroupName() == null || getCurrentGroupName().trim().isEmpty()) {
for (int i = 0; i < getText().length(); i++) {
positionCaret(i);
if (getCurrentGroupName() != null && !getCurrentGroupName().trim().isEmpty()) break;
}
}
requestFocus();
processKeyCode(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.DOWN, true, false, false, false));
}
private String getFixedText() {
if (_fixedText == null) {
_fixedText = getInitialTextFromMask();
if(_fixedText == null) {
_fixedText = "";
}
}
return _fixedText;
}
private String getInitialTextFromMask() {
String pattern = getPattern();
ObservableMap<String, Callback<String, Boolean>> verifiers = getPatternVerifiers();
for (String s : verifiers.keySet()) {
pattern = pattern.replace(s, "");
}
_fixedText = pattern;
return pattern;
}
public StringProperty patternProperty() {
if (_patternProperty == null) {
_patternProperty = new SimpleStringProperty(this, "pattern") { //NON-NLS
@Override
protected void invalidated() {
super.invalidated();
_fixedText = null;
updateText(FormattedTextField.this.getValue());
}
};
}
return _patternProperty;
}
/**
* Gets the pattern.
*
* @return the pattern.
*/
public String getPattern() {
return patternProperty().get();
}
/**
* Sets the pattern.
*
* @param pattern a new pattern
*/
public void setPattern(String pattern) {
patternProperty().set(pattern);
}
public StringProperty regularExpressionProperty() {
if (_regularExpressionProperty == null) {
_regularExpressionProperty = new SimpleStringProperty();
}
return _regularExpressionProperty;
}
/**
* Gets the regular expression pattern.
*
* @return the regex.
*/
public String getRegularExpression() {
String regex = regularExpressionProperty().get();
if (regex == null) {
regex = createRegexFromPattern(false);
// verify the regex
if (!verifyMatcher(regex, getPattern())) {
regex = createRegexFromPattern(true);
if (!verifyMatcher(regex, getPattern())) {
throw new IllegalStateException("You must call setRegularExpression method to set a regular expression for the pattern \"" + getPattern() + "\" as we couldn't figure out how to split it in to groups.");
}
}
}
return regex;
}
/**
* Sets the regular expression pattern. This regular expression pattern will be used to parse a string and separate
* it into groups.
* <p>
* In most cases, you don't need to call this method because we will automatically create the regular expression
* using the pattern from the setPattern method. If the groups are separated by a non-group characters, we should
* have no problem figuring out. Even if the groups are adjacent, we will check if the verifier implements {@link
* PatternVerifier.Length}. If yes, we will use the min/maxLength as additional information to help us figuring it
* out. If none of the efforts works, we will at last throw an IllegalStateException in the runtime. When you saw
* this exception, you can then call this method to help us with the regular expression, or you can improve the
* pattern or the verifier.
*
* @param regex a new regular expression pattern with the group information.
*/
public void setRegularExpression(String regex) {
regularExpressionProperty().set(regex);
}
private boolean verifyMatcher(String regex, String sampleText) {
Matcher matcher = Pattern.compile(regex).matcher(sampleText);
if (matcher != null && matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
String group = matcher.group(i);
if (group == null || group.trim().isEmpty()) {
return false;
}
}
return true;
}
return false;
}
public ObjectProperty<StringConverter<T>> stringConverterProperty() {
if (_stringConverterProperty == null) {
_stringConverterProperty = new SimpleObjectProperty<>();
}
return _stringConverterProperty;
}
/**
* Gets the StringConverter.
*
* @return the StringConverter.
*/
public StringConverter<T> getStringConverter() {
return stringConverterProperty().get();
}
/**
* Sets the StringConverter that will convert the value from/to String.
*
* @param stringConverter the new StringConverter.
*/
public void setStringConverter(StringConverter<T> stringConverter) {
stringConverterProperty().set(stringConverter);
}
public ObjectProperty<T> valueProperty() {
if (_valueProperty == null) {
_valueProperty = new SimpleObjectProperty<T>(this, "value") { //NON-NLS
@Override
protected void invalidated() {
super.invalidated();
T value = get();
if (value != null && !supportFromString()) {
throw new IllegalStateException("You must call setStringConverter before you can call setValue.");
}
updateText(value);
}
};
}
return _valueProperty;
}
private void updateText(T value) {
String text = toString(value);
if (text != null) {
if (!text.equals(getText())) {
setTextWithoutChecking(text);
}
if (isAutoSelectAll() && _internalAutoSelectAll) {
selectAll();
}
}
else {
setTextWithoutChecking(getInitialTextFromMask());
if (isAutoSelectAll() && _internalAutoSelectAll) {
selectAll();
}
}
}
/**
* Gets the value represented by this {@code FormattedTextField}. The value is only used by the group-based field.
*
* @return the value if it is the group-based field.