Skip to content

Commit a1be8e4

Browse files
authored
Refactor control to use ListView (#125)
Co-authored-by: jose.pereda <jose.pereda@gluonhq.com>
1 parent e6fe3c2 commit a1be8e4

14 files changed

+845
-412
lines changed

src/main/java/com/gluonhq/Main.java

+24-7
Original file line numberDiff line numberDiff line change
@@ -70,14 +70,31 @@ public class Main extends Application {
7070
}
7171

7272
private final List<DecorationModel> decorations = List.of(
73-
new DecorationModel(0, 12, TextDecoration.builder().presets().build()),
74-
new DecorationModel(12, 3, TextDecoration.builder().presets().fontWeight(FontWeight.BOLD).build()),
75-
new DecorationModel(15, 1, new ImageDecoration(Main.class.getResource("gluon_logo-150x150@2x.png").toURI().toString(), 32, 32)),
76-
new DecorationModel(16, 11, TextDecoration.builder().presets().fontPosture(FontPosture.ITALIC).build()),
77-
new DecorationModel(27, 15, TextDecoration.builder().presets().foreground(Color.RED).build())
78-
);
73+
new DecorationModel(0, 20, TextDecoration.builder().presets().fontWeight(FontWeight.BOLD).fontSize(14).build()),
74+
new DecorationModel(20, 576, TextDecoration.builder().presets().build()),
75+
new DecorationModel(596, 17, TextDecoration.builder().presets().fontWeight(FontWeight.BOLD).fontSize(14).build()),
76+
new DecorationModel(613, 615, TextDecoration.builder().presets().build()),
77+
new DecorationModel(1228, 24, TextDecoration.builder().presets().fontWeight(FontWeight.BOLD).fontSize(14).build()),
78+
new DecorationModel(1252, 1060, TextDecoration.builder().presets().build())
79+
);
80+
81+
private final Document document = new Document("What is Lorem Ipsum?" +
82+
"\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
83+
"Why do we use it?" +
84+
"\nIt is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\n" +
85+
"Where does it come from?" +
86+
"\nContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.\nThe standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.\n",
87+
decorations, 2312);
7988

80-
private final Document document = new Document("Simple text one\u200b two three\nExtra line text", decorations, 42);
89+
// private final List<DecorationModel> decorations = List.of(
90+
// new DecorationModel(0, 12, TextDecoration.builder().presets().build()),
91+
// new DecorationModel(12, 3, TextDecoration.builder().presets().fontWeight(FontWeight.BOLD).build()),
92+
// new DecorationModel(15, 1, new ImageDecoration(Main.class.getResource("gluon_logo-150x150@2x.png").toURI().toString(), 32, 32)),
93+
// new DecorationModel(16, 11, TextDecoration.builder().presets().fontPosture(FontPosture.ITALIC).build()),
94+
// new DecorationModel(27, 15, TextDecoration.builder().presets().foreground(Color.RED).build())
95+
// );
96+
//
97+
// private final Document document = new Document("Simple text one\u200b two three\nExtra line text", decorations, 42);
8198

