-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathStyledTextArea.java
1215 lines (1053 loc) · 50.7 KB
/
StyledTextArea.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
package org.fxmisc.richtext;
import static org.fxmisc.richtext.PopupAlignment.*;
import static org.reactfx.EventStreams.*;
import static org.reactfx.util.Tuples.*;
import java.time.Duration;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.IntSupplier;
import java.util.function.IntUnaryOperator;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import javafx.beans.binding.Binding;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableBooleanValue;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.css.PseudoClass;
import javafx.css.StyleableObjectProperty;
import javafx.event.Event;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.IndexRange;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.PopupWindow;
import org.fxmisc.flowless.Cell;
import org.fxmisc.flowless.VirtualFlow;
import org.fxmisc.flowless.VirtualFlowHit;
import org.fxmisc.flowless.Virtualized;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CssProperties.EditableProperty;
import org.fxmisc.undo.UndoManager;
import org.fxmisc.undo.UndoManagerFactory;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import org.reactfx.StateMachine;
import org.reactfx.Subscription;
import org.reactfx.collection.LiveList;
import org.reactfx.util.Tuple2;
import org.reactfx.value.Val;
import org.reactfx.value.Var;
/**
* Text editing control. Accepts user input (keyboard, mouse) and
* provides API to assign style to text ranges. It is suitable for
* syntax highlighting and rich-text editors.
*
* <p>Subclassing is allowed to define the type of style, e.g. inline
* style or style classes.</p>
*
* <p>Note: Scroll bars no longer appear when the content spans outside
* of the viewport. To add scroll bars, the area needs to be embedded in
* a {@link VirtualizedScrollPane}. {@link AreaFactory} is provided to make
* this more convenient.</p>
*
* <h3>Overriding keyboard shortcuts</h3>
*
* {@code StyledTextArea} comes with {@link #onKeyTypedProperty()} and
* {@link #onKeyPressedProperty()} handlers installed to handle keyboard input.
* Ordinary character input is handled by the {@code onKeyTyped} handler and
* control key combinations (including Enter and Tab) are handled by the
* {@code onKeyPressed} handler. To add or override some keyboard shortcuts,
* but keep the rest in place, you would combine the default event handler with
* a new one that adds or overrides some of the default key combinations. This
* is how to bind {@code Ctrl+S} to the {@code save()} operation:
* <pre>
* {@code
* import static javafx.scene.input.KeyCode.*;
* import static javafx.scene.input.KeyCombination.*;
* import static org.fxmisc.wellbehaved.event.EventPattern.*;
*
* import org.fxmisc.wellbehaved.event.EventHandlerHelper;
*
* EventHandler<? super KeyEvent> ctrlS = EventHandlerHelper
* .on(keyPressed(S, CONTROL_DOWN)).act(event -> save())
* .create();
*
* EventHandlerHelper.install(area.onKeyPressedProperty(), ctrlS);
* }
* </pre>
*
* @param <S> type of style that can be applied to text.
*/
public class StyledTextArea<PS, S> extends Region
implements
TextEditingArea<PS, S>,
EditActions<PS, S>,
ClipboardActions<PS, S>,
NavigationActions<PS, S>,
UndoActions,
TwoDimensional,
Virtualized {
/**
* Index range [0, 0).
*/
public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0);
private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret");
private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph");
private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph");
/* ********************************************************************** *
* *
* Properties *
* *
* Properties affect behavior and/or appearance of this control. *
* *
* They are readable and writable by the client code and never change by *
* other means, i.e. they contain either the default value or the value *
* set by the client code. *
* *
* ********************************************************************** */
/**
* Background fill for highlighted text.
*/
private final StyleableObjectProperty<Paint> highlightFill
= new CssProperties.HighlightFillProperty(this, Color.DODGERBLUE);
/**
* Text color for highlighted text.
*/
private final StyleableObjectProperty<Paint> highlightTextFill
= new CssProperties.HighlightTextFillProperty(this, Color.WHITE);
// editable property
/**
* Indicates whether this text area can be edited by the user.
* Note that this property doesn't affect editing through the API.
*/
private final BooleanProperty editable = new EditableProperty<>(this);
public final boolean isEditable() { return editable.get(); }
public final void setEditable(boolean value) { editable.set(value); }
public final BooleanProperty editableProperty() { return editable; }
// wrapText property
/**
* When a run of text exceeds the width of the text region,
* then this property indicates whether the text should wrap
* onto another line.
*/
private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText");
public final boolean isWrapText() { return wrapText.get(); }
public final void setWrapText(boolean value) { wrapText.set(value); }
public final BooleanProperty wrapTextProperty() { return wrapText; }
// undo manager
@Override public UndoManager getUndoManager() { return model.getUndoManager(); }
@Override public void setUndoManager(UndoManagerFactory undoManagerFactory) {
model.setUndoManager(undoManagerFactory);
}
/**
* Popup window that will be positioned by this text area relative to the
* caret or selection. Use {@link #popupAlignmentProperty()} to specify
* how the popup should be positioned relative to the caret or selection.
* Use {@link #popupAnchorOffsetProperty()} or
* {@link #popupAnchorAdjustmentProperty()} to further adjust the position.
*/
private final ObjectProperty<PopupWindow> popupWindow = new SimpleObjectProperty<>();
public void setPopupWindow(PopupWindow popup) { popupWindow.set(popup); }
public PopupWindow getPopupWindow() { return popupWindow.get(); }
public ObjectProperty<PopupWindow> popupWindowProperty() { return popupWindow; }
/** @deprecated Use {@link #setPopupWindow(PopupWindow)}. */
@Deprecated
public void setPopupAtCaret(PopupWindow popup) { popupWindow.set(popup); }
/** @deprecated Use {@link #getPopupWindow()}. */
@Deprecated
public PopupWindow getPopupAtCaret() { return popupWindow.get(); }
/** @deprecated Use {@link #popupWindowProperty()}. */
@Deprecated
public ObjectProperty<PopupWindow> popupAtCaretProperty() { return popupWindow; }
/**
* Specifies further offset (in pixels) of the popup window from the
* position specified by {@link #popupAlignmentProperty()}.
*
* <p>If {@link #popupAnchorAdjustmentProperty()} is also specified, then
* it overrides the offset set by this property.
*/
private final ObjectProperty<Point2D> popupAnchorOffset = new SimpleObjectProperty<>();
public void setPopupAnchorOffset(Point2D offset) { popupAnchorOffset.set(offset); }
public Point2D getPopupAnchorOffset() { return popupAnchorOffset.get(); }
public ObjectProperty<Point2D> popupAnchorOffsetProperty() { return popupAnchorOffset; }
/**
* Specifies how to adjust the popup window's anchor point. The given
* operator is invoked with the screen position calculated according to
* {@link #popupAlignmentProperty()} and should return a new screen
* position. This position will be used as the popup window's anchor point.
*
* <p>Setting this property overrides {@link #popupAnchorOffsetProperty()}.
*/
private final ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustment = new SimpleObjectProperty<>();
public void setPopupAnchorAdjustment(UnaryOperator<Point2D> f) { popupAnchorAdjustment.set(f); }
public UnaryOperator<Point2D> getPopupAnchorAdjustment() { return popupAnchorAdjustment.get(); }
public ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustmentProperty() { return popupAnchorAdjustment; }
/**
* Defines where the popup window given in {@link #popupWindowProperty()}
* is anchored, i.e. where its anchor point is positioned. This position
* can further be adjusted by {@link #popupAnchorOffsetProperty()} or
* {@link #popupAnchorAdjustmentProperty()}.
*/
private final ObjectProperty<PopupAlignment> popupAlignment = new SimpleObjectProperty<>(CARET_TOP);
public void setPopupAlignment(PopupAlignment pos) { popupAlignment.set(pos); }
public PopupAlignment getPopupAlignment() { return popupAlignment.get(); }
public ObjectProperty<PopupAlignment> popupAlignmentProperty() { return popupAlignment; }
/**
* Defines how long the mouse has to stay still over the text before a
* {@link MouseOverTextEvent} of type {@code MOUSE_OVER_TEXT_BEGIN} is
* fired on this text area. When set to {@code null}, no
* {@code MouseOverTextEvent}s are fired on this text area.
*
* <p>Default value is {@code null}.
*/
private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null);
public void setMouseOverTextDelay(Duration delay) { mouseOverTextDelay.set(delay); }
public Duration getMouseOverTextDelay() { return mouseOverTextDelay.get(); }
public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; }
/**
* Defines how to handle an event in which the user has selected some text, dragged it to a
* new location within the area, and released the mouse at some character {@code index}
* within the area.
*
* <p>By default, this will relocate the selected text to the character index where the mouse
* was released. To override it, use {@link #setOnSelectionDrop(IntConsumer)}.
*/
private Property<IntConsumer> onSelectionDrop = new SimpleObjectProperty<>(this::moveSelectedText);
public final void setOnSelectionDrop(IntConsumer consumer) { onSelectionDrop.setValue(consumer); }
public final IntConsumer getOnSelectionDrop() { return onSelectionDrop.getValue(); }
private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null);
public void setParagraphGraphicFactory(IntFunction<? extends Node> factory) { paragraphGraphicFactory.set(factory); }
public IntFunction<? extends Node> getParagraphGraphicFactory() { return paragraphGraphicFactory.get(); }
public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; }
/**
* Indicates whether the initial style should also be used for plain text
* inserted into this text area. When {@code false}, the style immediately
* preceding the insertion position is used. Default value is {@code false}.
*/
public BooleanProperty useInitialStyleForInsertionProperty() { return model.useInitialStyleForInsertionProperty(); }
public void setUseInitialStyleForInsertion(boolean value) { model.setUseInitialStyleForInsertion(value); }
public boolean getUseInitialStyleForInsertion() { return model.getUseInitialStyleForInsertion(); }
private Optional<Tuple2<Codec<PS>, Codec<S>>> styleCodecs = Optional.empty();
/**
* Sets codecs to encode/decode style information to/from binary format.
* Providing codecs enables clipboard actions to retain the style information.
*/
public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<S> textStyleCodec) {
styleCodecs = Optional.of(t(paragraphStyleCodec, textStyleCodec));
}
@Override
public Optional<Tuple2<Codec<PS>, Codec<S>>> getStyleCodecs() {
return styleCodecs;
}
/**
* The <em>estimated</em> scrollX value. This can be set in order to scroll the content.
* Value is only accurate when area does not wrap lines and uses the same font size
* throughout the entire area.
*/
@Override
public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); }
public double getEstimatedScrollX() { return virtualFlow.estimatedScrollXProperty().getValue(); }
public void setEstimatedScrollX(double value) { virtualFlow.estimatedScrollXProperty().setValue(value); }
/**
* The <em>estimated</em> scrollY value. This can be set in order to scroll the content.
* Value is only accurate when area does not wrap lines and uses the same font size
* throughout the entire area.
*/
@Override
public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); }
public double getEstimatedScrollY() { return virtualFlow.estimatedScrollYProperty().getValue(); }
public void setEstimatedScrollY(double value) { virtualFlow.estimatedScrollYProperty().setValue(value); }
/* ********************************************************************** *
* *
* Observables *
* *
* Observables are "dynamic" (i.e. changing) characteristics of this *
* control. They are not directly settable by the client code, but change *
* in response to user input and/or API actions. *
* *
* ********************************************************************** */
// text
@Override public final String getText() { return model.getText(); }
@Override public final ObservableValue<String> textProperty() { return model.textProperty(); }
// rich text
@Override public final StyledDocument<PS, S> getDocument() { return model.getDocument(); }
// length
@Override public final int getLength() { return model.getLength(); }
@Override public final ObservableValue<Integer> lengthProperty() { return model.lengthProperty(); }
// caret position
@Override public final int getCaretPosition() { return model.getCaretPosition(); }
@Override public final ObservableValue<Integer> caretPositionProperty() { return model.caretPositionProperty(); }
// selection anchor
@Override public final int getAnchor() { return model.getAnchor(); }
@Override public final ObservableValue<Integer> anchorProperty() { return model.anchorProperty(); }
// selection
@Override public final IndexRange getSelection() { return model.getSelection(); }
@Override public final ObservableValue<IndexRange> selectionProperty() { return model.selectionProperty(); }
// selected text
@Override public final String getSelectedText() { return model.getSelectedText(); }
@Override public final ObservableValue<String> selectedTextProperty() { return model.selectedTextProperty(); }
// current paragraph index
@Override public final int getCurrentParagraph() { return model.getCurrentParagraph(); }
@Override public final ObservableValue<Integer> currentParagraphProperty() { return model.currentParagraphProperty(); }
// caret column
@Override public final int getCaretColumn() { return model.getCaretColumn(); }
@Override public final ObservableValue<Integer> caretColumnProperty() { return model.caretColumnProperty(); }
// paragraphs
@Override public LiveList<Paragraph<PS, S>> getParagraphs() { return model.getParagraphs(); }
// beingUpdated
public ObservableBooleanValue beingUpdatedProperty() { return model.beingUpdatedProperty(); }
public boolean isBeingUpdated() { return model.isBeingUpdated(); }
// total width estimate
/**
* The <em>estimated</em> width of the entire document. Accurate when area does not wrap lines and
* uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by
* the skin, not the user.
*/
@Override
public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); }
public double getTotalWidthEstimate() { return virtualFlow.totalWidthEstimateProperty().getValue(); }
// total height estimate
/**
* The <em>estimated</em> height of the entire document. Accurate when area does not wrap lines and
* uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by
* the skin, not the user.
*/
@Override
public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); }
public double getTotalHeightEstimate() { return virtualFlow.totalHeightEstimateProperty().getValue(); }
/* ********************************************************************** *
* *
* Event streams *
* *
* ********************************************************************** */
// text changes
@Override public final EventStream<PlainTextChange> plainTextChanges() { return model.plainTextChanges(); }
// rich text changes
@Override public final EventStream<RichTextChange<PS, S>> richChanges() { return model.richChanges(); }
/* ********************************************************************** *
* *
* Private fields *
* *
* ********************************************************************** */
private final StyledTextAreaBehavior behavior;
private Subscription subscriptions = () -> {};
private final Binding<Boolean> caretVisible;
private final Val<UnaryOperator<Point2D>> _popupAnchorAdjustment;
private final VirtualFlow<Paragraph<PS, S>, Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> virtualFlow;
// used for two-level navigation, where on the higher level are
// paragraphs and on the lower level are lines within a paragraph
private final TwoLevelNavigator navigator;
private boolean followCaretRequested = false;
/**
* model
*/
private final StyledTextAreaModel<PS, S> model;
/**
* @return this area's {@link StyledTextAreaModel}
*/
final StyledTextAreaModel<PS, S> getModel() {
return model;
}
/* ********************************************************************** *
* *
* Fields necessary for Cloning *
* *
* ********************************************************************** */
/**
* The underlying document that can be displayed by multiple {@code StyledTextArea}s.
*/
public final EditableStyledDocument<PS, S> getContent() { return model.getContent(); }
/**
* Style used by default when no other style is provided.
*/
public final S getInitialTextStyle() { return model.getInitialTextStyle(); }
/**
* Style used by default when no other style is provided.
*/
public final PS getInitialParagraphStyle() { return model.getInitialParagraphStyle(); }
/**
* Style applicator used by the default skin.
*/
private final BiConsumer<? super TextExt, S> applyStyle;
public final BiConsumer<? super TextExt, S> getApplyStyle() { return applyStyle; }
/**
* Style applicator used by the default skin.
*/
private final BiConsumer<TextFlow, PS> applyParagraphStyle;
public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; }
/**
* Indicates whether style should be preserved on undo/redo,
* copy/paste and text move.
* TODO: Currently, only undo/redo respect this flag.
*/
public final boolean isPreserveStyle() { return model.isPreserveStyle(); }
/* ********************************************************************** *
* *
* Constructors *
* *
* ********************************************************************** */
/**
* Creates a text area with empty text content.
*
* @param initialTextStyle style to use in places where no other style is
* specified (yet).
* @param applyStyle function that, given a {@link Text} node and
* a style, applies the style to the text node. This function is
* used by the default skin to apply style to text nodes.
* @param initialParagraphStyle style to use in places where no other style is
* specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
*/
public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle
) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, true);
}
public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle,
boolean preserveStyle
) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle,
new EditableStyledDocumentImpl<>(initialParagraphStyle, initialTextStyle), preserveStyle);
}
/**
* The same as {@link #StyledTextArea(Object, BiConsumer, Object, BiConsumer)} except that
* this constructor can be used to create another {@code StyledTextArea} object that
* shares the same {@link EditableStyledDocument}.
*/
public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle,
EditableStyledDocument<PS, S> document
) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, document, true);
}
public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle,
S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle,
EditableStyledDocument<PS, S> document, boolean preserveStyle
) {
this.model = new StyledTextAreaModel<>(initialParagraphStyle, initialTextStyle, document, preserveStyle);
this.applyStyle = applyStyle;
this.applyParagraphStyle = applyParagraphStyle;
// allow tab traversal into area
setFocusTraversable(true);
this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
getStyleClass().add("styled-text-area");
getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm());
// keeps track of currently used non-empty cells
@SuppressWarnings("unchecked")
ObservableSet<ParagraphBox<PS, S>> nonEmptyCells = FXCollections.observableSet();
// Initialize content
virtualFlow = VirtualFlow.createVertical(
getParagraphs(),
par -> {
Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = createCell(
par,
applyStyle,
applyParagraphStyle);
nonEmptyCells.add(cell.getNode());
return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode()))
.afterUpdateItem(p -> nonEmptyCells.add(cell.getNode()));
});
getChildren().add(virtualFlow);
// initialize navigator
IntSupplier cellCount = () -> getParagraphs().size();
IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount();
navigator = new TwoLevelNavigator(cellCount, cellLength);
// follow the caret every time the caret position or paragraphs change
EventStream<?> caretPosDirty = invalidationsOf(caretPositionProperty());
EventStream<?> paragraphsDirty = invalidationsOf(getParagraphs());
EventStream<?> selectionDirty = invalidationsOf(selectionProperty());
// need to reposition popup even when caret hasn't moved, but selection has changed (been deselected)
EventStream<?> caretDirty = merge(caretPosDirty, paragraphsDirty, selectionDirty);
subscribeTo(caretDirty, x -> requestFollowCaret());
// whether or not to animate the caret
BooleanBinding blinkCaret = focusedProperty()
.and(editableProperty())
.and(disabledProperty().not());
manageBinding(blinkCaret);
// The caret is visible in periodic intervals,
// but only when blinkCaret is true.
caretVisible = EventStreams.valuesOf(blinkCaret)
.flatMap(blink -> blink
? booleanPulse(Duration.ofMillis(500), caretDirty)
: EventStreams.valuesOf(Val.constant(false)))
.toBinding(false);
manageBinding(caretVisible);
// Adjust popup anchor by either a user-provided function,
// or user-provided offset, or don't adjust at all.
Val<UnaryOperator<Point2D>> userOffset = Val.map(
popupAnchorOffsetProperty(),
offset -> anchor -> anchor.add(offset));
_popupAnchorAdjustment =
Val.orElse(
popupAnchorAdjustmentProperty(),
userOffset)
.orElseConst(UnaryOperator.identity());
// dispatch MouseOverTextEvents when mouseOverTextDelay is not null
EventStreams.valuesOf(mouseOverTextDelayProperty())
.flatMap(delay -> delay != null
? mouseOverTextEvents(nonEmptyCells, delay)
: EventStreams.never())
.subscribe(evt -> Event.fireEvent(this, evt));
behavior = new StyledTextAreaBehavior(this);
}
/* ********************************************************************** *
* *
* Queries *
* *
* Queries are parameterized observables. *
* *
* ********************************************************************** */
/**
* Returns caret bounds relative to the viewport, i.e. the visual bounds
* of the embedded VirtualFlow.
*/
Optional<Bounds> getCaretBounds() {
return virtualFlow.getCellIfVisible(getCurrentParagraph())
.map(c -> {
Bounds cellBounds = c.getNode().getCaretBounds();
return virtualFlow.cellToViewport(c, cellBounds);
});
}
/**
* Returns x coordinate of the caret in the current paragraph.
*/
ParagraphBox.CaretOffsetX getCaretOffsetX() {
int idx = getCurrentParagraph();
return getCell(idx).getCaretOffsetX();
}
double getViewportHeight() {
return virtualFlow.getHeight();
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) {
int parIdx = targetLine.getMajor();
ParagraphBox<PS, S> cell = virtualFlow.getCell(parIdx).getNode();
CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor());
return parHit.offset(getParagraphOffset(parIdx));
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) {
VirtualFlowHit<Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> hit = virtualFlow.hit(0.0, y);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hitText(x, cellOffset.getY());
return parHit.offset(parOffset);
}
}
/**
* Helpful for determining which letter is at point x, y:
* <pre>
* {@code
* StyledTextArea area = // creation code
* area.addEventHandler(MouseEvent.MOUSE_PRESSED, (MouseEvent e) -> {
* CharacterHit hit = area.hit(e.getX(), e.getY());
* int characterPosition = hit.getInsertionIndex();
*
* // move the caret to that character's position
* area.moveTo(characterPosition, SelectionPolicy.CLEAR);
* }}
* </pre>
*/
public CharacterHit hit(double x, double y) {
VirtualFlowHit<Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> hit = virtualFlow.hit(x, y);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hit(cellOffset);
return parHit.offset(parOffset);
}
}
/**
* Returns the current line as a two-level index.
* The major number is the paragraph index, the minor
* number is the line number within the paragraph.
*
* <p>This method has a side-effect of bringing the current
* paragraph to the viewport if it is not already visible.
*/
TwoDimensional.Position currentLine() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx);
int lineIdx = cell.getNode().getCurrentLineIndex();
return _position(parIdx, lineIdx);
}
TwoDimensional.Position _position(int par, int line) {
return navigator.position(par, line);
}
@Override
public final String getText(int start, int end) {
return model.getText(start, end);
}
@Override
public String getText(int paragraph) {
return model.getText(paragraph);
}
public Paragraph<PS, S> getParagraph(int index) {
return model.getParagraph(index);
}
@Override
public StyledDocument<PS, S> subDocument(int start, int end) {
return model.subDocument(start, end);
}
@Override
public StyledDocument<PS, S> subDocument(int paragraphIndex) {
return model.subDocument(paragraphIndex);
}
/**
* Returns the selection range in the given paragraph.
*/
public IndexRange getParagraphSelection(int paragraph) {
return model.getParagraphSelection(paragraph);
}
/**
* Returns the style of the character with the given index.
* If {@code index} points to a line terminator character,
* the last style used in the paragraph terminated by that
* line terminator is returned.
*/
public S getStyleOfChar(int index) {
return model.getStyleOfChar(index);
}
/**
* Returns the style at the given position. That is the style of the
* character immediately preceding {@code position}, except when
* {@code position} points to a paragraph boundary, in which case it
* is the style at the beginning of the latter paragraph.
*
* <p>In other words, most of the time {@code getStyleAtPosition(p)}
* is equivalent to {@code getStyleOfChar(p-1)}, except when {@code p}
* points to a paragraph boundary, in which case it is equivalent to
* {@code getStyleOfChar(p)}.
*/
public S getStyleAtPosition(int position) {
return model.getStyleAtPosition(position);
}
/**
* Returns the range of homogeneous style that includes the given position.
* If {@code position} points to a boundary between two styled ranges, then
* the range preceding {@code position} is returned. If {@code position}
* points to a boundary between two paragraphs, then the first styled range
* of the latter paragraph is returned.
*/
public IndexRange getStyleRangeAtPosition(int position) {
return model.getStyleRangeAtPosition(position);
}
/**
* Returns the styles in the given character range.
*/
public StyleSpans<S> getStyleSpans(int from, int to) {
return model.getStyleSpans(from, to);
}
/**
* Returns the styles in the given character range.
*/
public StyleSpans<S> getStyleSpans(IndexRange range) {
return getStyleSpans(range.getStart(), range.getEnd());
}
/**
* Returns the style of the character with the given index in the given
* paragraph. If {@code index} is beyond the end of the paragraph, the
* style at the end of line is returned. If {@code index} is negative, it
* is the same as if it was 0.
*/
public S getStyleOfChar(int paragraph, int index) {
return model.getStyleOfChar(paragraph, index);
}
/**
* Returns the style at the given position in the given paragraph.
* This is equivalent to {@code getStyleOfChar(paragraph, position-1)}.
*/
public S getStyleAtPosition(int paragraph, int position) {
return model.getStyleAtPosition(paragraph, position);
}
/**
* Returns the range of homogeneous style that includes the given position
* in the given paragraph. If {@code position} points to a boundary between
* two styled ranges, then the range preceding {@code position} is returned.
*/
public IndexRange getStyleRangeAtPosition(int paragraph, int position) {
return model.getStyleRangeAtPosition(paragraph, position);
}
/**
* Returns styles of the whole paragraph.
*/
public StyleSpans<S> getStyleSpans(int paragraph) {
return model.getStyleSpans(paragraph);
}
/**
* Returns the styles in the given character range of the given paragraph.
*/
public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) {
return model.getStyleSpans(paragraph, from, to);
}
/**
* Returns the styles in the given character range of the given paragraph.
*/
public StyleSpans<S> getStyleSpans(int paragraph, IndexRange range) {
return getStyleSpans(paragraph, range.getStart(), range.getEnd());
}
@Override
public Position position(int row, int col) {
return model.position(row, col);
}
@Override
public Position offsetToPosition(int charOffset, Bias bias) {
return model.offsetToPosition(charOffset, bias);
}
/* ********************************************************************** *
* *
* Actions *
* *
* Actions change the state of this control. They typically cause a *
* change of one or more observables and/or produce an event. *
* *
* ********************************************************************** */
void scrollBy(Point2D deltas) {
virtualFlow.scrollXBy(deltas.getX());
virtualFlow.scrollYBy(deltas.getY());
}
void show(double y) {
virtualFlow.show(y);
}
void showCaretAtBottom() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds();
double y = caretBounds.getMaxY();
virtualFlow.showAtOffset(parIdx, getViewportHeight() - y);
}
void showCaretAtTop() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds();
double y = caretBounds.getMinY();
virtualFlow.showAtOffset(parIdx, -y);
}
void requestFollowCaret() {
followCaretRequested = true;
requestLayout();
}
private void followCaret() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds();
double graphicWidth = cell.getNode().getGraphicPrefWidth();
Bounds region = extendLeft(caretBounds, graphicWidth);
virtualFlow.show(parIdx, region);
}
/**
* Sets style for the given character range.
*/
public void setStyle(int from, int to, S style) {
model.setStyle(from, to, style);
}
/**
* Sets style for the whole paragraph.
*/
public void setStyle(int paragraph, S style) {
model.setStyle(paragraph, style);
}
/**
* Sets style for the given range relative in the given paragraph.
*/
public void setStyle(int paragraph, int from, int to, S style) {
model.setStyle(paragraph, from, to, style);
}
/**
* Set multiple style ranges at once. This is equivalent to
* <pre>
* for(StyleSpan{@code <S>} span: styleSpans) {
* setStyle(from, from + span.getLength(), span.getStyle());
* from += span.getLength();
* }
* </pre>
* but the actual implementation is more efficient.
*/
public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) {
model.setStyleSpans(from, styleSpans);
}
/**
* Set multiple style ranges of a paragraph at once. This is equivalent to
* <pre>
* for(StyleSpan{@code <S>} span: styleSpans) {
* setStyle(paragraph, from, from + span.getLength(), span.getStyle());
* from += span.getLength();
* }
* </pre>
* but the actual implementation is more efficient.
*/
public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) {
model.setStyleSpans(paragraph, from, styleSpans);
}
/**
* Sets style for the whole paragraph.
*/
public void setParagraphStyle(int paragraph, PS paragraphStyle) {
model.setParagraphStyle(paragraph, paragraphStyle);
}
/**
* Resets the style of the given range to the initial style.
*/
public void clearStyle(int from, int to) {
model.clearStyle(from, to);
}
/**
* Resets the style of the given paragraph to the initial style.
*/
public void clearStyle(int paragraph) {
model.clearStyle(paragraph);
}
/**
* Resets the style of the given range in the given paragraph
* to the initial style.
*/
public void clearStyle(int paragraph, int from, int to) {
model.clearStyle(paragraph, from, to);
}
/**
* Resets the style of the given paragraph to the initial style.
*/
public void clearParagraphStyle(int paragraph) {
model.clearParagraphStyle(paragraph);
}
@Override
public void replaceText(int start, int end, String text) {
model.replaceText(start, end, text);
}
@Override
public void replace(int start, int end, StyledDocument<PS, S> replacement) {
model.replace(start, end, replacement);
}
@Override
public void selectRange(int anchor, int caretPosition) {
model.selectRange(anchor, caretPosition);
}
/**
* {@inheritDoc}
* @deprecated You probably meant to use {@link #moveTo(int)}. This method will be made
* package-private in the future
*/
@Deprecated
@Override
public void positionCaret(int pos) {
model.positionCaret(pos);
}