-
Notifications
You must be signed in to change notification settings - Fork 437
/
TextAreaSkin.java
1490 lines (1271 loc) · 57.1 KB
/
TextAreaSkin.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, 2021, 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.skin;
import com.sun.javafx.scene.control.behavior.TextAreaBehavior;
import com.sun.javafx.scene.control.skin.Utils;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.value.ObservableBooleanValue;
import javafx.beans.value.ObservableIntegerValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Orientation;
import javafx.geometry.Point2D;
import javafx.geometry.Rectangle2D;
import javafx.geometry.VPos;
import javafx.geometry.VerticalDirection;
import javafx.scene.AccessibleAttribute;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.IndexRange;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.Region;
import javafx.scene.shape.Path;
import javafx.scene.shape.PathElement;
import javafx.scene.text.Text;
import javafx.scene.text.HitInfo;
import javafx.util.Duration;
import java.util.List;
import static com.sun.javafx.PlatformUtil.isMac;
import static com.sun.javafx.PlatformUtil.isWindows;
/**
* Default skin implementation for the {@link TextArea} control.
*
* @see TextArea
* @since 9
*/
public class TextAreaSkin extends TextInputControlSkin<TextArea> {
/* ************************************************************************
*
* Static fields
*
**************************************************************************/
/** A shared helper object, used only by downLines(). */
private static final Path tmpCaretPath = new Path();
/* ************************************************************************
*
* Private fields
*
**************************************************************************/
final private TextArea textArea;
// *** NOTE: Multiple node mode is not yet fully implemented *** //
private static final boolean USE_MULTIPLE_NODES = false;
private final TextAreaBehavior behavior;
private double computedMinWidth = Double.NEGATIVE_INFINITY;
private double computedMinHeight = Double.NEGATIVE_INFINITY;
private double computedPrefWidth = Double.NEGATIVE_INFINITY;
private double computedPrefHeight = Double.NEGATIVE_INFINITY;
private double widthForComputedPrefHeight = Double.NEGATIVE_INFINITY;
private double characterWidth;
private double lineHeight;
private ContentView contentView = new ContentView();
private Group paragraphNodes = new Group();
private Text promptNode;
private ObservableBooleanValue usePromptText;
private ObservableIntegerValue caretPosition;
private Group selectionHighlightGroup = new Group();
private ScrollPane scrollPane;
private Bounds oldViewportBounds;
private VerticalDirection scrollDirection = null;
private Path characterBoundingPath = new Path();
private Timeline scrollSelectionTimeline = new Timeline();
private EventHandler<ActionEvent> scrollSelectionHandler = event -> {
switch (scrollDirection) {
case UP: {
// TODO Get previous offset
break;
}
case DOWN: {
// TODO Get next offset
break;
}
}
};
private double pressX, pressY; // For dragging handles on embedded
private boolean handlePressed;
private EventHandler<ScrollEvent> scrollEventFilter;
/**
* Remembers horizontal position when traversing up / down.
*/
double targetCaretX = -1;
/* ************************************************************************
*
* Constructors
*
**************************************************************************/
/**
* Creates a new TextAreaSkin instance, installing the necessary child
* nodes into the Control {@link Control#getChildren() children} list, as
* well as the necessary input mappings for handling key, mouse, etc events.
*
* @param control The control that this skin should be installed onto.
*/
public TextAreaSkin(final TextArea control) {
super(control);
// install default input map for the text area control
this.behavior = new TextAreaBehavior(control);
this.behavior.setTextAreaSkin(this);
// control.setInputMap(behavior.getInputMap());
this.textArea = control;
caretPosition = new IntegerBinding() {
{ bind(control.caretPositionProperty()); }
@Override protected int computeValue() {
return control.getCaretPosition();
}
};
caretPosition.addListener((observable, oldValue, newValue) -> {
targetCaretX = -1;
if (control.getWidth() > 0) {
setForwardBias(true);
}
});
forwardBiasProperty().addListener(observable -> {
if (control.getWidth() > 0) {
updateTextNodeCaretPos(control.getCaretPosition());
}
});
// setManaged(false);
// Initialize content
scrollPane = new ScrollPane();
scrollPane.setFitToWidth(control.isWrapText());
scrollPane.setContent(contentView);
getChildren().add(scrollPane);
scrollEventFilter = event -> {
if (event.isDirect() && handlePressed) {
event.consume();
}
};
getSkinnable().addEventFilter(ScrollEvent.ANY, scrollEventFilter);
// Add selection
selectionHighlightGroup.setManaged(false);
selectionHighlightGroup.setVisible(false);
contentView.getChildren().add(selectionHighlightGroup);
// Add content view
paragraphNodes.setManaged(false);
contentView.getChildren().add(paragraphNodes);
// Add caret
caretPath.setManaged(false);
caretPath.setStrokeWidth(1);
caretPath.fillProperty().bind(textFillProperty());
caretPath.strokeProperty().bind(textFillProperty());
// modifying visibility of the caret forces a layout-pass (RT-32373), so
// instead we modify the opacity.
caretPath.opacityProperty().bind(new DoubleBinding() {
{ bind(caretVisibleProperty()); }
@Override protected double computeValue() {
return caretVisibleProperty().get() ? 1.0 : 0.0;
}
});
contentView.getChildren().add(caretPath);
if (SHOW_HANDLES) {
contentView.getChildren().addAll(caretHandle, selectionHandle1, selectionHandle2);
}
scrollPane.hvalueProperty().addListener((observable, oldValue, newValue) -> {
getSkinnable().setScrollLeft(newValue.doubleValue() * getScrollLeftMax());
});
scrollPane.vvalueProperty().addListener((observable, oldValue, newValue) -> {
getSkinnable().setScrollTop(newValue.doubleValue() * getScrollTopMax());
});
// Initialize the scroll selection timeline
scrollSelectionTimeline.setCycleCount(Timeline.INDEFINITE);
List<KeyFrame> scrollSelectionFrames = scrollSelectionTimeline.getKeyFrames();
scrollSelectionFrames.clear();
scrollSelectionFrames.add(new KeyFrame(Duration.millis(350), scrollSelectionHandler));
// Add initial text content
for (int i = 0, n = USE_MULTIPLE_NODES ? control.getParagraphs().size() : 1; i < n; i++) {
CharSequence paragraph = (n == 1) ? control.textProperty().getValueSafe() : control.getParagraphs().get(i);
addParagraphNode(i, paragraph.toString());
}
registerChangeListener(control.selectionProperty(), e -> {
// TODO Why do we need two calls here?
control.requestLayout();
contentView.requestLayout();
});
registerChangeListener(control.wrapTextProperty(), e -> {
invalidateMetrics();
scrollPane.setFitToWidth(control.isWrapText());
});
registerChangeListener(control.prefColumnCountProperty(), e -> {
invalidateMetrics();
updatePrefViewportWidth();
});
registerChangeListener(control.prefRowCountProperty(), e -> {
invalidateMetrics();
updatePrefViewportHeight();
});
updateFontMetrics();
fontMetrics.addListener(valueModel -> {
updateFontMetrics();
});
contentView.paddingProperty().addListener(valueModel -> {
updatePrefViewportWidth();
updatePrefViewportHeight();
});
scrollPane.viewportBoundsProperty().addListener(valueModel -> {
if (scrollPane.getViewportBounds() != null) {
// ScrollPane creates a new Bounds instance for each
// layout pass, so we need to check if the width/height
// have really changed to avoid infinite layout requests.
Bounds newViewportBounds = scrollPane.getViewportBounds();
if (oldViewportBounds == null ||
oldViewportBounds.getWidth() != newViewportBounds.getWidth() ||
oldViewportBounds.getHeight() != newViewportBounds.getHeight()) {
invalidateMetrics();
oldViewportBounds = newViewportBounds;
contentView.requestLayout();
}
}
});
registerChangeListener(control.scrollTopProperty(), e -> {
double newValue = control.getScrollTop();
double vValue = (newValue < getScrollTopMax())
? (newValue / getScrollTopMax()) : 1.0;
scrollPane.setVvalue(vValue);
});
registerChangeListener(control.scrollLeftProperty(), e -> {
double newValue = control.getScrollLeft();
double hValue = (newValue < getScrollLeftMax())
? (newValue / getScrollLeftMax()) : 1.0;
scrollPane.setHvalue(hValue);
});
if (USE_MULTIPLE_NODES) {
registerListChangeListener(control.getParagraphs(), change -> {
while (change.next()) {
int from = change.getFrom();
int to = change.getTo();
List<? extends CharSequence> removed = (List<? extends CharSequence>) change.getRemoved();
if (from < to) {
if (removed.isEmpty()) {
// This is an add
for (int i = from, n = to; i < n; i++) {
addParagraphNode(i, change.getList().get(i).toString());
}
} else {
// This is an update
for (int i = from, n = to; i < n; i++) {
Node node = paragraphNodes.getChildren().get(i);
Text paragraphNode = (Text) node;
paragraphNode.setText(change.getList().get(i).toString());
}
}
} else {
// This is a remove
paragraphNodes.getChildren().subList(from, from + removed.size()).clear();
}
}
});
} else {
registerInvalidationListener(control.textProperty(), e -> {
invalidateMetrics();
((Text)paragraphNodes.getChildren().get(0)).setText(control.textProperty().getValueSafe());
contentView.requestLayout();
});
}
usePromptText = new BooleanBinding() {
{ bind(control.textProperty(), control.promptTextProperty()); }
@Override protected boolean computeValue() {
String txt = control.getText();
String promptTxt = control.getPromptText();
return ((txt == null || txt.isEmpty()) &&
promptTxt != null && !promptTxt.isEmpty());
}
};
if (usePromptText.get()) {
createPromptNode();
}
registerInvalidationListener(usePromptText, e -> {
createPromptNode();
control.requestLayout();
});
updateHighlightFill();
updatePrefViewportWidth();
updatePrefViewportHeight();
if (control.isFocused()) setCaretAnimating(true);
if (SHOW_HANDLES) {
selectionHandle1.setRotate(180);
EventHandler<MouseEvent> handlePressHandler = e -> {
pressX = e.getX();
pressY = e.getY();
handlePressed = true;
e.consume();
};
EventHandler<MouseEvent> handleReleaseHandler = event -> {
handlePressed = false;
};
caretHandle.setOnMousePressed(handlePressHandler);
selectionHandle1.setOnMousePressed(handlePressHandler);
selectionHandle2.setOnMousePressed(handlePressHandler);
caretHandle.setOnMouseReleased(handleReleaseHandler);
selectionHandle1.setOnMouseReleased(handleReleaseHandler);
selectionHandle2.setOnMouseReleased(handleReleaseHandler);
caretHandle.setOnMouseDragged(e -> {
Text textNode = getTextNode();
Point2D tp = textNode.localToScene(0, 0);
Point2D p = new Point2D(e.getSceneX() - tp.getX() - pressX + caretHandle.getWidth() / 2,
e.getSceneY() - tp.getY() - pressY - 6);
HitInfo hit = textNode.hitTest(translateCaretPosition(p));
positionCaret(hit, false);
e.consume();
});
selectionHandle1.setOnMouseDragged(e -> {
TextArea control1 = getSkinnable();
Text textNode = getTextNode();
Point2D tp = textNode.localToScene(0, 0);
Point2D p = new Point2D(e.getSceneX() - tp.getX() - pressX + selectionHandle1.getWidth() / 2,
e.getSceneY() - tp.getY() - pressY + selectionHandle1.getHeight() + 5);
HitInfo hit = textNode.hitTest(translateCaretPosition(p));
if (control1.getAnchor() < control1.getCaretPosition()) {
// Swap caret and anchor
control1.selectRange(control1.getCaretPosition(), control1.getAnchor());
}
int pos = hit.getCharIndex();
if (pos > 0) {
if (pos >= control1.getAnchor()) {
pos = control1.getAnchor();
}
}
positionCaret(hit, true);
e.consume();
});
selectionHandle2.setOnMouseDragged(e -> {
TextArea control1 = getSkinnable();
Text textNode = getTextNode();
Point2D tp = textNode.localToScene(0, 0);
Point2D p = new Point2D(e.getSceneX() - tp.getX() - pressX + selectionHandle2.getWidth() / 2,
e.getSceneY() - tp.getY() - pressY - 6);
HitInfo hit = textNode.hitTest(translateCaretPosition(p));
if (control1.getAnchor() > control1.getCaretPosition()) {
// Swap caret and anchor
control1.selectRange(control1.getCaretPosition(), control1.getAnchor());
}
int pos = hit.getCharIndex();
if (pos > 0) {
if (pos <= control1.getAnchor() + 1) {
pos = Math.min(control1.getAnchor() + 2, control1.getLength());
}
positionCaret(hit, true);
}
e.consume();
});
}
}
/* *************************************************************************
* *
* Public API *
* *
**************************************************************************/
/** {@inheritDoc} */
@Override protected void invalidateMetrics() {
computedMinWidth = Double.NEGATIVE_INFINITY;
computedMinHeight = Double.NEGATIVE_INFINITY;
computedPrefWidth = Double.NEGATIVE_INFINITY;
computedPrefHeight = Double.NEGATIVE_INFINITY;
}
/** {@inheritDoc} */
@Override protected void layoutChildren(double contentX, double contentY, double contentWidth, double contentHeight) {
scrollPane.resizeRelocate(contentX, contentY, contentWidth, contentHeight);
}
/** {@inheritDoc} */
@Override protected void updateHighlightFill() {
for (Node node : selectionHighlightGroup.getChildren()) {
Path selectionHighlightPath = (Path)node;
selectionHighlightPath.setFill(highlightFillProperty().get());
}
}
// Public for behavior
/**
* Performs a hit test, mapping point to index in the content.
*
* @param x the x coordinate of the point.
* @param y the y coordinate of the point.
* @return a {@code HitInfo} object describing the index and forward bias.
*/
public HitInfo getIndex(double x, double y) {
// adjust the event to be in the same coordinate space as the
// text content of the textInputControl
Text textNode = getTextNode();
Point2D p = new Point2D(x - textNode.getLayoutX(), y - getTextTranslateY());
HitInfo hit = textNode.hitTest(translateCaretPosition(p));
return hit;
};
/** {@inheritDoc} */
@Override public void moveCaret(TextUnit unit, Direction dir, boolean select) {
switch (unit) {
case CHARACTER:
switch (dir) {
case LEFT:
case RIGHT:
nextCharacterVisually(dir == Direction.RIGHT);
break;
default:
throw new IllegalArgumentException(""+dir);
}
break;
case LINE:
switch (dir) {
case UP:
previousLine(select);
break;
case DOWN:
nextLine(select);
break;
case BEGINNING:
lineStart(select, select && isMac());
break;
case END:
lineEnd(select, select && isMac());
break;
default:
throw new IllegalArgumentException(""+dir);
}
break;
case PAGE:
switch (dir) {
case UP:
previousPage(select);
break;
case DOWN:
nextPage(select);
break;
default:
throw new IllegalArgumentException(""+dir);
}
break;
case PARAGRAPH:
switch (dir) {
case UP:
paragraphStart(true, select);
break;
case DOWN:
paragraphEnd(true, select);
break;
case BEGINNING:
paragraphStart(false, select);
break;
case END:
paragraphEnd(false, select);
break;
default:
throw new IllegalArgumentException(""+dir);
}
break;
default:
throw new IllegalArgumentException(""+unit);
}
}
private void nextCharacterVisually(boolean moveRight) {
if (isRTL()) {
// Text node is mirrored.
moveRight = !moveRight;
}
Text textNode = getTextNode();
Bounds caretBounds = caretPath.getLayoutBounds();
if (caretPath.getElements().size() == 4) {
// The caret is split
// TODO: Find a better way to get the primary caret position
// instead of depending on the internal implementation.
// See RT-25465.
caretBounds = new Path(caretPath.getElements().get(0), caretPath.getElements().get(1)).getLayoutBounds();
}
double hitX = moveRight ? caretBounds.getMaxX() : caretBounds.getMinX();
double hitY = (caretBounds.getMinY() + caretBounds.getMaxY()) / 2;
HitInfo hit = textNode.hitTest(new Point2D(hitX, hitY));
boolean leading = hit.isLeading();
Path charShape = new Path(textNode.rangeShape(hit.getCharIndex(), hit.getCharIndex() + 1));
if ((moveRight && charShape.getLayoutBounds().getMaxX() > caretBounds.getMaxX()) ||
(!moveRight && charShape.getLayoutBounds().getMinX() < caretBounds.getMinX())) {
leading = !leading;
positionCaret(hit.getInsertionIndex(), leading, false, false);
} else {
// We're at beginning or end of line. Try moving up / down.
int dot = textArea.getCaretPosition();
targetCaretX = moveRight ? 0 : Double.MAX_VALUE;
// TODO: Use Bidi sniffing instead of assuming right means forward here?
downLines(moveRight ? 1 : -1, false, false);
targetCaretX = -1;
if (dot == textArea.getCaretPosition()) {
if (moveRight) {
textArea.forward();
} else {
textArea.backward();
}
}
}
}
private void downLines(int nLines, boolean select, boolean extendSelection) {
Text textNode = getTextNode();
Bounds caretBounds = caretPath.getLayoutBounds();
// The middle y coordinate of the the line we want to go to.
double targetLineMidY = (caretBounds.getMinY() + caretBounds.getMaxY()) / 2 + nLines * lineHeight;
if (targetLineMidY < 0) {
targetLineMidY = 0;
}
// The target x for the caret. This may have been set during a
// previous call.
double x = (targetCaretX >= 0) ? targetCaretX : (caretBounds.getMaxX());
// Find a text position for the target x,y.
HitInfo hit = textNode.hitTest(translateCaretPosition(new Point2D(x, targetLineMidY)));
int pos = hit.getCharIndex();
// Save the old pos temporarily while testing the new one.
int oldPos = textNode.getCaretPosition();
boolean oldBias = textNode.isCaretBias();
textNode.setCaretBias(hit.isLeading());
textNode.setCaretPosition(pos);
tmpCaretPath.getElements().clear();
tmpCaretPath.getElements().addAll(textNode.getCaretShape());
tmpCaretPath.setLayoutX(textNode.getLayoutX());
tmpCaretPath.setLayoutY(textNode.getLayoutY());
Bounds tmpCaretBounds = tmpCaretPath.getLayoutBounds();
// The y for the middle of the row we found.
double foundLineMidY = (tmpCaretBounds.getMinY() + tmpCaretBounds.getMaxY()) / 2;
textNode.setCaretBias(oldBias);
textNode.setCaretPosition(oldPos);
// Test if the found line is in the correct direction and move
// the caret.
if (nLines == 0 ||
(nLines > 0 && foundLineMidY > caretBounds.getMaxY()) ||
(nLines < 0 && foundLineMidY < caretBounds.getMinY())) {
positionCaret(hit.getInsertionIndex(), hit.isLeading(), select, extendSelection);
targetCaretX = x;
}
}
private void previousLine(boolean select) {
downLines(-1, select, false);
}
private void nextLine(boolean select) {
downLines(1, select, false);
}
private void previousPage(boolean select) {
downLines(-(int)(scrollPane.getViewportBounds().getHeight() / lineHeight),
select, false);
}
private void nextPage(boolean select) {
downLines((int)(scrollPane.getViewportBounds().getHeight() / lineHeight),
select, false);
}
private void lineStart(boolean select, boolean extendSelection) {
targetCaretX = 0;
downLines(0, select, extendSelection);
targetCaretX = -1;
}
private void lineEnd(boolean select, boolean extendSelection) {
targetCaretX = Double.MAX_VALUE;
downLines(0, select, extendSelection);
targetCaretX = -1;
}
private void paragraphStart(boolean previousIfAtStart, boolean select) {
TextArea textArea = getSkinnable();
String text = textArea.textProperty().getValueSafe();
int pos = textArea.getCaretPosition();
if (pos > 0) {
if (previousIfAtStart && text.codePointAt(pos-1) == 0x0a) {
// We are at the beginning of a paragraph.
// Back up to the previous paragraph.
pos--;
}
// Back up to the beginning of this paragraph
while (pos > 0 && text.codePointAt(pos-1) != 0x0a) {
pos--;
}
if (select) {
textArea.selectPositionCaret(pos);
} else {
textArea.positionCaret(pos);
setForwardBias(true);
}
}
}
private void paragraphEnd(boolean goPastInitialNewline, boolean select) {
TextArea textArea = getSkinnable();
String text = textArea.textProperty().getValueSafe();
int pos = textArea.getCaretPosition();
int len = text.length();
boolean wentPastInitialNewline = false;
boolean goPastTrailingNewline = isWindows();
if (pos < len) {
if (goPastInitialNewline && text.codePointAt(pos) == 0x0a) {
// We are at the end of a paragraph, start by moving to the
// next paragraph.
pos++;
wentPastInitialNewline = true;
}
if (!(goPastTrailingNewline && wentPastInitialNewline)) {
// Go to the end of this paragraph
while (pos < len && text.codePointAt(pos) != 0x0a) {
pos++;
}
if (goPastTrailingNewline && pos < len) {
// We are at the end of a paragraph, finish by moving to
// the beginning of the next paragraph (Windows behavior).
pos++;
}
}
if (select) {
textArea.selectPositionCaret(pos);
} else {
textArea.positionCaret(pos);
}
}
}
/** {@inheritDoc} */
@Override protected PathElement[] getUnderlineShape(int start, int end) {
int pStart = 0;
for (Node node : paragraphNodes.getChildren()) {
Text p = (Text)node;
int pEnd = pStart + p.textProperty().getValueSafe().length();
if (pEnd >= start) {
return p.underlineShape(start - pStart, end - pStart);
}
pStart = pEnd + 1;
}
return null;
}
/** {@inheritDoc} */
@Override protected PathElement[] getRangeShape(int start, int end) {
int pStart = 0;
for (Node node : paragraphNodes.getChildren()) {
Text p = (Text)node;
int pEnd = pStart + p.textProperty().getValueSafe().length();
if (pEnd >= start) {
return p.rangeShape(start - pStart, end - pStart);
}
pStart = pEnd + 1;
}
return null;
}
/** {@inheritDoc} */
@Override protected void addHighlight(List<? extends Node> nodes, int start) {
int pStart = 0;
Text paragraphNode = null;
for (Node node : paragraphNodes.getChildren()) {
Text p = (Text)node;
int pEnd = pStart + p.textProperty().getValueSafe().length();
if (pEnd >= start) {
paragraphNode = p;
break;
}
pStart = pEnd + 1;
}
if (paragraphNode != null) {
for (Node node : nodes) {
node.setLayoutX(paragraphNode.getLayoutX());
node.setLayoutY(paragraphNode.getLayoutY());
}
}
contentView.getChildren().addAll(nodes);
}
/** {@inheritDoc} */
@Override protected void removeHighlight(List<? extends Node> nodes) {
contentView.getChildren().removeAll(nodes);
}
/** {@inheritDoc} */
@Override public Point2D getMenuPosition() {
contentView.layoutChildren();
Point2D p = super.getMenuPosition();
if (p != null) {
p = new Point2D(Math.max(0, p.getX() - contentView.snappedLeftInset() - getSkinnable().getScrollLeft()),
Math.max(0, p.getY() - contentView.snappedTopInset() - getSkinnable().getScrollTop()));
}
return p;
}
// Public for FXVKSkin
/**
* Gets the {@code Bounds} of the caret of the skinned {@code TextArea}.
* @return the {@code Bounds} of the caret shape, relative to the {@code TextArea}.
*/
public Bounds getCaretBounds() {
return getSkinnable().sceneToLocal(caretPath.localToScene(caretPath.getBoundsInLocal()));
}
/** {@inheritDoc} */
@Override protected Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) {
switch (attribute) {
case LINE_FOR_OFFSET:
case LINE_START:
case LINE_END:
case BOUNDS_FOR_RANGE:
case OFFSET_AT_POINT:
Text text = getTextNode();
return text.queryAccessibleAttribute(attribute, parameters);
default: return super.queryAccessibleAttribute(attribute, parameters);
}
}
/** {@inheritDoc} */
@Override public void dispose() {
if (getSkinnable() == null) return;
getSkinnable().removeEventFilter(ScrollEvent.ANY, scrollEventFilter);
getChildren().remove(scrollPane);
super.dispose();
if (behavior != null) {
behavior.dispose();
}
}
/** {@inheritDoc} */
@Override public double computeBaselineOffset(double topInset, double rightInset, double bottomInset, double leftInset) {
Text firstParagraph = (Text) paragraphNodes.getChildren().get(0);
return Utils.getAscent(getSkinnable().getFont(), firstParagraph.getBoundsType())
+ contentView.snappedTopInset() + textArea.snappedTopInset();
}
private char getCharacter(int index) {
int n = paragraphNodes.getChildren().size();
int paragraphIndex = 0;
int offset = index;
String paragraph = null;
while (paragraphIndex < n) {
Text paragraphNode = (Text)paragraphNodes.getChildren().get(paragraphIndex);
paragraph = paragraphNode.getText();
int count = paragraph.length() + 1;
if (offset < count) {
break;
}
offset -= count;
paragraphIndex++;
}
return offset == paragraph.length() ? '\n' : paragraph.charAt(offset);
}
/** {@inheritDoc} */
@Override protected int getInsertionPoint(double x, double y) {
TextArea textArea = getSkinnable();
int n = paragraphNodes.getChildren().size();
int index = -1;
if (n > 0) {
if (y < contentView.snappedTopInset()) {
// Select the character at x in the first row
Text paragraphNode = (Text)paragraphNodes.getChildren().get(0);
index = getNextInsertionPoint(paragraphNode, x, -1, VerticalDirection.DOWN);
} else if (y > contentView.snappedTopInset() + contentView.getHeight()) {
// Select the character at x in the last row
int lastParagraphIndex = n - 1;
Text lastParagraphView = (Text)paragraphNodes.getChildren().get(lastParagraphIndex);
index = getNextInsertionPoint(lastParagraphView, x, -1, VerticalDirection.UP)
+ (textArea.getLength() - lastParagraphView.getText().length());
} else {
// Select the character at x in the row at y
int paragraphOffset = 0;
for (int i = 0; i < n; i++) {
Text paragraphNode = (Text)paragraphNodes.getChildren().get(i);
Bounds bounds = paragraphNode.getBoundsInLocal();
double paragraphViewY = paragraphNode.getLayoutY() + bounds.getMinY();
if (y >= paragraphViewY
&& y < paragraphViewY + paragraphNode.getBoundsInLocal().getHeight()) {
index = getInsertionPoint(paragraphNode,
x - paragraphNode.getLayoutX(),
y - paragraphNode.getLayoutY()) + paragraphOffset;
break;
}
paragraphOffset += paragraphNode.getText().length() + 1;
}
}
}
return index;
}
// Public for behavior
/**
* Moves the caret to the specified position.
*
* @param hit the new position and forward bias of the caret.
* @param select whether to extend selection to the new position.
*/
public void positionCaret(HitInfo hit, boolean select) {
positionCaret(hit.getInsertionIndex(), hit.isLeading(), select, false);
}
private void positionCaret(int pos, boolean leading, boolean select, boolean extendSelection) {
boolean isNewLine =
(pos > 0 &&
pos <= getSkinnable().getLength() &&
getSkinnable().getText().codePointAt(pos-1) == 0x0a);
// special handling for a new line
if (!leading && isNewLine) {
leading = true;
pos -= 1;
}
if (select) {
if (extendSelection) {
getSkinnable().extendSelection(pos);
} else {
getSkinnable().selectPositionCaret(pos);
}
} else {
getSkinnable().positionCaret(pos);
}
setForwardBias(leading);
}
/** {@inheritDoc} */
@Override public Rectangle2D getCharacterBounds(int index) {
TextArea textArea = getSkinnable();
int paragraphIndex = paragraphNodes.getChildren().size();
int paragraphOffset = textArea.getLength() + 1;
Text paragraphNode = null;
do {
paragraphNode = (Text)paragraphNodes.getChildren().get(--paragraphIndex);
paragraphOffset -= paragraphNode.getText().length() + 1;
} while (index < paragraphOffset);
int characterIndex = index - paragraphOffset;
boolean terminator = false;
if (characterIndex == paragraphNode.getText().length()) {
characterIndex--;
terminator = true;
}
characterBoundingPath.getElements().clear();
characterBoundingPath.getElements().addAll(paragraphNode.rangeShape(characterIndex, characterIndex + 1));
characterBoundingPath.setLayoutX(paragraphNode.getLayoutX());
characterBoundingPath.setLayoutY(paragraphNode.getLayoutY());
Bounds bounds = characterBoundingPath.getBoundsInLocal();
double x = bounds.getMinX() + paragraphNode.getLayoutX() - textArea.getScrollLeft();
double y = bounds.getMinY() + paragraphNode.getLayoutY() - textArea.getScrollTop();
// Sometimes the bounds is empty, in which case we must ignore the width/height
double width = bounds.isEmpty() ? 0 : bounds.getWidth();
double height = bounds.isEmpty() ? 0 : bounds.getHeight();
if (terminator) {
x += width;
width = 0;
}
return new Rectangle2D(x, y, width, height);
}
/** {@inheritDoc} */
@Override protected void scrollCharacterToVisible(final int index) {
// TODO We queue a callback because when characters are added or
// removed the bounds are not immediately updated; is this really
// necessary?