-
Notifications
You must be signed in to change notification settings - Fork 236
/
GenericStyledArea.java
2157 lines (1861 loc) · 97 KB
/
GenericStyledArea.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.reactfx.EventStreams.*;
import static org.reactfx.util.Tuples.*;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntSupplier;
import java.util.function.IntUnaryOperator;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.beans.NamedArg;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.css.CssMetaData;
import javafx.css.PseudoClass;
import javafx.css.StyleConverter;
import javafx.css.Styleable;
import javafx.css.StyleableObjectProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.IndexRange;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.InputMethodRequests;
import javafx.scene.input.InputMethodTextRun;
import javafx.scene.input.MouseEvent;
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.TextFlow;
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.model.Codec;
import org.fxmisc.richtext.model.EditableStyledDocument;
import org.fxmisc.richtext.model.GenericEditableStyledDocument;
import org.fxmisc.richtext.model.Paragraph;
import org.fxmisc.richtext.model.ReadOnlyStyledDocument;
import org.fxmisc.richtext.model.PlainTextChange;
import org.fxmisc.richtext.model.Replacement;
import org.fxmisc.richtext.model.RichTextChange;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyledDocument;
import org.fxmisc.richtext.model.StyledSegment;
import org.fxmisc.richtext.model.TextOps;
import org.fxmisc.richtext.model.TwoDimensional;
import org.fxmisc.richtext.model.TwoLevelNavigator;
import org.fxmisc.richtext.event.MouseOverTextEvent;
import org.fxmisc.richtext.util.SubscribeableContentsObsSet;
import org.fxmisc.richtext.util.UndoUtils;
import org.fxmisc.undo.UndoManager;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import org.reactfx.Guard;
import org.reactfx.Subscription;
import org.reactfx.Suspendable;
import org.reactfx.SuspendableEventStream;
import org.reactfx.SuspendableNo;
import org.reactfx.collection.LiveList;
import org.reactfx.collection.SuspendableList;
import org.reactfx.util.Tuple2;
import org.reactfx.value.Val;
import org.reactfx.value.Var;
/**
* Text editing control that renders and edits a {@link EditableStyledDocument}.
*
* Accepts user input (keyboard, mouse) and provides API to assign style to text ranges. It is suitable for
* syntax highlighting and rich-text editors.
*
* <h3>Adding Scrollbars to the Area</h3>
*
* <p>By default, scroll bars do not appear when the content spans outside of the viewport.
* To add scroll bars, the area needs to be wrapped in a {@link VirtualizedScrollPane}. For example, </p>
* <pre><code>
* // shows area without scroll bars
* InlineCssTextArea area = new InlineCssTextArea();
*
* // add scroll bars that will display as needed
* VirtualizedScrollPane<InlineCssTextArea> vsPane = new VirtualizedScrollPane<>(area);
*
* Parent parent = // creation code
* parent.getChildren().add(vsPane)
* </code></pre>
*
* <h3>Auto-Scrolling to the Caret</h3>
*
* <p>Every time the underlying {@link EditableStyledDocument} changes via user interaction (e.g. typing) through
* the {@code GenericStyledArea}, the area will scroll to insure the caret is kept in view. However, this does not
* occur if changes are done programmatically. For example, let's say the area is displaying the bottom part
* of the area's {@link EditableStyledDocument} and some code changes something in the top part of the document
* that is not currently visible. If there is no call to {@link #requestFollowCaret()} at the end of that code,
* the area will not auto-scroll to that section of the document. The change will occur, and the user will continue
* to see the bottom part of the document as before. If such a call is there, then the area will scroll
* to the top of the document and no longer display the bottom part of it.</p>
* <p>For example...</p>
* <pre><code>
* // assuming the user is currently seeing the top of the area
*
* // then changing the bottom, currently not visible part of the area...
* int startParIdx = 40;
* int startColPosition = 2;
* int endParIdx = 42;
* int endColPosition = 10;
*
* // ...by itself will not scroll the viewport to where the change occurs
* area.replaceText(startParIdx, startColPosition, endParIdx, endColPosition, "replacement text");
*
* // adding this line after the last modification to the area will cause the viewport to scroll to that change
* // leaving the following line out will leave the viewport unaffected and the user will not notice any difference
* area.requestFollowCaret();
* </code></pre>
*
* <p>Additionally, when overriding the default user-interaction behavior, remember to include a call
* to {@link #requestFollowCaret()}.</p>
*
* <h3>Setting the area's {@link UndoManager}</h3>
*
* <p>
* The default UndoManager can undo/redo either {@link PlainTextChange}s or {@link RichTextChange}s. To create
* your own specialized version that may use changes different than these (or a combination of these changes
* with others), create them using the convenient factory methods in {@link UndoUtils}.
* </p>
*
* <h3>Overriding default keyboard behavior</h3>
*
* {@code GenericStyledArea} uses {@link javafx.scene.input.KeyEvent#KEY_TYPED KEY_TYPED} to handle ordinary
* character input and {@link javafx.scene.input.KeyEvent#KEY_PRESSED KEY_PRESSED} to handle control key
* combinations (including Enter and Tab). To add or override some keyboard
* shortcuts, while keeping 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.
* <p>
* For example, this is how to bind {@code Ctrl+S} to the {@code save()} operation:
* </p>
* <pre><code>
* import static javafx.scene.input.KeyCode.*;
* import static javafx.scene.input.KeyCombination.*;
* import static org.fxmisc.wellbehaved.event.EventPattern.*;
* import static org.fxmisc.wellbehaved.event.InputMap.*;
*
* import org.fxmisc.wellbehaved.event.Nodes;
*
* // installs the following consume InputMap,
* // so that a CTRL+S event saves the document and consumes the event
* Nodes.addInputMap(area, consume(keyPressed(S, CONTROL_DOWN), event -> save()));
* </code></pre>
*
* <h3>Overriding default mouse behavior</h3>
*
* The area's default mouse behavior properly handles auto-scrolling and dragging the selected text to a new location.
* As such, some parts cannot be partially overridden without it affecting other behavior.
*
* <p>The following lists either {@link org.fxmisc.wellbehaved.event.EventPattern}s that cannot be
* overridden without negatively affecting the default mouse behavior or describe how to safely override things
* in a special way without disrupting the auto scroll behavior.</p>
* <ul>
* <li>
* <em>First (1 click count) Primary Button Mouse Pressed Events:</em>
* (<code>EventPattern.mousePressed(MouseButton.PRIMARY).onlyIf(e -> e.getClickCount() == 1)</code>).
* Do not override. Instead, use {@link #onOutsideSelectionMousePressed},
* {@link #onInsideSelectionMousePressReleased}, or see next item.
* </li>
* <li>(
* <em>All Other Mouse Pressed Events (e.g., Primary with 2+ click count):</em>
* Aside from hiding the context menu if it is showing (use {@link #hideContextMenu()} some((where in your
* overriding InputMap to maintain this behavior), these can be safely overridden via any of the
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate InputMapTemplate's factory methods} or
* {@link org.fxmisc.wellbehaved.event.InputMap InputMap's factory methods}.
* </li>
* <li>
* <em>Primary-Button-only Mouse Drag Detection Events:</em>
* (<code>EventPattern.eventType(MouseEvent.DRAG_DETECTED).onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>).
* Do not override. Instead, use {@link #onNewSelectionDrag} or {@link #onSelectionDrag}.
* </li>
* <li>
* <em>Primary-Button-only Mouse Drag Events:</em>
* (<code>EventPattern.mouseDragged().onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>)
* Do not override, but see next item.
* </li>
* <li>
* <em>All Other Mouse Drag Events:</em>
* You may safely override other Mouse Drag Events using different
* {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if
* process InputMaps (
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or
* {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)}
* ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned.
* The area has a "catch all" Mouse Drag InputMap that will auto scroll towards the mouse drag event when it
* occurs outside the bounds of the area and will stop auto scrolling when the mouse event occurs within the
* area. However, this only works if the event is not consumed before the event reaches that InputMap.
* To insure the auto scroll feature is enabled, set {@link #isAutoScrollOnDragDesired()} to true in your
* process InputMap. If the feature is not desired for that specific drag event, set it to false in the
* process InputMap.
* <em>Note: Due to this "catch-all" nature, all Mouse Drag Events are consumed.</em>
* </li>
* <li>
* <em>Primary-Button-only Mouse Released Events:</em>
* (<code>EventPattern.mouseReleased().onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>).
* Do not override. Instead, use {@link #onNewSelectionDragFinished}, {@link #onSelectionDropped}, or see next item.
* </li>
* <li>
* <em>All other Mouse Released Events:</em>
* You may override other Mouse Released Events using different
* {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if
* process InputMaps (
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or
* {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)}
* ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned.
* The area has a "catch-all" InputMap that will consume all mouse released events and stop auto scroll if it
* was scrolling. However, this only works if the event is not consumed before the event reaches that InputMap.
* <em>Note: Due to this "catch-all" nature, all Mouse Released Events are consumed.</em>
* </li>
* </ul>
*
* <h3>CSS, Style Classes, and Pseudo Classes</h3>
* <p>
* Refer to the <a href="https://github.com/FXMisc/RichTextFX/wiki/RichTextFX-CSS-Reference-Guide">
* RichTextFX CSS Reference Guide
* </a>.
* </p>
*
* <h3>Area Actions and Other Operations</h3>
* <p>
* To distinguish the actual operations one can do on this area from the boilerplate methods
* within this area (e.g. properties and their getters/setters, etc.), look at the interfaces
* this area implements. Each lists and documents methods that fall under that category.
* </p>
* <p>
* To update multiple portions of the area's underlying document in one call, see {@link #createMultiChange()}.
* </p>
*
* <h3>Calculating a Position Within the Area</h3>
* <p>
* To calculate a position or index within the area, read through the javadoc of
* {@link org.fxmisc.richtext.model.TwoDimensional} and {@link org.fxmisc.richtext.model.TwoDimensional.Bias}.
* Also, read the difference between "position" and "index" in
* {@link org.fxmisc.richtext.model.StyledDocument#getAbsolutePosition(int, int)}.
* </p>
*
* @see EditableStyledDocument
* @see TwoDimensional
* @see org.fxmisc.richtext.model.TwoDimensional.Bias
* @see VirtualFlow
* @see VirtualizedScrollPane
* @see Caret
* @see Selection
* @see CaretSelectionBind
*
* @param <PS> type of style that can be applied to paragraphs (e.g. {@link TextFlow}.
* @param <SEG> type of segment used in {@link Paragraph}. Can be only text (plain or styled) or
* a type that combines text and other {@link Node}s.
* @param <S> type of style that can be applied to a segment.
*/
public class GenericStyledArea<PS, SEG, S> extends Region
implements
TextEditingArea<PS, SEG, S>,
EditActions<PS, SEG, S>,
ClipboardActions<PS, SEG, S>,
NavigationActions<PS, SEG, S>,
StyleActions<PS, S>,
UndoActions,
ViewActions<PS, SEG, S>,
TwoDimensional,
Virtualized {
/**
* Index range [0, 0).
*/
public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0);
private static final PseudoClass READ_ONLY = PseudoClass.getPseudoClass("readonly");
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. *
* *
* ********************************************************************** */
/**
* Text color for highlighted text.
*/
private final StyleableObjectProperty<Paint> highlightTextFill
= new CustomStyleableProperty<>(Color.WHITE, "highlightTextFill", this, HIGHLIGHT_TEXT_FILL);
// editable property
private final BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) {
@Override
protected void invalidated() {
((Region) getBean()).pseudoClassStateChanged(READ_ONLY, !get());
}
};
@Override public final BooleanProperty editableProperty() { return editable; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setEditable(boolean value) { editable.set(value); }
@Override public boolean isEditable() { return editable.get(); }
private final ReadOnlyBooleanProperty overwriteMode;
/**
* Indicates weather the area is in overwrite or insert mode.
*/
public final ReadOnlyBooleanProperty overwriteModeProperty() { return overwriteMode; }
public boolean isOverwriteMode() { return overwriteMode.get(); }
// wrapText property
private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText");
@Override public final BooleanProperty wrapTextProperty() { return wrapText; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setWrapText(boolean value) { wrapText.set(value); }
@Override public boolean isWrapText() { return wrapText.get(); }
// undo manager
private UndoManager undoManager;
@Override public UndoManager getUndoManager() { return undoManager; }
/**
* @param undoManager may be null in which case a no op undo manager will be set.
*/
@Override public void setUndoManager(UndoManager undoManager) {
this.undoManager.close();
this.undoManager = undoManager != null ? undoManager : UndoUtils.noOpUndoManager();
}
private Locale textLocale = Locale.getDefault();
/**
* This is used to determine word and sentence breaks while navigating or selecting.
* Override this method if your paragraph or text style accommodates Locales as well.
* @return Locale.getDefault() by default
*/
@Override
public Locale getLocale() { return textLocale; }
public void setLocale( Locale editorLocale ) {
textLocale = editorLocale;
}
private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null);
@Override public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; }
private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null);
@Override public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; }
public void recreateParagraphGraphic( int parNdx ) {
ObjectProperty<IntFunction<? extends Node>> gProp;
gProp = getCell(parNdx).graphicFactoryProperty();
gProp.unbind();
gProp.bind(paragraphGraphicFactoryProperty());
}
public Node getParagraphGraphic( int parNdx ) {
return getCell(parNdx).getGraphic();
}
/**
* This Node is shown to the user, centered over the area, when the area has no text content.
* <br>To customize the placeholder's layout override {@link #configurePlaceholder( Node )}
*/
public final void setPlaceholder(Node value) { setPlaceholder(value,Pos.CENTER); }
public void setPlaceholder(Node value, Pos where) { placeHolderProp.set(value); placeHolderPos = Objects.requireNonNull(where); }
private ObjectProperty<Node> placeHolderProp = new SimpleObjectProperty<>(this, "placeHolder", null);
public final ObjectProperty<Node> placeholderProperty() { return placeHolderProp; }
public final Node getPlaceholder() { return placeHolderProp.get(); }
private Pos placeHolderPos = Pos.CENTER;
private ObjectProperty<ContextMenu> contextMenu = new SimpleObjectProperty<>(null);
@Override public final ObjectProperty<ContextMenu> contextMenuObjectProperty() { return contextMenu; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenu(ContextMenu menu) { contextMenu.set(menu); }
@Override public ContextMenu getContextMenu() { return contextMenu.get(); }
protected final boolean isContextMenuPresent() { return contextMenu.get() != null; }
private DoubleProperty contextMenuXOffset = new SimpleDoubleProperty(2);
@Override public final DoubleProperty contextMenuXOffsetProperty() { return contextMenuXOffset; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenuXOffset(double offset) { contextMenuXOffset.set(offset); }
@Override public double getContextMenuXOffset() { return contextMenuXOffset.get(); }
private DoubleProperty contextMenuYOffset = new SimpleDoubleProperty(2);
@Override public final DoubleProperty contextMenuYOffsetProperty() { return contextMenuYOffset; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenuYOffset(double offset) { contextMenuYOffset.set(offset); }
@Override public double getContextMenuYOffset() { return contextMenuYOffset.get(); }
private final BooleanProperty useInitialStyleForInsertion = new SimpleBooleanProperty();
@Override public BooleanProperty useInitialStyleForInsertionProperty() { return useInitialStyleForInsertion; }
private Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> styleCodecs = Optional.empty();
@Override public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<StyledSegment<SEG, S>> styledSegCodec) {
styleCodecs = Optional.of(t(paragraphStyleCodec, styledSegCodec));
}
@Override public Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> getStyleCodecs() {
return styleCodecs;
}
@Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); }
@Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); }
private final SubscribeableContentsObsSet<CaretNode> caretSet;
private final SubscribeableContentsObsSet<Selection<PS, SEG, S>> selectionSet;
public final boolean addCaret(CaretNode caret) {
if (caret.getArea() != this) {
throw new IllegalArgumentException(String.format(
"The caret (%s) is associated with a different area (%s), " +
"not this area (%s)", caret, caret.getArea(), this));
}
return caretSet.add(caret);
}
public final boolean removeCaret(CaretNode caret) {
if (caret != caretSelectionBind.getUnderlyingCaret()) {
return caretSet.remove(caret);
} else {
return false;
}
}
public final boolean addSelection(Selection<PS, SEG, S> selection) {
if (selection.getArea() != this) {
throw new IllegalArgumentException(String.format(
"The selection (%s) is associated with a different area (%s), " +
"not this area (%s)", selection, selection.getArea(), this));
}
return selectionSet.add(selection);
}
public final boolean removeSelection(Selection<PS, SEG, S> selection) {
if (selection != caretSelectionBind.getUnderlyingSelection()) {
return selectionSet.remove(selection);
} else {
return false;
}
}
/* ********************************************************************** *
* *
* Mouse Behavior Hooks *
* *
* Hooks for overriding some of the default mouse behavior *
* *
* ********************************************************************** */
@Override public final EventHandler<MouseEvent> getOnOutsideSelectionMousePressed() { return onOutsideSelectionMousePressed.get(); }
@Override public final void setOnOutsideSelectionMousePressed(EventHandler<MouseEvent> handler) { onOutsideSelectionMousePressed.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressedProperty() { return onOutsideSelectionMousePressed; }
private final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressed = new SimpleObjectProperty<>( e -> {
moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR );
});
@Override public final EventHandler<MouseEvent> getOnInsideSelectionMousePressReleased() { return onInsideSelectionMousePressReleased.get(); }
@Override public final void setOnInsideSelectionMousePressReleased(EventHandler<MouseEvent> handler) { onInsideSelectionMousePressReleased.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleasedProperty() { return onInsideSelectionMousePressReleased; }
private final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleased = new SimpleObjectProperty<>( e -> {
moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR );
});
private final ObjectProperty<Consumer<Point2D>> onNewSelectionDrag = new SimpleObjectProperty<>(p -> {
CharacterHit hit = hit(p.getX(), p.getY());
moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST);
});
@Override public final ObjectProperty<Consumer<Point2D>> onNewSelectionDragProperty() { return onNewSelectionDrag; }
@Override public final EventHandler<MouseEvent> getOnNewSelectionDragFinished() { return onNewSelectionDragFinished.get(); }
@Override public final void setOnNewSelectionDragFinished(EventHandler<MouseEvent> handler) { onNewSelectionDragFinished.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinishedProperty() { return onNewSelectionDragFinished; }
private final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinished = new SimpleObjectProperty<>( e -> {
CharacterHit hit = hit(e.getX(), e.getY());
moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST);
});
private final ObjectProperty<Consumer<Point2D>> onSelectionDrag = new SimpleObjectProperty<>(p -> {
CharacterHit hit = hit(p.getX(), p.getY());
displaceCaret(hit.getInsertionIndex());
});
@Override public final ObjectProperty<Consumer<Point2D>> onSelectionDragProperty() { return onSelectionDrag; }
@Override public final EventHandler<MouseEvent> getOnSelectionDropped() { return onSelectionDropped.get(); }
@Override public final void setOnSelectionDropped(EventHandler<MouseEvent> handler) { onSelectionDropped.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onSelectionDroppedProperty() { return onSelectionDropped; }
private final ObjectProperty<EventHandler<MouseEvent>> onSelectionDropped = new SimpleObjectProperty<>( e -> {
moveSelectedText( hit( e.getX(), e.getY() ).getInsertionIndex() );
});
// not a hook, but still plays a part in the default mouse behavior
private final BooleanProperty autoScrollOnDragDesired = new SimpleBooleanProperty(true);
@Override public final BooleanProperty autoScrollOnDragDesiredProperty() { return autoScrollOnDragDesired; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setAutoScrollOnDragDesired(boolean val) { autoScrollOnDragDesired.set(val); }
@Override public boolean isAutoScrollOnDragDesired() { return autoScrollOnDragDesired.get(); }
/* ********************************************************************** *
* *
* 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 ObservableValue<String> textProperty() { return content.textProperty(); }
// rich text
@Override public final StyledDocument<PS, SEG, S> getDocument() { return content; }
private CaretSelectionBind<PS, SEG, S> caretSelectionBind;
@Override public final CaretSelectionBind<PS, SEG, S> getCaretSelectionBind() { return caretSelectionBind; }
// length
@Override public final ObservableValue<Integer> lengthProperty() { return content.lengthProperty(); }
// paragraphs
@Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return content.getParagraphs(); }
private final SuspendableList<Paragraph<PS, SEG, S>> visibleParagraphs;
@Override public final LiveList<Paragraph<PS, SEG, S>> getVisibleParagraphs() { return visibleParagraphs; }
// beingUpdated
private final SuspendableNo beingUpdated = new SuspendableNo();
@Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; }
// total width estimate
@Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); }
// total height estimate
@Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); }
/* ********************************************************************** *
* *
* Event streams *
* *
* ********************************************************************** */
@Override public EventStream<List<RichTextChange<PS, SEG, S>>> multiRichChanges() { return content.multiRichChanges(); }
@Override public EventStream<List<PlainTextChange>> multiPlainChanges() { return content.multiPlainChanges(); }
// text changes
@Override public final EventStream<PlainTextChange> plainTextChanges() { return content.plainChanges(); }
// rich text changes
@Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return content.richChanges(); }
private final SuspendableEventStream<?> viewportDirty;
@Override public final EventStream<?> viewportDirtyEvents() { return viewportDirty; }
/* ********************************************************************** *
* *
* Private fields *
* *
* ********************************************************************** */
private Subscription subscriptions = () -> {};
private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, 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 paragraphLineNavigator;
private boolean paging, followCaretRequested = false;
/* ********************************************************************** *
* *
* Fields necessary for Cloning *
* *
* ********************************************************************** */
private final EditableStyledDocument<PS, SEG, S> content;
@Override public final EditableStyledDocument<PS, SEG, S> getContent() { return content; }
private final S initialTextStyle;
@Override public final S getInitialTextStyle() { return initialTextStyle; }
private final PS initialParagraphStyle;
@Override public final PS getInitialParagraphStyle() { return initialParagraphStyle; }
private final BiConsumer<TextFlow, PS> applyParagraphStyle;
@Override public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; }
// TODO: Currently, only undo/redo respect this flag.
private final boolean preserveStyle;
@Override public final boolean isPreserveStyle() { return preserveStyle; }
/* ********************************************************************** *
* *
* Miscellaneous *
* *
* ********************************************************************** */
private final TextOps<SEG, S> segmentOps;
@Override public final TextOps<SEG, S> getSegOps() { return segmentOps; }
private final EventStream<Boolean> autoCaretBlinksSteam;
final EventStream<Boolean> autoCaretBlink() { return autoCaretBlinksSteam; }
/* ********************************************************************** *
* *
* Constructors *
* *
* ********************************************************************** */
/**
* Creates a text area with empty text content.
*
* @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.
* @param initialTextStyle style to use in places where no other style is
* specified (yet).
* @param segmentOps The operations which are defined on the text segment objects.
* @param nodeFactory A function which is used to create the JavaFX scene nodes for a
* particular segment.
*/
public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory);
}
/**
* Same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} but also allows one
* to specify whether the undo manager should be a plain or rich undo manager via {@code preserveStyle}.
*
* @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.
* @param initialTextStyle style to use in places where no other style is specified (yet).
* @param segmentOps The operations which are defined on the text segment objects.
* @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or
* {@link PlainTextChange}s
* @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment.
*/
public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("preserveStyle") boolean preserveStyle,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle,
new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory);
}
/**
* The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that
* this constructor can be used to create another {@code GenericStyledArea} that renders and edits the same
* {@link EditableStyledDocument} or when one wants to use a custom {@link EditableStyledDocument} implementation.
*/
public GenericStyledArea(
@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("document") EditableStyledDocument<PS, SEG, S> document,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, segmentOps, true, nodeFactory);
}
/**
* Creates an area with flexibility in all of its options.
*
* @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.
* @param initialTextStyle style to use in places where no other style is specified (yet).
* @param document the document to render and edit
* @param segmentOps The operations which are defined on the text segment objects.
* @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or
* {@link PlainTextChange}s
* @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment.
*/
public GenericStyledArea(
@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("document") EditableStyledDocument<PS, SEG, S> document,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("preserveStyle") boolean preserveStyle,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this.initialTextStyle = initialTextStyle;
this.initialParagraphStyle = initialParagraphStyle;
this.preserveStyle = preserveStyle;
this.content = document;
this.applyParagraphStyle = applyParagraphStyle;
this.segmentOps = segmentOps;
undoManager = UndoUtils.defaultUndoManager(this);
// 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, SEG, S>> nonEmptyCells = FXCollections.observableSet();
caretSet = new SubscribeableContentsObsSet<>();
manageSubscription(() -> {
List<CaretNode> l = new ArrayList<>(caretSet);
caretSet.clear();
l.forEach(CaretNode::dispose);
});
selectionSet = new SubscribeableContentsObsSet<>();
manageSubscription(() -> {
List<Selection<PS, SEG, S>> l = new ArrayList<>(selectionSet);
selectionSet.clear();
l.forEach(Selection::dispose);
});
// Initialize content
virtualFlow = VirtualFlow.createVertical(
getParagraphs(),
par -> {
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell(
par,
applyParagraphStyle,
nodeFactory);
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();
paragraphLineNavigator = new TwoLevelNavigator(cellCount, cellLength);
viewportDirty = merge(
// no need to check for width & height invalidations as scroll values update when these do
// scale
invalidationsOf(scaleXProperty()),
invalidationsOf(scaleYProperty()),
// scroll
invalidationsOf(estimatedScrollXProperty()),
invalidationsOf(estimatedScrollYProperty())
).suppressible();
autoCaretBlinksSteam = EventStreams.valuesOf(focusedProperty()
.and(editableProperty())
.and(disabledProperty().not())
);
caretSelectionBind = new CaretSelectionBindImpl<>("main-caret", "main-selection",this);
caretSelectionBind.paragraphIndexProperty().addListener( this::skipOverFoldedParagraphs );
caretSet.add(caretSelectionBind.getUnderlyingCaret());
selectionSet.add(caretSelectionBind.getUnderlyingSelection());
visibleParagraphs = LiveList.map(virtualFlow.visibleCells(), c -> c.getNode().getParagraph()).suspendable();
final Suspendable omniSuspendable = Suspendable.combine(
beingUpdated, // must be first, to be the last one to release
visibleParagraphs
);
manageSubscription(omniSuspendable.suspendWhen(content.beingUpdatedProperty()));
// 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));
this.overwriteMode = new GenericStyledAreaBehavior(this).overwriteModeProperty();
// Setup place holder visibility & placement
final Val<Boolean> showPlaceholder = Val.create
(
() -> getLength() == 0 && ! isFocused(),
lengthProperty(), focusedProperty()
);
placeHolderProp.addListener( (ob,ov,newNode) -> displayPlaceHolder( showPlaceholder.getValue(), newNode ) );
showPlaceholder.addListener( (ob,ov,show) -> displayPlaceHolder( show, getPlaceholder() ) );
if ( Platform.isFxApplicationThread() ) initInputMethodHandling();
else Platform.runLater( () -> initInputMethodHandling() );
}
private void initInputMethodHandling()
{
if( Platform.isSupported( ConditionalFeature.INPUT_METHOD ) )
{
setOnInputMethodTextChanged( event -> handleInputMethodEvent(event) );
// Both of these have to be set for input composition to work !
setInputMethodRequests( new InputMethodRequests()
{
@Override public Point2D getTextLocation( int offset ) {
return getCaretBounds()
.or( () -> getCharacterBoundsOnScreen( offset, offset ) )
.map( cb -> new Point2D( cb.getMaxX() - 5, cb.getMaxY() ) )
.orElseGet( () -> new Point2D( 10,10 ) );
}
@Override public int getLocationOffset( int x, int y ) {
return 0;
}
@Override public void cancelLatestCommittedText() {}
@Override public String getSelectedText() {
return GenericStyledArea.this.getSelectedText();
}
});
}
}
// Start/Length of the text under input method composition
private int imstart;
private int imlength;
protected void handleInputMethodEvent( InputMethodEvent event )
{
if ( isEditable() && !isDisabled() )
{
// remove previous input method text (if any) or selected text
if ( imlength != 0 ) {
selectRange( imstart, imstart + imlength );
}
// Insert committed text
if ( event.getCommitted().length() != 0 ) {
replaceText( getSelection(), event.getCommitted() );
}
// Replace composed text
imstart = getSelection().getStart();
StringBuilder composed = new StringBuilder();
for ( InputMethodTextRun run : event.getComposed() ) {
composed.append( run.getText() );
}
replaceText( getSelection(), composed.toString() );
imlength = composed.length();
if ( imlength != 0 )
{
int pos = imstart;
for ( InputMethodTextRun run : event.getComposed() ) {
int endPos = pos + run.getText().length();
pos = endPos;
}
// Set caret position in composed text
int caretPos = event.getCaretPosition();
if ( caretPos >= 0 && caretPos < imlength ) {
selectRange( imstart + caretPos, imstart + caretPos );
}
}
}
}
private Node placeholder;
private boolean positionPlaceholder = false;
private void displayPlaceHolder( boolean show, Node newNode )
{
if ( placeholder != null && (! show || newNode != placeholder) )
{
placeholder.layoutXProperty().unbind();
placeholder.layoutYProperty().unbind();
getChildren().remove( placeholder );
placeholder = null;
setClip( null );
}
if ( newNode != null && show && newNode != placeholder )
{
configurePlaceholder( newNode );
getChildren().add( newNode );
placeholder = newNode;
}
}
/**
* Override this to customize the placeholder's layout.
* <br>The default position is centered over the area.
*/
protected void configurePlaceholder( Node placeholder )
{
positionPlaceholder = true;
}
/* ********************************************************************** *
* *
* Queries *
* *
* Queries are parameterized observables. *
* *
* ********************************************************************** */
@Override
public final double getViewportHeight() {
return virtualFlow.getHeight();
}
@Override
public final Optional<Integer> allParToVisibleParIndex(int allParIndex) {
if (allParIndex < 0) {
throw new IllegalArgumentException("The given paragraph index (allParIndex) cannot be negative but was " + allParIndex);
}
if (allParIndex >= getParagraphs().size()) {
throw new IllegalArgumentException(String.format(
"Paragraphs' last index is [%s] but allParIndex was [%s]",
getParagraphs().size() - 1, allParIndex)
);
}
List<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> visibleList = virtualFlow.visibleCells();
int firstVisibleParIndex = visibleList.get( 0 ).getNode().getIndex();
int targetIndex = allParIndex - firstVisibleParIndex;
if ( allParIndex >= firstVisibleParIndex && targetIndex < visibleList.size() )
{
if ( visibleList.get( targetIndex ).getNode().getIndex() == allParIndex )
{
return Optional.of( targetIndex );
}
}
return Optional.empty();
}
@Override
public final int visibleParToAllParIndex(int visibleParIndex) {
if (visibleParIndex < 0) {
throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + visibleParIndex);
}
if (visibleParIndex > 0 && visibleParIndex >= getVisibleParagraphs().size()) {
throw new IllegalArgumentException(String.format(
"Visible paragraphs' last index is [%s] but visibleParIndex was [%s]",
getVisibleParagraphs().size() - 1, visibleParIndex)
);
}
try {
Cell<Paragraph<PS,SEG,S>, ParagraphBox<PS,SEG,S>> visibleCell = null;
if ( visibleParIndex > 0 ) visibleCell = virtualFlow.visibleCells().get( visibleParIndex );