8299
private final Label textLengthLabel = new Label();
83100
private final RichTextArea editor = new RichTextArea();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.gluonhq.richtext;
2+
3+
import javafx.scene.shape.Path;
4+
import javafx.scene.shape.PathElement;
5+
6+
import java.util.Objects;
7+
8+
class BackgroundColorPath extends Path {
9+
10+
public BackgroundColorPath(PathElement[] elements) {
11+
super(elements);
12+
}
13+
14+
@Override
15+
public boolean equals(Object o) {
16+
if (this == o) return true;
17+
if (o == null || getClass() != o.getClass()) return false;
18+
BackgroundColorPath that = (BackgroundColorPath) o;
19+
return Objects.equals(getLayoutBounds(), that.getLayoutBounds()) && Objects.equals(getFill(), that.getFill());
20+
}
21+
22+
@Override
23+
public int hashCode() {
24+
return Objects.hash(getLayoutBounds(), getFill());
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.gluonhq.richtext;
2+
3+
import javafx.scene.paint.Color;
4+
5+
class IndexRangeColor {
6+
7+
private final int start;
8+
private final int end;
9+
private final Color color;
10+
11+
public IndexRangeColor(int start, int end, Color color) {
12+
this.start = start;
13+
this.end = end;
14+
this.color = color;
15+
}
16+
17+
public int getStart() {
18+
return start;
19+
}
20+
21+
public int getEnd() {
22+
return end;
23+
}
24+
25+
public Color getColor() {
26+
return color;
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
package com.gluonhq.richtext;
2+
3+
import com.gluonhq.richtext.model.Paragraph;
4+
import com.gluonhq.richtext.viewmodel.RichTextAreaViewModel;
5+
import javafx.animation.KeyFrame;
6+
import javafx.animation.Timeline;
7+
import javafx.beans.value.ChangeListener;
8+
import javafx.collections.FXCollections;
9+
import javafx.collections.ObservableSet;
10+
import javafx.collections.SetChangeListener;
11+
import javafx.geometry.Bounds;
12+
import javafx.geometry.Insets;
13+
import javafx.geometry.Point2D;
14+
import javafx.scene.Group;
15+
import javafx.scene.image.Image;
16+
import javafx.scene.image.ImageView;
17+
import javafx.scene.input.MouseButton;
18+
import javafx.scene.input.MouseEvent;
19+
import javafx.scene.layout.HBox;
20+
import javafx.scene.layout.Pane;
21+
import javafx.scene.shape.Path;
22+
import javafx.scene.shape.PathElement;
23+
import javafx.scene.text.Font;
24+
import javafx.scene.text.HitInfo;
25+
import javafx.scene.text.Text;
26+
import javafx.scene.text.TextAlignment;
27+
import javafx.scene.text.TextFlow;
28+
import javafx.util.Duration;
29+
30+
import java.util.ArrayList;
31+
import java.util.List;
32+
import java.util.Objects;
33+
import java.util.Set;
34+
import java.util.stream.Collectors;
35+
36+
public class ParagraphTile extends HBox {
37+
38+
private final Timeline caretTimeline = new Timeline(
39+
new KeyFrame(Duration.ZERO , e -> setCaretVisibility(false)),
40+
new KeyFrame(Duration.seconds(0.5), e -> setCaretVisibility(true)),
41+
new KeyFrame(Duration.seconds(1.0))
42+
);
43+
44+
private final Pane root;
45+
private final Group layers;
46+
private final ObservableSet<Path> textBackgroundColorPaths = FXCollections.observableSet();
47+
private final Path caretShape = new Path();
48+
private final Path selectionShape = new Path();
49+
private final TextFlow textFlow = new TextFlow() {
50+
@Override
51+
protected double computePrefHeight(double width) {
52+
double prefHeight = super.computePrefHeight(width);
53+
// take into account caret
54+
root.setPrefHeight(prefHeight + 1);
55+
return prefHeight;
56+
}
57+
};
58+
59+
private final RichTextArea control;
60+
private final RichTextAreaSkin richTextAreaSkin;
61+
private final RichTextAreaViewModel viewModel;
62+
63+
private Paragraph paragraph;
64+
private final double textFlowLayoutX = 1d, textFlowLayoutY = 1d;
65+
private final ChangeListener<Number> caretPositionListener = (o, ocp, p) -> updateCaretPosition(p.intValue());
66+
private final ChangeListener<Selection> selectionListener = (o, os, selection) -> updateSelection(selection);
67+
68+
public ParagraphTile(RichTextAreaSkin richTextAreaSkin) {
69+
this.richTextAreaSkin = richTextAreaSkin;
70+
this.control = richTextAreaSkin.getSkinnable();
71+
this.viewModel = richTextAreaSkin.getViewModel();
72+
getStyleClass().setAll("paragraph-tile");
73+
caretTimeline.setCycleCount(Timeline.INDEFINITE);
74+
textFlow.setFocusTraversable(false);
75+
textFlow.getStyleClass().setAll("text-flow");
76+
textFlow.setOnMousePressed(this::mousePressedListener);
77+
// TODO: Expose paragraph justification
78+
textFlow.setTextAlignment(TextAlignment.LEFT);
79+
// TODO: Expose paragraph spacing
80+
textFlow.setLineSpacing(0);
81+
82+
caretShape.setFocusTraversable(false);
83+
caretShape.getStyleClass().add("caret");
84+
85+
selectionShape.getStyleClass().setAll("selection");
86+
87+
layers = new Group(selectionShape, caretShape, textFlow);
88+
layers.getStyleClass().add("layers");
89+
root = new Pane(layers);
90+
root.setPadding(new Insets(1));
91+
root.getStyleClass().setAll("content-area");
92+
layers.getChildren().addAll(0, textBackgroundColorPaths);
93+
textBackgroundColorPaths.addListener(this::updateLayers);
94+
// TODO: add left label for list decoration, line number, indentation
95+
getChildren().add(root);
96+
// TODO: expose padding as paragraph indentation
97+
setPadding(new Insets(0, 0, 10, 0));
98+
}
99+
100+
void setParagraph(Paragraph paragraph) {
101+
viewModel.caretPositionProperty().removeListener(caretPositionListener);
102+
viewModel.selectionProperty().removeListener(selectionListener);
103+
this.paragraph = paragraph;
104+
viewModel.caretPositionProperty().addListener(caretPositionListener);
105+
viewModel.selectionProperty().addListener(selectionListener);
106+
}
107+
108+
TextFlow getTextFlow() {
109+
return textFlow;
110+
}
111+
112+
ObservableSet<Path> getTextBackgroundColorPaths() {
113+
return textBackgroundColorPaths;
114+
}
115+
116+
private void mousePressedListener(MouseEvent e) {
117+
if (control.isDisabled()) {
118+
return;
119+
}
120+
if (e.getButton() == MouseButton.PRIMARY && !(e.isMiddleButtonDown() || e.isSecondaryButtonDown())) {
121+
HitInfo hitInfo = textFlow.hitTest(new Point2D(e.getX() - textFlowLayoutX, e.getY() - textFlowLayoutY));
122+
Selection prevSelection = viewModel.getSelection();
123+
int prevCaretPosition = viewModel.getCaretPosition();
124+
int insertionIndex = hitInfo.getInsertionIndex();
125+
if (insertionIndex >= 0) {
126+
int globalInsertionIndex = paragraph.getStart() + insertionIndex;
127+
if (!(e.isControlDown() || e.isAltDown() || e.isShiftDown() || e.isMetaDown() || e.isShortcutDown())) {
128+
viewModel.setCaretPosition(globalInsertionIndex);
129+
if (e.getClickCount() == 2) {
130+
viewModel.selectCurrentWord();
131+
} else if (e.getClickCount() == 3) {
132+
viewModel.selectCurrentParagraph();
133+
} else {
134+
richTextAreaSkin.dragStart = globalInsertionIndex;
135+
viewModel.clearSelection();
136+
}
137+
} else if (e.isShiftDown() && e.getClickCount() == 1 && !(e.isControlDown() || e.isAltDown() || e.isMetaDown() || e.isShortcutDown())) {
138+
int pos = prevSelection.isDefined() ?
139+
globalInsertionIndex < prevSelection.getStart() ? prevSelection.getEnd() : prevSelection.getStart() :
140+
prevCaretPosition;
141+
viewModel.setSelection(new Selection(pos, globalInsertionIndex));
142+
viewModel.setCaretPosition(globalInsertionIndex);
143+
}
144+
}
145+
control.requestFocus();
146+
e.consume();
147+
}
148+
if (richTextAreaSkin.contextMenu.isShowing()) {
149+
richTextAreaSkin.contextMenu.hide();
150+
}
151+
}
152+
153+
void mouseDraggedListener(MouseEvent e) {
154+
HitInfo hitInfo = textFlow.hitTest(new Point2D(e.getX() - textFlowLayoutX, e.getY() - textFlowLayoutY));
155+
if (hitInfo.getInsertionIndex() >= 0) {
156+
int dragEnd = paragraph.getStart() + hitInfo.getInsertionIndex();
157+
viewModel.setSelection(new Selection(richTextAreaSkin.dragStart, dragEnd));
158+
viewModel.setCaretPosition(dragEnd);
159+
}
160+
e.consume();
161+
}
162+
163+
private void updateCaretPosition(int caretPosition) {
164+
caretShape.getElements().clear();
165+
if (paragraph == null || caretPosition < paragraph.getStart() || paragraph.getEnd() <= caretPosition) {
166+
caretTimeline.stop();
167+
return;
168+
}
169+
if (caretPosition < 0 || !control.isEditable()) {
170+
caretTimeline.stop();
171+
} else {
172+
var pathElements = textFlow.caretShape(caretPosition - paragraph.getStart(), true);
173+
if (pathElements.length > 0) {
174+
caretShape.getElements().addAll(pathElements);
175+
richTextAreaSkin.lastValidCaretPosition = caretPosition;
176+
caretTimeline.play();
177+
}
178+
}
179+
caretShape.setLayoutX(textFlowLayoutX);
180+
caretShape.setLayoutY(textFlowLayoutY);
181+
}
182+
183+
private void setCaretVisibility(boolean on) {
184+
if (caretShape.getElements().size() > 0) {
185+
// Opacity is used since we don't want the changing caret bounds to affect the layout
186+
// Otherwise text appears to be jumping
187+
caretShape.setOpacity(on ? 1 : 0);
188+
}
189+
}
190+
191+
private void updateSelection(Selection selection) {
192+
selectionShape.getElements().clear();
193+
if (selection != null && selection.isDefined()) {
194+
PathElement[] pathElements = textFlow.rangeShape(
195+
Math.max(paragraph.getStart(), selection.getStart()) - paragraph.getStart(),
196+
Math.min(paragraph.getEnd(), selection.getEnd()) - paragraph.getStart());
197+
if (pathElements.length > 0) {
198+
selectionShape.getElements().setAll(pathElements);
199+
}
200+
}
201+
selectionShape.setLayoutX(textFlowLayoutX);
202+
selectionShape.setLayoutY(textFlowLayoutY);
203+
}
204+
205+
private void updateLayers(SetChangeListener.Change<? extends Path> change) {
206+
if (change.wasAdded()) {
207+
layers.getChildren().add(0, change.getElementAdded());
208+
} else if (change.wasRemoved()) {
209+
layers.getChildren().remove(change.getElementRemoved());
210+
}
211+
}
212+
213+
void evictUnusedObjects() {
214+
Set<Font> usedFonts = textFlow.getChildren()
215+
.stream()
216+
.filter(Text.class::isInstance)
217+
.map(t -> ((Text) t).getFont())
218+
.filter(Objects::nonNull)
219+
.collect(Collectors.toSet());
220+
List<Font> cachedFonts = new ArrayList<>(richTextAreaSkin.getFontCache().values());
221+
cachedFonts.removeAll(usedFonts);
222+
richTextAreaSkin.getFontCache().values().removeAll(cachedFonts);
223+
224+
Set<Image> usedImages = textFlow.getChildren()
225+
.stream()
226+
.filter(ImageView.class::isInstance)
227+
.map(t -> ((ImageView) t).getImage())
228+
.filter(Objects::nonNull)
229+
.collect(Collectors.toSet());
230+
List<Image> cachedImages = new ArrayList<>(richTextAreaSkin.getImageCache().values());
231+
cachedImages.removeAll(usedImages);
232+
richTextAreaSkin.getImageCache().values().removeAll(cachedImages);
233+
}
234+
235+
void updateLayout() {
236+
if (control == null || viewModel == null) {
237+
return;
238+
}
239+
updateSelection(viewModel.getSelection());
240+
updateCaretPosition(viewModel.getCaretPosition());
241+
}
242+
243+
boolean hasCaret() {
244+
return !caretShape.getElements().isEmpty();
245+
}
246+
247+
int getNextRowPosition(double x, boolean down) {
248+
Bounds caretBounds = caretShape.getLayoutBounds();
249+
double nextRowPos = x < 0d ?
250+
down ?
251+
caretBounds.getMaxY() + textFlow.getLineSpacing() :
252+
caretBounds.getMinY() - textFlow.getLineSpacing() :
253+
caretBounds.getCenterY();
254+
double xPos = x < 0d ? caretBounds.getMaxX() : x;
255+
HitInfo hitInfo = textFlow.hitTest(new Point2D(xPos, nextRowPos));
256+
return paragraph.getStart() + hitInfo.getInsertionIndex();
257+
}
258+
259+
}

0 commit comments

Comments
 (0)