1 /* 2 * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package javafx.scene.text; 27 28 import java.util.ArrayList; 29 import java.util.Collections; 30 import java.util.List; 31 import javafx.beans.property.DoubleProperty; 32 import javafx.beans.property.ObjectProperty; 33 import javafx.geometry.HPos; 34 import javafx.geometry.Insets; 35 import javafx.geometry.NodeOrientation; 36 import javafx.geometry.Orientation; 37 import javafx.geometry.VPos; 38 import javafx.scene.AccessibleAttribute; 39 import javafx.scene.AccessibleRole; 40 import javafx.scene.Node; 41 import javafx.scene.layout.Pane; 42 import javafx.scene.shape.PathElement; 43 import javafx.css.StyleableDoubleProperty; 44 import javafx.css.StyleableObjectProperty; 45 import javafx.css.CssMetaData; 46 import javafx.css.converter.EnumConverter; 47 import javafx.css.converter.SizeConverter; 48 import com.sun.javafx.geom.BaseBounds; 49 import com.sun.javafx.geom.Point2D; 50 import com.sun.javafx.geom.RectBounds; 51 import com.sun.javafx.scene.text.GlyphList; 52 import com.sun.javafx.scene.text.TextLayout; 53 import com.sun.javafx.scene.text.TextLayoutFactory; 54 import com.sun.javafx.scene.text.TextSpan; 55 import com.sun.javafx.tk.Toolkit; 56 import javafx.css.Styleable; 57 import javafx.css.StyleableProperty; 58 59 /** 60 * TextFlow is special layout designed to lay out rich text. 61 * It can be used to layout several {@link Text} nodes in a single text flow. 62 * The TextFlow uses the text and the font of each {@link Text} node inside of it 63 * plus it own width and text alignment to determine the location for each child. 64 * A single {@link Text} node can span over several lines due to wrapping and 65 * the visual location of {@link Text} node can differ from the logical location 66 * due to bidi reordering. 67 * 68 * <p> 69 * Any other Node, rather than Text, will be treated as embedded object in the 70 * text layout. It will be inserted in the content using its preferred width, 71 * height, and baseline offset. 72 * 73 * <p> 74 * When a {@link Text} node is inside of a TextFlow some its properties are ignored. 75 * For example, the x and y properties of the {@link Text} node are ignored since 76 * the location of the node is determined by the parent. Likewise, the wrapping 77 * width in the {@link Text} node is ignored since the width used for wrapping 78 * is the TextFlow's width. The value of the <code>pickOnBounds</code> property 79 * of a {@link Text} is set to <code>false</code> when it is laid out by the 80 * TextFlow. This happens because the content of a single {@link Text} node can 81 * divided and placed in the different locations on the TextFlow (usually due to 82 * line breaking and bidi reordering). 83 * 84 * <p> 85 * The wrapping width of the layout is determined by the region's current width. 86 * It can be specified by the application by setting the textflow's preferred 87 * width. If no wrapping is desired, the application can either set the preferred 88 * with to Double.MAX_VALUE or Region.USE_COMPUTED_SIZE. 89 * 90 * <p> 91 * Paragraphs are separated by {@code '\n'} present in any Text child. 92 * 93 * <p> 94 * Example of a TextFlow: 95 * <pre><code> 96 * Text text1 = new Text("Big italic red text"); 97 * text1.setFill(Color.RED); 98 * text1.setFont(Font.font("Helvetica", FontPosture.ITALIC, 40)); 99 * Text text2 = new Text(" little bold blue text"); 100 * text2.setFill(Color.BLUE); 101 * text2.setFont(Font.font("Helvetica", FontWeight.BOLD, 10)); 102 * TextFlow textFlow = new TextFlow(text1, text2); 103 * </code></pre> 104 * 105 * <p> 106 * TextFlow lays out each managed child regardless of the child's visible property value; 107 * unmanaged children are ignored for all layout calculations.</p> 108 * 109 * <p> 110 * TextFlow may be styled with backgrounds and borders using CSS. See 111 * {@link javafx.scene.layout.Region Region} superclass for details.</p> 112 * 113 * <h4>Resizable Range</h4> 114 * 115 * A textflow's parent will resize the textflow within the textflow's range 116 * during layout. By default the textflow computes this range based on its content 117 * as outlined in the tables below. 118 * <p> 119 * <table border="1"> 120 * <tr><td></td><th>width</th><th>height</th></tr> 121 * <tr><th>minimum</th> 122 * <td>left/right insets</td> 123 * <td>top/bottom insets plus the height of the text content</td></tr> 124 * <tr><th>preferred</th> 125 * <td>left/right insets plus the width of the text content</td> 126 * <td>top/bottom insets plus the height of the text content</td></tr> 127 * <tr><th>maximum</th> 128 * <td>Double.MAX_VALUE</td><td>Double.MAX_VALUE</td></tr> 129 * </table> 130 * <p> 131 * A textflow's unbounded maximum width and height are an indication to the parent that 132 * it may be resized beyond its preferred size to fill whatever space is assigned to it. 133 * <p> 134 * TextFlow provides properties for setting the size range directly. These 135 * properties default to the sentinel value Region.USE_COMPUTED_SIZE, however the 136 * application may set them to other values as needed: 137 * <pre><code> 138 * <b>textflow.setMaxWidth(500);</b> 139 * </code></pre> 140 * Applications may restore the computed values by setting these properties back 141 * to Region.USE_COMPUTED_SIZE. 142 * <p> 143 * TextFlow does not clip its content by default, so it is possible that childrens' 144 * bounds may extend outside its own bounds if a child's pref size is larger than 145 * the space textflow has to allocate for it.</p> 146 * 147 * @since JavaFX 8.0 148 */ 149 public class TextFlow extends Pane { 150 151 private TextLayout layout; 152 private boolean needsContent; 153 private boolean inLayout; 154 // private static final PathElement[] EMPTY_PATH_ELEMENT_ARRAY = new PathElement[0]; 155 156 /** 157 * Creates an empty TextFlow layout. 158 */ 159 public TextFlow() { 160 super(); 161 effectiveNodeOrientationProperty().addListener(observable -> checkOrientation()); 162 setAccessibleRole(AccessibleRole.TEXT); 163 } 164 165 /** 166 * Creates a TextFlow layout with the given children. 167 * 168 * @param children children. 169 */ 170 public TextFlow(Node... children) { 171 this(); 172 getChildren().addAll(children); 173 } 174 175 private void checkOrientation() { 176 NodeOrientation orientation = getEffectiveNodeOrientation(); 177 boolean rtl = orientation == NodeOrientation.RIGHT_TO_LEFT; 178 int dir = rtl ? TextLayout.DIRECTION_RTL : TextLayout.DIRECTION_LTR; 179 TextLayout layout = getTextLayout(); 180 if (layout.setDirection(dir)) { 181 requestLayout(); 182 } 183 } 184 185 /** 186 * Maps local point to index in the content. 187 * 188 * @since 9 189 */ 190 public final HitInfo hitTest(javafx.geometry.Point2D point) { 191 if (point != null) { 192 TextLayout layout = getTextLayout(); 193 double x = point.getX()/* - getX()*/; 194 double y = point.getY()/* - getY()/* + getYRendering()*/; 195 TextLayout.Hit layoutHit = layout.getHitInfo((float)x, (float)y); 196 return new HitInfo(layoutHit.getCharIndex(), layoutHit.getInsertionIndex(), 197 layoutHit.isLeading(), null/*getText()*/); 198 } else { 199 return null; 200 } 201 } 202 203 /** 204 * Returns shape of caret in local coordinates. 205 * 206 * @since 9 207 */ 208 public PathElement[] caretShape(int charIndex, boolean leading) { 209 return getTextLayout().getCaretShape(charIndex, leading, 0, 0); 210 } 211 212 /** 213 * Returns shape for the range of the text in local coordinates. 214 * 215 * @since 9 216 */ 217 public final PathElement[] rangeShape(int start, int end) { 218 return getRange(start, end, TextLayout.TYPE_TEXT); 219 } 220 221 @Override 222 public boolean usesMirroring() { 223 return false; 224 } 225 226 @Override protected void setWidth(double value) { 227 if (value != getWidth()) { 228 TextLayout layout = getTextLayout(); 229 Insets insets = getInsets(); 230 double left = snapSpace(insets.getLeft()); 231 double right = snapSpace(insets.getRight()); 232 double width = Math.max(1, value - left - right); 233 layout.setWrapWidth((float)width); 234 super.setWidth(value); 235 } 236 } 237 238 @Override protected double computePrefWidth(double height) { 239 TextLayout layout = getTextLayout(); 240 layout.setWrapWidth(0); 241 double width = layout.getBounds().getWidth(); 242 Insets insets = getInsets(); 243 double left = snapSpace(insets.getLeft()); 244 double right = snapSpace(insets.getRight()); 245 double wrappingWidth = Math.max(1, getWidth() - left - right); 246 layout.setWrapWidth((float)wrappingWidth); 247 return left + width + right; 248 } 249 250 @Override protected double computePrefHeight(double width) { 251 TextLayout layout = getTextLayout(); 252 Insets insets = getInsets(); 253 double left = snapSpace(insets.getLeft()); 254 double right = snapSpace(insets.getRight()); 255 if (width == USE_COMPUTED_SIZE) { 256 layout.setWrapWidth(0); 257 } else { 258 double wrappingWidth = Math.max(1, width - left - right); 259 layout.setWrapWidth((float)wrappingWidth); 260 } 261 double height = layout.getBounds().getHeight(); 262 double wrappingWidth = Math.max(1, getWidth() - left - right); 263 layout.setWrapWidth((float)wrappingWidth); 264 double top = snapSpace(insets.getTop()); 265 double bottom = snapSpace(insets.getBottom()); 266 return top + height + bottom; 267 } 268 269 @Override protected double computeMinHeight(double width) { 270 return computePrefHeight(width); 271 } 272 273 @Override public void requestLayout() { 274 /* The geometry of text nodes can be changed during layout children. 275 * For that reason it has to call impl_geomChanged() causing 276 * requestLayout() to happen during layoutChildren(). 277 * The inLayout flag prevents this call to cause any extra work. 278 */ 279 if (inLayout) return; 280 281 /* 282 * There is no need to reset the text layout's content every time 283 * requestLayout() is called. For example, the content needs 284 * to be set when: 285 * children add or removed 286 * children managed state changes 287 * children geomChanged (width/height of embedded node) 288 * children content changes (text/font of text node) 289 * The content does not need to set when: 290 * the width/height changes in the region 291 * the insets changes in the region 292 * 293 * Unfortunately, it is not possible to know what change invoked request 294 * layout. The solution is to always reset the content in the text 295 * layout and rely on it to preserve itself if the new content equals to 296 * the old one. The cost to generate the new content is not avoid. 297 */ 298 needsContent = true; 299 super.requestLayout(); 300 } 301 302 @Override public Orientation getContentBias() { 303 return Orientation.HORIZONTAL; 304 } 305 306 @Override protected void layoutChildren() { 307 inLayout = true; 308 Insets insets = getInsets(); 309 double top = snapSpace(insets.getTop()); 310 double left = snapSpace(insets.getLeft()); 311 312 GlyphList[] runs = getTextLayout().getRuns(); 313 for (int j = 0; j < runs.length; j++) { 314 GlyphList run = runs[j]; 315 TextSpan span = run.getTextSpan(); 316 if (span instanceof EmbeddedSpan) { 317 Node child = ((EmbeddedSpan)span).getNode(); 318 Point2D location = run.getLocation(); 319 double baselineOffset = -run.getLineBounds().getMinY(); 320 321 layoutInArea(child, left + location.x, top + location.y, 322 run.getWidth(), run.getHeight(), 323 baselineOffset, null, true, true, 324 HPos.CENTER, VPos.BASELINE); 325 } 326 } 327 328 List<Node> managed = getManagedChildren(); 329 for (Node node: managed) { 330 if (node instanceof Text) { 331 Text text = (Text)node; 332 text.layoutSpan(runs); 333 BaseBounds spanBounds = text.getSpanBounds(); 334 text.relocate(left + spanBounds.getMinX(), 335 top + spanBounds.getMinY()); 336 } 337 } 338 inLayout = false; 339 } 340 341 private PathElement[] getRange(int start, int end, int type) { 342 TextLayout layout = getTextLayout(); 343 // int length = textLayout().getCharCount(); 344 // if (0 <= start && start < end && end <= length) { 345 return layout.getRange(start, end, type, 0, 0); 346 // } 347 // return EMPTY_PATH_ELEMENT_ARRAY; 348 } 349 350 private static class EmbeddedSpan implements TextSpan { 351 RectBounds bounds; 352 Node node; 353 public EmbeddedSpan(Node node, double baseline, double width, double height) { 354 this.node = node; 355 bounds = new RectBounds(0, (float)-baseline, 356 (float)width, (float)(height - baseline)); 357 } 358 359 @Override public String getText() { 360 return "\uFFFC"; 361 } 362 363 @Override public Object getFont() { 364 return null; 365 } 366 367 @Override public RectBounds getBounds() { 368 return bounds; 369 } 370 371 public Node getNode() { 372 return node; 373 } 374 } 375 376 TextLayout getTextLayout() { 377 if (layout == null) { 378 TextLayoutFactory factory = Toolkit.getToolkit().getTextLayoutFactory(); 379 layout = factory.createLayout(); 380 needsContent = true; 381 } 382 if (needsContent) { 383 List<Node> children = getManagedChildren(); 384 TextSpan[] spans = new TextSpan[children.size()]; 385 for (int i = 0; i < spans.length; i++) { 386 Node node = children.get(i); 387 if (node instanceof Text) { 388 spans[i] = ((Text)node).getTextSpan(); 389 } else { 390 /* Creating a text span every time forces text layout 391 * to run a full text analysis in the new content. 392 */ 393 double baseline = node.getBaselineOffset(); 394 if (baseline == BASELINE_OFFSET_SAME_AS_HEIGHT) { 395 baseline = node.getLayoutBounds().getHeight(); 396 } 397 double width = computeChildPrefAreaWidth(node, null); 398 double height = computeChildPrefAreaHeight(node, null); 399 spans[i] = new EmbeddedSpan(node, baseline, width, height); 400 } 401 } 402 layout.setContent(spans); 403 needsContent = false; 404 } 405 return layout; 406 } 407 408 /** 409 * Defines horizontal text alignment. 410 * 411 * @defaultValue TextAlignment.LEFT 412 */ 413 private ObjectProperty<TextAlignment> textAlignment; 414 415 public final void setTextAlignment(TextAlignment value) { 416 textAlignmentProperty().set(value); 417 } 418 419 public final TextAlignment getTextAlignment() { 420 return textAlignment == null ? TextAlignment.LEFT : textAlignment.get(); 421 } 422 423 public final ObjectProperty<TextAlignment> textAlignmentProperty() { 424 if (textAlignment == null) { 425 textAlignment = 426 new StyleableObjectProperty<TextAlignment>(TextAlignment.LEFT) { 427 @Override public Object getBean() { return TextFlow.this; } 428 @Override public String getName() { return "textAlignment"; } 429 @Override public CssMetaData<TextFlow, TextAlignment> getCssMetaData() { 430 return StyleableProperties.TEXT_ALIGNMENT; 431 } 432 @Override public void invalidated() { 433 TextAlignment align = get(); 434 if (align == null) align = TextAlignment.LEFT; 435 TextLayout layout = getTextLayout(); 436 layout.setAlignment(align.ordinal()); 437 requestLayout(); 438 } 439 }; 440 } 441 return textAlignment; 442 } 443 444 /** 445 * Defines the vertical space in pixel between lines. 446 * 447 * @defaultValue 0 448 * 449 * @since JavaFX 8.0 450 */ 451 private DoubleProperty lineSpacing; 452 453 public final void setLineSpacing(double spacing) { 454 lineSpacingProperty().set(spacing); 455 } 456 457 public final double getLineSpacing() { 458 return lineSpacing == null ? 0 : lineSpacing.get(); 459 } 460 461 public final DoubleProperty lineSpacingProperty() { 462 if (lineSpacing == null) { 463 lineSpacing = 464 new StyleableDoubleProperty(0) { 465 @Override public Object getBean() { return TextFlow.this; } 466 @Override public String getName() { return "lineSpacing"; } 467 @Override public CssMetaData<TextFlow, Number> getCssMetaData() { 468 return StyleableProperties.LINE_SPACING; 469 } 470 @Override public void invalidated() { 471 TextLayout layout = getTextLayout(); 472 if (layout.setLineSpacing((float)get())) { 473 requestLayout(); 474 } 475 } 476 }; 477 } 478 return lineSpacing; 479 } 480 481 @Override public final double getBaselineOffset() { 482 Insets insets = getInsets(); 483 double top = snapSpace(insets.getTop()); 484 return top - getTextLayout().getBounds().getMinY(); 485 } 486 487 /*************************************************************************** 488 * * 489 * Stylesheet Handling * 490 * * 491 **************************************************************************/ 492 493 /** 494 * Super-lazy instantiation pattern from Bill Pugh. 495 * @treatAsPrivate implementation detail 496 */ 497 private static class StyleableProperties { 498 499 private static final 500 CssMetaData<TextFlow, TextAlignment> TEXT_ALIGNMENT = 501 new CssMetaData<TextFlow,TextAlignment>("-fx-text-alignment", 502 new EnumConverter<TextAlignment>(TextAlignment.class), 503 TextAlignment.LEFT) { 504 505 @Override public boolean isSettable(TextFlow node) { 506 return node.textAlignment == null || !node.textAlignment.isBound(); 507 } 508 509 @Override public StyleableProperty<TextAlignment> getStyleableProperty(TextFlow node) { 510 return (StyleableProperty<TextAlignment>)node.textAlignmentProperty(); 511 } 512 }; 513 514 private static final 515 CssMetaData<TextFlow,Number> LINE_SPACING = 516 new CssMetaData<TextFlow,Number>("-fx-line-spacing", 517 SizeConverter.getInstance(), 0) { 518 519 @Override public boolean isSettable(TextFlow node) { 520 return node.lineSpacing == null || !node.lineSpacing.isBound(); 521 } 522 523 @Override public StyleableProperty<Number> getStyleableProperty(TextFlow node) { 524 return (StyleableProperty<Number>)node.lineSpacingProperty(); 525 } 526 }; 527 528 private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; 529 static { 530 final List<CssMetaData<? extends Styleable, ?>> styleables = 531 new ArrayList<CssMetaData<? extends Styleable, ?>>(Pane.getClassCssMetaData()); 532 styleables.add(TEXT_ALIGNMENT); 533 styleables.add(LINE_SPACING); 534 STYLEABLES = Collections.unmodifiableList(styleables); 535 } 536 } 537 538 /** 539 * @return The CssMetaData associated with this class, which may include the 540 * CssMetaData of its super classes. 541 */ 542 public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { 543 return StyleableProperties.STYLEABLES; 544 } 545 546 @Override 547 public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { 548 return getClassCssMetaData(); 549 } 550 551 /* The methods in this section are copied from Region due to package visibility restriction */ 552 private static double snapSpace(double value, boolean snapToPixel) { 553 return snapToPixel ? Math.round(value) : value; 554 } 555 556 static double boundedSize(double min, double pref, double max) { 557 double a = pref >= min ? pref : min; 558 double b = min >= max ? min : max; 559 return a <= b ? a : b; 560 } 561 562 double computeChildPrefAreaWidth(Node child, Insets margin) { 563 return computeChildPrefAreaWidth(child, margin, -1); 564 } 565 566 double computeChildPrefAreaWidth(Node child, Insets margin, double height) { 567 final boolean snap = isSnapToPixel(); 568 double top = margin != null? snapSpace(margin.getTop(), snap) : 0; 569 double bottom = margin != null? snapSpace(margin.getBottom(), snap) : 0; 570 double left = margin != null? snapSpace(margin.getLeft(), snap) : 0; 571 double right = margin != null? snapSpace(margin.getRight(), snap) : 0; 572 double alt = -1; 573 if (child.getContentBias() == Orientation.VERTICAL) { // width depends on height 574 alt = snapSize(boundedSize( 575 child.minHeight(-1), height != -1? height - top - bottom : 576 child.prefHeight(-1), child.maxHeight(-1))); 577 } 578 return left + snapSize(boundedSize(child.minWidth(alt), child.prefWidth(alt), child.maxWidth(alt))) + right; 579 } 580 581 double computeChildPrefAreaHeight(Node child, Insets margin) { 582 return computeChildPrefAreaHeight(child, margin, -1); 583 } 584 585 double computeChildPrefAreaHeight(Node child, Insets margin, double width) { 586 final boolean snap = isSnapToPixel(); 587 double top = margin != null? snapSpace(margin.getTop(), snap) : 0; 588 double bottom = margin != null? snapSpace(margin.getBottom(), snap) : 0; 589 double left = margin != null? snapSpace(margin.getLeft(), snap) : 0; 590 double right = margin != null? snapSpace(margin.getRight(), snap) : 0; 591 double alt = -1; 592 if (child.getContentBias() == Orientation.HORIZONTAL) { // height depends on width 593 alt = snapSize(boundedSize( 594 child.minWidth(-1), width != -1? width - left - right : 595 child.prefWidth(-1), child.maxWidth(-1))); 596 } 597 return top + snapSize(boundedSize(child.minHeight(alt), child.prefHeight(alt), child.maxHeight(alt))) + bottom; 598 } 599 /* end of copied code */ 600 601 @Override 602 public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) { 603 switch (attribute) { 604 case TEXT: { 605 String accText = getAccessibleText(); 606 if (accText != null && !accText.isEmpty()) return accText; 607 608 StringBuilder title = new StringBuilder(); 609 for (Node node: getChildren()) { 610 Object text = node.queryAccessibleAttribute(AccessibleAttribute.TEXT, parameters); 611 if (text != null) { 612 title.append(text.toString()); 613 } 614 } 615 return title.toString(); 616 } 617 default: return super.queryAccessibleAttribute(attribute, parameters); 618 } 619 } 620 }