1. /*
  2. * @(#)TextLayout.java 1.97 04/05/05
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * (C) Copyright Taligent, Inc. 1996 - 1997, All Rights Reserved
  9. * (C) Copyright IBM Corp. 1996-2003, All Rights Reserved
  10. *
  11. * The original version of this source code and documentation is
  12. * copyrighted and owned by Taligent, Inc., a wholly-owned subsidiary
  13. * of IBM. These materials are provided under terms of a License
  14. * Agreement between Taligent and Sun. This technology is protected
  15. * by multiple US and International patents.
  16. *
  17. * This notice and attribution to Taligent may not be removed.
  18. * Taligent is a registered trademark of Taligent, Inc.
  19. *
  20. */
  21. package java.awt.font;
  22. import java.awt.Color;
  23. import java.awt.Font;
  24. import java.awt.Graphics2D;
  25. import java.awt.Shape;
  26. import java.awt.font.NumericShaper;
  27. import java.awt.font.TextLine.TextLineMetrics;
  28. import java.awt.geom.AffineTransform;
  29. import java.awt.geom.GeneralPath;
  30. import java.awt.geom.Point2D;
  31. import java.awt.geom.Rectangle2D;
  32. import java.text.AttributedString;
  33. import java.text.AttributedCharacterIterator;
  34. import java.text.AttributedCharacterIterator.Attribute;
  35. import java.util.Map;
  36. import java.util.HashMap;
  37. import java.util.Hashtable;
  38. import sun.font.AdvanceCache;
  39. import sun.font.CoreMetrics;
  40. import sun.font.Decoration;
  41. import sun.font.FontLineMetrics;
  42. import sun.font.FontResolver;
  43. import sun.font.GraphicComponent;
  44. import sun.text.CodePointIterator;
  45. /**
  46. *
  47. * <code>TextLayout</code> is an immutable graphical representation of styled
  48. * character data.
  49. * <p>
  50. * It provides the following capabilities:
  51. * <ul>
  52. * <li>implicit bidirectional analysis and reordering,
  53. * <li>cursor positioning and movement, including split cursors for
  54. * mixed directional text,
  55. * <li>highlighting, including both logical and visual highlighting
  56. * for mixed directional text,
  57. * <li>multiple baselines (roman, hanging, and centered),
  58. * <li>hit testing,
  59. * <li>justification,
  60. * <li>default font substitution,
  61. * <li>metric information such as ascent, descent, and advance, and
  62. * <li>rendering
  63. * </ul>
  64. * <p>
  65. * A <code>TextLayout</code> object can be rendered using
  66. * its <code>draw</code> method.
  67. * <p>
  68. * <code>TextLayout</code> can be constructed either directly or through
  69. * the use of a {@link LineBreakMeasurer}. When constructed directly, the
  70. * source text represents a single paragraph. <code>LineBreakMeasurer</code>
  71. * allows styled text to be broken into lines that fit within a particular
  72. * width. See the <code>LineBreakMeasurer</code> documentation for more
  73. * information.
  74. * <p>
  75. * <code>TextLayout</code> construction logically proceeds as follows:
  76. * <ul>
  77. * <li>paragraph attributes are extracted and examined,
  78. * <li>text is analyzed for bidirectional reordering, and reordering
  79. * information is computed if needed,
  80. * <li>text is segmented into style runs
  81. * <li>fonts are chosen for style runs, first by using a font if the
  82. * attribute {@link TextAttribute#FONT} is present, otherwise by computing
  83. * a default font using the attributes that have been defined
  84. * <li>if text is on multiple baselines, the runs or subruns are further
  85. * broken into subruns sharing a common baseline,
  86. * <li>glyphvectors are generated for each run using the chosen font,
  87. * <li>final bidirectional reordering is performed on the glyphvectors
  88. * </ul>
  89. * <p>
  90. * All graphical information returned from a <code>TextLayout</code>
  91. * object's methods is relative to the origin of the
  92. * <code>TextLayout</code>, which is the intersection of the
  93. * <code>TextLayout</code> object's baseline with its left edge. Also,
  94. * coordinates passed into a <code>TextLayout</code> object's methods
  95. * are assumed to be relative to the <code>TextLayout</code> object's
  96. * origin. Clients usually need to translate between a
  97. * <code>TextLayout</code> object's coordinate system and the coordinate
  98. * system in another object (such as a
  99. * {@link java.awt.Graphics Graphics} object).
  100. * <p>
  101. * <code>TextLayout</code> objects are constructed from styled text,
  102. * but they do not retain a reference to their source text. Thus,
  103. * changes in the text previously used to generate a <code>TextLayout</code>
  104. * do not affect the <code>TextLayout</code>.
  105. * <p>
  106. * Three methods on a <code>TextLayout</code> object
  107. * (<code>getNextRightHit</code>, <code>getNextLeftHit</code>, and
  108. * <code>hitTestChar</code>) return instances of {@link TextHitInfo}.
  109. * The offsets contained in these <code>TextHitInfo</code> objects
  110. * are relative to the start of the <code>TextLayout</code>, <b>not</b>
  111. * to the text used to create the <code>TextLayout</code>. Similarly,
  112. * <code>TextLayout</code> methods that accept <code>TextHitInfo</code>
  113. * instances as parameters expect the <code>TextHitInfo</code> object's
  114. * offsets to be relative to the <code>TextLayout</code>, not to any
  115. * underlying text storage model.
  116. * <p>
  117. * <strong>Examples</strong>:<p>
  118. * Constructing and drawing a <code>TextLayout</code> and its bounding
  119. * rectangle:
  120. * <blockquote><pre>
  121. * Graphics2D g = ...;
  122. * Point2D loc = ...;
  123. * Font font = Font.getFont("Helvetica-bold-italic");
  124. * FontRenderContext frc = g.getFontRenderContext();
  125. * TextLayout layout = new TextLayout("This is a string", font, frc);
  126. * layout.draw(g, (float)loc.getX(), (float)loc.getY());
  127. *
  128. * Rectangle2D bounds = layout.getBounds();
  129. * bounds.setRect(bounds.getX()+loc.getX(),
  130. * bounds.getY()+loc.getY(),
  131. * bounds.getWidth(),
  132. * bounds.getHeight());
  133. * g.draw(bounds);
  134. * </pre>
  135. * </blockquote>
  136. * <p>
  137. * Hit-testing a <code>TextLayout</code> (determining which character is at
  138. * a particular graphical location):
  139. * <blockquote><pre>
  140. * Point2D click = ...;
  141. * TextHitInfo hit = layout.hitTestChar(
  142. * (float) (click.getX() - loc.getX()),
  143. * (float) (click.getY() - loc.getY()));
  144. * </pre>
  145. * </blockquote>
  146. * <p>
  147. * Responding to a right-arrow key press:
  148. * <blockquote><pre>
  149. * int insertionIndex = ...;
  150. * TextHitInfo next = layout.getNextRightHit(insertionIndex);
  151. * if (next != null) {
  152. * // translate graphics to origin of layout on screen
  153. * g.translate(loc.getX(), loc.getY());
  154. * Shape[] carets = layout.getCaretShapes(next.getInsertionIndex());
  155. * g.draw(carets[0]);
  156. * if (carets[1] != null) {
  157. * g.draw(carets[1]);
  158. * }
  159. * }
  160. * </pre></blockquote>
  161. * <p>
  162. * Drawing a selection range corresponding to a substring in the source text.
  163. * The selected area may not be visually contiguous:
  164. * <blockquote><pre>
  165. * // selStart, selLimit should be relative to the layout,
  166. * // not to the source text
  167. *
  168. * int selStart = ..., selLimit = ...;
  169. * Color selectionColor = ...;
  170. * Shape selection = layout.getLogicalHighlightShape(selStart, selLimit);
  171. * // selection may consist of disjoint areas
  172. * // graphics is assumed to be tranlated to origin of layout
  173. * g.setColor(selectionColor);
  174. * g.fill(selection);
  175. * </pre></blockquote>
  176. * <p>
  177. * Drawing a visually contiguous selection range. The selection range may
  178. * correspond to more than one substring in the source text. The ranges of
  179. * the corresponding source text substrings can be obtained with
  180. * <code>getLogicalRangesForVisualSelection()</code>:
  181. * <blockquote><pre>
  182. * TextHitInfo selStart = ..., selLimit = ...;
  183. * Shape selection = layout.getVisualHighlightShape(selStart, selLimit);
  184. * g.setColor(selectionColor);
  185. * g.fill(selection);
  186. * int[] ranges = getLogicalRangesForVisualSelection(selStart, selLimit);
  187. * // ranges[0], ranges[1] is the first selection range,
  188. * // ranges[2], ranges[3] is the second selection range, etc.
  189. * </pre></blockquote>
  190. * <p>
  191. * @see LineBreakMeasurer
  192. * @see TextAttribute
  193. * @see TextHitInfo
  194. */
  195. public final class TextLayout implements Cloneable {
  196. private int characterCount;
  197. private boolean isVerticalLine = false;
  198. private byte baseline;
  199. private float[] baselineOffsets; // why have these ?
  200. private TextLine textLine;
  201. // cached values computed from GlyphSets and set info:
  202. // all are recomputed from scratch in buildCache()
  203. private TextLine.TextLineMetrics lineMetrics = null;
  204. private float visibleAdvance;
  205. private int hashCodeCache;
  206. /**
  207. * temporary optimization
  208. */
  209. static class OptInfo implements Decoration.Label {
  210. private static final float MAGIC_ADVANCE = -12345.67f;
  211. // cache of required information for TextLine construction
  212. private FontRenderContext frc;
  213. private char[] chars;
  214. private Font font;
  215. private CoreMetrics metrics;
  216. private Map attrs;
  217. // deferred initialization
  218. private float advance;
  219. private Rectangle2D vb;
  220. private Decoration decoration;
  221. private String str;
  222. private OptInfo(FontRenderContext frc, char[] chars, Font font, CoreMetrics metrics, Map attrs) {
  223. this.frc = frc;
  224. this.chars = chars;
  225. this.font = font;
  226. this.metrics = metrics;
  227. this.attrs = attrs;
  228. if (attrs != null) {
  229. this.attrs = new HashMap(attrs); // sigh, need to clone since might change...
  230. }
  231. this.advance = MAGIC_ADVANCE;
  232. }
  233. TextLine createTextLine() {
  234. return TextLine.fastCreateTextLine(frc, chars, font, metrics, attrs);
  235. }
  236. float getAdvance() {
  237. if (advance == MAGIC_ADVANCE) {
  238. AdvanceCache adv = AdvanceCache.get(font, frc);
  239. advance = adv.getAdvance(chars, 0, chars.length); // we pretested the chars array so no exception here
  240. }
  241. return advance;
  242. }
  243. // Decoration.Label reqd.
  244. public CoreMetrics getCoreMetrics() {
  245. return metrics;
  246. }
  247. // Decoration.Label reqd.
  248. public Rectangle2D getLogicalBounds() {
  249. return new Rectangle2D.Float(0, -metrics.ascent, getAdvance(), metrics.height);
  250. }
  251. // Decoration.Label reqd.
  252. public void handleDraw(Graphics2D g2d, float x, float y) {
  253. if (str == null) {
  254. str = new String(chars, 0, chars.length);
  255. }
  256. g2d.drawString(str, x , y);
  257. }
  258. // Decoration.Label reqd.
  259. public Rectangle2D handleGetCharVisualBounds(int index) {
  260. // not used
  261. throw new InternalError();
  262. }
  263. // Decoration.Label reqd.
  264. public Rectangle2D handleGetVisualBounds() {
  265. AdvanceCache adv = AdvanceCache.get(font, frc);
  266. return adv.getVisualBounds(chars, 0, chars.length);
  267. }
  268. // Decoration.Label reqd.
  269. public Shape handleGetOutline(float x, float y) {
  270. // not used
  271. throw new InternalError();
  272. }
  273. // if we could successfully draw, then return true
  274. boolean draw(Graphics2D g2d, float x, float y) {
  275. // If the frc differs from the graphics frc, we punt to TextLayout because the
  276. // metrics might be different...
  277. if (g2d.getFontRenderContext().equals(frc)) {
  278. Font oldFont = g2d.getFont();
  279. g2d.setFont(font);
  280. getDecoration().drawTextAndDecorations(this, g2d, x, y);
  281. g2d.setFont(oldFont);
  282. return true;
  283. }
  284. return false;
  285. }
  286. Rectangle2D getVisualBounds() {
  287. if (vb == null) {
  288. vb = getDecoration().getVisualBounds(this);
  289. }
  290. return (Rectangle2D)vb.clone();
  291. }
  292. Decoration getDecoration() {
  293. if (decoration == null) {
  294. if (attrs == null) {
  295. decoration = Decoration.getDecoration(null);
  296. } else {
  297. decoration = Decoration.getDecoration(StyledParagraph.addInputMethodAttrs(attrs));
  298. }
  299. }
  300. return decoration;
  301. }
  302. static OptInfo create(FontRenderContext frc, char[] chars, Font font, CoreMetrics metrics, Map attrs) {
  303. // Preflight text to make sure advance cache supports it, otherwise it would throw an exception.
  304. // We also need to preflight to make sure we don't require layout. If we limit optimizations to
  305. // latin-1 we handle both cases. We could add an additional check for Japanese since currently
  306. // it doesn't require layout and the advance cache would be simple, but right now we don't.
  307. if (!font.isTransformed() && AdvanceCache.supportsText(chars)) {
  308. if (attrs == null || attrs.get(TextAttribute.CHAR_REPLACEMENT) == null) {
  309. return new OptInfo(frc, chars, font, metrics, attrs);
  310. }
  311. }
  312. return null;
  313. }
  314. }
  315. private OptInfo optInfo;
  316. /*
  317. * TextLayouts are supposedly immutable. If you mutate a TextLayout under
  318. * the covers (like the justification code does) you'll need to set this
  319. * back to false. Could be replaced with textLine != null <--> cacheIsValid.
  320. */
  321. private boolean cacheIsValid = false;
  322. // This value is obtained from an attribute, and constrained to the
  323. // interval [0,1]. If 0, the layout cannot be justified.
  324. private float justifyRatio;
  325. // If a layout is produced by justification, then that layout
  326. // cannot be justified. To enforce this constraint the
  327. // justifyRatio of the justified layout is set to this value.
  328. private static final float ALREADY_JUSTIFIED = -53.9f;
  329. // dx and dy specify the distance between the TextLayout's origin
  330. // and the origin of the leftmost GlyphSet (TextLayoutComponent,
  331. // actually). They were used for hanging punctuation support,
  332. // which is no longer implemented. Currently they are both always 0,
  333. // and TextLayout is not guaranteed to work with non-zero dx, dy
  334. // values right now. They were left in as an aide and reminder to
  335. // anyone who implements hanging punctuation or other similar stuff.
  336. // They are static now so they don't take up space in TextLayout
  337. // instances.
  338. private static float dx;
  339. private static float dy;
  340. /*
  341. * Natural bounds is used internally. It is built on demand in
  342. * getNaturalBounds.
  343. */
  344. private Rectangle2D naturalBounds = null;
  345. /*
  346. * boundsRect encloses all of the bits this TextLayout can draw. It
  347. * is build on demand in getBounds.
  348. */
  349. private Rectangle2D boundsRect = null;
  350. /*
  351. * flag to supress/allow carets inside of ligatures when hit testing or
  352. * arrow-keying
  353. */
  354. private boolean caretsInLigaturesAreAllowed = false;
  355. /**
  356. * Defines a policy for determining the strong caret location.
  357. * This class contains one method, <code>getStrongCaret</code>, which
  358. * is used to specify the policy that determines the strong caret in
  359. * dual-caret text. The strong caret is used to move the caret to the
  360. * left or right. Instances of this class can be passed to
  361. * <code>getCaretShapes</code>, <code>getNextLeftHit</code> and
  362. * <code>getNextRightHit</code> to customize strong caret
  363. * selection.
  364. * <p>
  365. * To specify alternate caret policies, subclass <code>CaretPolicy</code>
  366. * and override <code>getStrongCaret</code>. <code>getStrongCaret</code>
  367. * should inspect the two <code>TextHitInfo</code> arguments and choose
  368. * one of them as the strong caret.
  369. * <p>
  370. * Most clients do not need to use this class.
  371. */
  372. public static class CaretPolicy {
  373. /**
  374. * Constructs a <code>CaretPolicy</code>.
  375. */
  376. public CaretPolicy() {
  377. }
  378. /**
  379. * Chooses one of the specified <code>TextHitInfo</code> instances as
  380. * a strong caret in the specified <code>TextLayout</code>.
  381. * @param hit1 a valid hit in <code>layout</code>
  382. * @param hit2 a valid hit in <code>layout</code>
  383. * @param layout the <code>TextLayout</code> in which
  384. * <code>hit1</code> and <code>hit2</code> are used
  385. * @return <code>hit1</code> or <code>hit2</code>
  386. * (or an equivalent <code>TextHitInfo</code>), indicating the
  387. * strong caret.
  388. */
  389. public TextHitInfo getStrongCaret(TextHitInfo hit1,
  390. TextHitInfo hit2,
  391. TextLayout layout) {
  392. // default implmentation just calls private method on layout
  393. return layout.getStrongHit(hit1, hit2);
  394. }
  395. }
  396. /**
  397. * This <code>CaretPolicy</code> is used when a policy is not specified
  398. * by the client. With this policy, a hit on a character whose direction
  399. * is the same as the line direction is stronger than a hit on a
  400. * counterdirectional character. If the characters' directions are
  401. * the same, a hit on the leading edge of a character is stronger
  402. * than a hit on the trailing edge of a character.
  403. */
  404. public static final CaretPolicy DEFAULT_CARET_POLICY = new CaretPolicy();
  405. /**
  406. * Constructs a <code>TextLayout</code> from a <code>String</code>
  407. * and a {@link Font}. All the text is styled using the specified
  408. * <code>Font</code>.
  409. * <p>
  410. * The <code>String</code> must specify a single paragraph of text,
  411. * because an entire paragraph is required for the bidirectional
  412. * algorithm.
  413. * @param string the text to display
  414. * @param font a <code>Font</code> used to style the text
  415. * @param frc contains information about a graphics device which is needed
  416. * to measure the text correctly.
  417. * Text measurements can vary slightly depending on the
  418. * device resolution, and attributes such as antialiasing. This
  419. * parameter does not specify a translation between the
  420. * <code>TextLayout</code> and user space.
  421. */
  422. public TextLayout(String string, Font font, FontRenderContext frc) {
  423. if (font == null) {
  424. throw new IllegalArgumentException("Null font passed to TextLayout constructor.");
  425. }
  426. if (string == null) {
  427. throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
  428. }
  429. if (string.length() == 0) {
  430. throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
  431. }
  432. char[] text = string.toCharArray();
  433. if (sameBaselineUpTo(font, text, 0, text.length) == text.length) {
  434. fastInit(text, font, null, frc);
  435. } else {
  436. AttributedString as = new AttributedString(string);
  437. as.addAttribute(TextAttribute.FONT, font);
  438. standardInit(as.getIterator(), text, frc);
  439. }
  440. }
  441. /**
  442. * Constructs a <code>TextLayout</code> from a <code>String</code>
  443. * and an attribute set.
  444. * <p>
  445. * All the text is styled using the provided attributes.
  446. * <p>
  447. * <code>string</code> must specify a single paragraph of text because an
  448. * entire paragraph is required for the bidirectional algorithm.
  449. * @param string the text to display
  450. * @param attributes the attributes used to style the text
  451. * @param frc contains information about a graphics device which is needed
  452. * to measure the text correctly.
  453. * Text measurements can vary slightly depending on the
  454. * device resolution, and attributes such as antialiasing. This
  455. * parameter does not specify a translation between the
  456. * <code>TextLayout</code> and user space.
  457. */
  458. public TextLayout(String string, Map<? extends Attribute,?> attributes,
  459. FontRenderContext frc)
  460. {
  461. if (string == null) {
  462. throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
  463. }
  464. if (attributes == null) {
  465. throw new IllegalArgumentException("Null map passed to TextLayout constructor.");
  466. }
  467. if (string.length() == 0) {
  468. throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
  469. }
  470. char[] text = string.toCharArray();
  471. Font font = singleFont(text, 0, text.length, attributes);
  472. if (font != null) {
  473. fastInit(text, font, attributes, frc);
  474. } else {
  475. AttributedString as = new AttributedString(string, attributes);
  476. standardInit(as.getIterator(), text, frc);
  477. }
  478. }
  479. /*
  480. * Determines a font for the attributes, and if a single font can render
  481. * all the text on one baseline, return it, otherwise null. If the
  482. * attributes specify a font, assume it can display all the text without
  483. * checking.
  484. * If the AttributeSet contains an embedded graphic, return null.
  485. */
  486. private static Font singleFont(char[] text,
  487. int start,
  488. int limit,
  489. Map attributes) {
  490. if (attributes.get(TextAttribute.CHAR_REPLACEMENT) != null) {
  491. return null;
  492. }
  493. Font font = (Font)attributes.get(TextAttribute.FONT);
  494. if (font == null) {
  495. if (attributes.get(TextAttribute.FAMILY) != null) {
  496. font = Font.getFont(attributes);
  497. if (font.canDisplayUpTo(text, start, limit) != -1) {
  498. return null;
  499. }
  500. } else {
  501. FontResolver resolver = FontResolver.getInstance();
  502. CodePointIterator iter = CodePointIterator.create(text, start, limit);
  503. int fontIndex = resolver.nextFontRunIndex(iter);
  504. if (iter.charIndex() == limit) {
  505. font = resolver.getFont(fontIndex, attributes);
  506. }
  507. }
  508. }
  509. if (sameBaselineUpTo(font, text, start, limit) != limit) {
  510. return null;
  511. }
  512. return font;
  513. }
  514. /**
  515. * Constructs a <code>TextLayout</code> from an iterator over styled text.
  516. * <p>
  517. * The iterator must specify a single paragraph of text because an
  518. * entire paragraph is required for the bidirectional
  519. * algorithm.
  520. * @param text the styled text to display
  521. * @param frc contains information about a graphics device which is needed
  522. * to measure the text correctly.
  523. * Text measurements can vary slightly depending on the
  524. * device resolution, and attributes such as antialiasing. This
  525. * parameter does not specify a translation between the
  526. * <code>TextLayout</code> and user space.
  527. */
  528. public TextLayout(AttributedCharacterIterator text, FontRenderContext frc) {
  529. if (text == null) {
  530. throw new IllegalArgumentException("Null iterator passed to TextLayout constructor.");
  531. }
  532. int start = text.getBeginIndex();
  533. int limit = text.getEndIndex();
  534. if (start == limit) {
  535. throw new IllegalArgumentException("Zero length iterator passed to TextLayout constructor.");
  536. }
  537. int len = limit - start;
  538. text.first();
  539. char[] chars = new char[len];
  540. int n = 0;
  541. for (char c = text.first(); c != text.DONE; c = text.next()) {
  542. chars[n++] = c;
  543. }
  544. text.first();
  545. if (text.getRunLimit() == limit) {
  546. Map attributes = text.getAttributes();
  547. Font font = singleFont(chars, 0, len, attributes);
  548. if (font != null) {
  549. fastInit(chars, font, attributes, frc);
  550. return;
  551. }
  552. }
  553. standardInit(text, chars, frc);
  554. }
  555. /**
  556. * Creates a <code>TextLayout</code> from a {@link TextLine} and
  557. * some paragraph data. This method is used by {@link TextMeasurer}.
  558. * @param textLine the line measurement attributes to apply to the
  559. * the resulting <code>TextLayout</code>
  560. * @param baseline the baseline of the text
  561. * @param baselineOffsets the baseline offsets for this
  562. * <code>TextLayout</code>. This should already be normalized to
  563. * <code>baseline</code>
  564. * @param justifyRatio <code>0</code> if the <code>TextLayout</code>
  565. * cannot be justified; <code>1</code> otherwise.
  566. */
  567. TextLayout(TextLine textLine,
  568. byte baseline,
  569. float[] baselineOffsets,
  570. float justifyRatio) {
  571. this.characterCount = textLine.characterCount();
  572. this.baseline = baseline;
  573. this.baselineOffsets = baselineOffsets;
  574. this.textLine = textLine;
  575. this.justifyRatio = justifyRatio;
  576. }
  577. /**
  578. * Initialize the paragraph-specific data.
  579. */
  580. private void paragraphInit(byte aBaseline, CoreMetrics lm, Map paragraphAttrs, char[] text) {
  581. baseline = aBaseline;
  582. // normalize to current baseline
  583. baselineOffsets = TextLine.getNormalizedOffsets(lm.baselineOffsets, baseline);
  584. justifyRatio = TextLine.getJustifyRatio(paragraphAttrs);
  585. if (paragraphAttrs != null) {
  586. Object o = paragraphAttrs.get(TextAttribute.NUMERIC_SHAPING);
  587. if (o != null) {
  588. try {
  589. NumericShaper shaper = (NumericShaper)o;
  590. shaper.shape(text, 0, text.length);
  591. }
  592. catch (ClassCastException e) {
  593. }
  594. }
  595. }
  596. }
  597. /*
  598. * the fast init generates a single glyph set. This requires:
  599. * all one style
  600. * all renderable by one font (ie no embedded graphics)
  601. * all on one baseline
  602. */
  603. private void fastInit(char[] chars, Font font, Map attrs, FontRenderContext frc) {
  604. // Object vf = attrs.get(TextAttribute.ORIENTATION);
  605. // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
  606. isVerticalLine = false;
  607. LineMetrics lm = font.getLineMetrics(chars, 0, chars.length, frc);
  608. CoreMetrics cm = CoreMetrics.get(lm);
  609. byte glyphBaseline = (byte) cm.baselineIndex;
  610. if (attrs == null) {
  611. baseline = glyphBaseline;
  612. baselineOffsets = cm.baselineOffsets;
  613. justifyRatio = 1.0f;
  614. } else {
  615. paragraphInit(glyphBaseline, cm, attrs, chars);
  616. }
  617. characterCount = chars.length;
  618. optInfo = OptInfo.create(frc, chars, font, cm, attrs);
  619. if (optInfo == null) {
  620. textLine = TextLine.fastCreateTextLine(frc, chars, font, cm, attrs);
  621. }
  622. }
  623. private void initTextLine() {
  624. textLine = optInfo.createTextLine();
  625. optInfo = null;
  626. }
  627. /*
  628. * the standard init generates multiple glyph sets based on style,
  629. * renderable, and baseline runs.
  630. * @param chars the text in the iterator, extracted into a char array
  631. */
  632. private void standardInit(AttributedCharacterIterator text, char[] chars, FontRenderContext frc) {
  633. characterCount = chars.length;
  634. // set paragraph attributes
  635. {
  636. // If there's an embedded graphic at the start of the
  637. // paragraph, look for the first non-graphic character
  638. // and use it and its font to initialize the paragraph.
  639. // If not, use the first graphic to initialize.
  640. Map paragraphAttrs = text.getAttributes();
  641. boolean haveFont = TextLine.advanceToFirstFont(text);
  642. if (haveFont) {
  643. Font defaultFont = TextLine.getFontAtCurrentPos(text);
  644. int charsStart = text.getIndex() - text.getBeginIndex();
  645. LineMetrics lm = defaultFont.getLineMetrics(chars, charsStart, charsStart+1, frc);
  646. CoreMetrics cm = CoreMetrics.get(lm);
  647. paragraphInit((byte)cm.baselineIndex, cm, paragraphAttrs, chars);
  648. }
  649. else {
  650. // hmmm what to do here? Just try to supply reasonable
  651. // values I guess.
  652. GraphicAttribute graphic = (GraphicAttribute)
  653. paragraphAttrs.get(TextAttribute.CHAR_REPLACEMENT);
  654. byte defaultBaseline = getBaselineFromGraphic(graphic);
  655. CoreMetrics cm = GraphicComponent.createCoreMetrics(graphic);
  656. paragraphInit(defaultBaseline, cm, paragraphAttrs, chars);
  657. }
  658. }
  659. textLine = TextLine.standardCreateTextLine(frc, text, chars, baselineOffsets);
  660. }
  661. /*
  662. * A utility to rebuild the ascent/descent/leading/advance cache.
  663. * You'll need to call this if you clone and mutate (like justification,
  664. * editing methods do)
  665. */
  666. private void ensureCache() {
  667. if (!cacheIsValid) {
  668. buildCache();
  669. }
  670. }
  671. private void buildCache() {
  672. if (textLine == null) {
  673. initTextLine();
  674. }
  675. lineMetrics = textLine.getMetrics();
  676. // compute visibleAdvance
  677. if (textLine.isDirectionLTR()) {
  678. int lastNonSpace = characterCount-1;
  679. while (lastNonSpace != -1) {
  680. int logIndex = textLine.visualToLogical(lastNonSpace);
  681. if (!textLine.isCharSpace(logIndex)) {
  682. break;
  683. }
  684. else {
  685. --lastNonSpace;
  686. }
  687. }
  688. if (lastNonSpace == characterCount-1) {
  689. visibleAdvance = lineMetrics.advance;
  690. }
  691. else if (lastNonSpace == -1) {
  692. visibleAdvance = 0;
  693. }
  694. else {
  695. int logIndex = textLine.visualToLogical(lastNonSpace);
  696. visibleAdvance = textLine.getCharLinePosition(logIndex)
  697. + textLine.getCharAdvance(logIndex);
  698. }
  699. }
  700. else {
  701. int leftmostNonSpace = 0;
  702. while (leftmostNonSpace != characterCount) {
  703. int logIndex = textLine.visualToLogical(leftmostNonSpace);
  704. if (!textLine.isCharSpace(logIndex)) {
  705. break;
  706. }
  707. else {
  708. ++leftmostNonSpace;
  709. }
  710. }
  711. if (leftmostNonSpace == characterCount) {
  712. visibleAdvance = 0;
  713. }
  714. else if (leftmostNonSpace == 0) {
  715. visibleAdvance = lineMetrics.advance;
  716. }
  717. else {
  718. int logIndex = textLine.visualToLogical(leftmostNonSpace);
  719. float pos = textLine.getCharLinePosition(logIndex);
  720. visibleAdvance = lineMetrics.advance - pos;
  721. }
  722. }
  723. // naturalBounds, boundsRect will be generated on demand
  724. naturalBounds = null;
  725. boundsRect = null;
  726. // hashCode will be regenerated on demand
  727. hashCodeCache = 0;
  728. cacheIsValid = true;
  729. }
  730. /**
  731. * The 'natural bounds' encloses all the carets the layout can draw.
  732. *
  733. */
  734. private Rectangle2D getNaturalBounds() {
  735. ensureCache();
  736. if (naturalBounds == null) {
  737. naturalBounds = textLine.getItalicBounds();
  738. }
  739. return naturalBounds;
  740. }
  741. /**
  742. * Creates a copy of this <code>TextLayout</code>.
  743. */
  744. protected Object clone() {
  745. /*
  746. * !!! I think this is safe. Once created, nothing mutates the
  747. * glyphvectors or arrays. But we need to make sure.
  748. * {jbr} actually, that's not quite true. The justification code
  749. * mutates after cloning. It doesn't actually change the glyphvectors
  750. * (that's impossible) but it replaces them with justified sets. This
  751. * is a problem for GlyphIterator creation, since new GlyphIterators
  752. * are created by cloning a prototype. If the prototype has outdated
  753. * glyphvectors, so will the new ones. A partial solution is to set the
  754. * prototypical GlyphIterator to null when the glyphvectors change. If
  755. * you forget this one time, you're hosed.
  756. */
  757. try {
  758. return super.clone();
  759. }
  760. catch (CloneNotSupportedException e) {
  761. throw new InternalError();
  762. }
  763. }
  764. /*
  765. * Utility to throw an expection if an invalid TextHitInfo is passed
  766. * as a parameter. Avoids code duplication.
  767. */
  768. private void checkTextHit(TextHitInfo hit) {
  769. if (hit == null) {
  770. throw new IllegalArgumentException("TextHitInfo is null.");
  771. }
  772. if (hit.getInsertionIndex() < 0 ||
  773. hit.getInsertionIndex() > characterCount) {
  774. throw new IllegalArgumentException("TextHitInfo is out of range");
  775. }
  776. }
  777. /**
  778. * Creates a copy of this <code>TextLayout</code> justified to the
  779. * specified width.
  780. * <p>
  781. * If this <code>TextLayout</code> has already been justified, an
  782. * exception is thrown. If this <code>TextLayout</code> object's
  783. * justification ratio is zero, a <code>TextLayout</code> identical
  784. * to this <code>TextLayout</code> is returned.
  785. * @param justificationWidth the width to use when justifying the line.
  786. * For best results, it should not be too different from the current
  787. * advance of the line.
  788. * @return a <code>TextLayout</code> justified to the specified width.
  789. * @exception Error if this layout has already been justified, an Error is
  790. * thrown.
  791. */
  792. public TextLayout getJustifiedLayout(float justificationWidth) {
  793. if (justificationWidth <= 0) {
  794. throw new IllegalArgumentException("justificationWidth <= 0 passed to TextLayout.getJustifiedLayout()");
  795. }
  796. if (justifyRatio == ALREADY_JUSTIFIED) {
  797. throw new Error("Can't justify again.");
  798. }
  799. ensureCache(); // make sure textLine is not null
  800. // default justification range to exclude trailing logical whitespace
  801. int limit = characterCount;
  802. while (limit > 0 && textLine.isCharWhitespace(limit-1)) {
  803. --limit;
  804. }
  805. TextLine newLine = textLine.getJustifiedLine(justificationWidth, justifyRatio, 0, limit);
  806. if (newLine != null) {
  807. return new TextLayout(newLine, baseline, baselineOffsets, ALREADY_JUSTIFIED);
  808. }
  809. return this;
  810. }
  811. /**
  812. * Justify this layout. Overridden by subclassers to control justification
  813. * (if there were subclassers, that is...)
  814. *
  815. * The layout will only justify if the paragraph attributes (from the
  816. * source text, possibly defaulted by the layout attributes) indicate a
  817. * non-zero justification ratio. The text will be justified to the
  818. * indicated width. The current implementation also adjusts hanging
  819. * punctuation and trailing whitespace to overhang the justification width.
  820. * Once justified, the layout may not be rejustified.
  821. * <p>
  822. * Some code may rely on immutablity of layouts. Subclassers should not
  823. * call this directly, but instead should call getJustifiedLayout, which
  824. * will call this method on a clone of this layout, preserving
  825. * the original.
  826. *
  827. * @param justificationWidth the width to use when justifying the line.
  828. * For best results, it should not be too different from the current
  829. * advance of the line.
  830. * @see #getJustifiedLayout(float)
  831. */
  832. protected void handleJustify(float justificationWidth) {
  833. // never called
  834. }
  835. /**
  836. * Returns the baseline for this <code>TextLayout</code>.
  837. * The baseline is one of the values defined in <code>Font</code>,
  838. * which are roman, centered and hanging. Ascent and descent are
  839. * relative to this baseline. The <code>baselineOffsets</code>
  840. * are also relative to this baseline.
  841. * @return the baseline of this <code>TextLayout</code>.
  842. * @see #getBaselineOffsets()
  843. * @see Font
  844. */
  845. public byte getBaseline() {
  846. return baseline;
  847. }
  848. /**
  849. * Returns the offsets array for the baselines used for this
  850. * <code>TextLayout</code>.
  851. * <p>
  852. * The array is indexed by one of the values defined in
  853. * <code>Font</code>, which are roman, centered and hanging. The
  854. * values are relative to this <code>TextLayout</code> object's
  855. * baseline, so that <code>getBaselineOffsets[getBaseline()] == 0</code>.
  856. * Offsets are added to the position of the <code>TextLayout</code>
  857. * object's baseline to get the position for the new baseline.
  858. * @return the offsets array containing the baselines used for this
  859. * <code>TextLayout</code>.
  860. * @see #getBaseline()
  861. * @see Font
  862. */
  863. public float[] getBaselineOffsets() {
  864. float[] offsets = new float[baselineOffsets.length];
  865. System.arraycopy(baselineOffsets, 0, offsets, 0, offsets.length);
  866. return offsets;
  867. }
  868. /**
  869. * Returns the advance of this <code>TextLayout</code>.
  870. * The advance is the distance from the origin to the advance of the
  871. * rightmost (bottommost) character measuring in the line direction.
  872. * @return the advance of this <code>TextLayout</code>.
  873. */
  874. public float getAdvance() {
  875. if (optInfo != null) {
  876. try {
  877. return optInfo.getAdvance();
  878. }
  879. catch (Error e) {
  880. // cache was flushed under optInfo
  881. }
  882. }
  883. ensureCache();
  884. return lineMetrics.advance;
  885. }
  886. /**
  887. * Returns the advance of this <code>TextLayout</code>, minus trailing
  888. * whitespace.
  889. * @return the advance of this <code>TextLayout</code> without the
  890. * trailing whitespace.
  891. * @see #getAdvance()
  892. */
  893. public float getVisibleAdvance() {
  894. ensureCache();
  895. return visibleAdvance;
  896. }
  897. /**
  898. * Returns the ascent of this <code>TextLayout</code>.
  899. * The ascent is the distance from the top (right) of the
  900. * <code>TextLayout</code> to the baseline. It is always either
  901. * positive or zero. The ascent is sufficient to
  902. * accomodate superscripted text and is the maximum of the sum of the
  903. * ascent, offset, and baseline of each glyph.
  904. * @return the ascent of this <code>TextLayout</code>.
  905. */
  906. public float getAscent() {
  907. if (optInfo != null) {
  908. return optInfo.getCoreMetrics().ascent;
  909. }
  910. ensureCache();
  911. return lineMetrics.ascent;
  912. }
  913. /**
  914. * Returns the descent of this <code>TextLayout</code>.
  915. * The descent is the distance from the baseline to the bottom (left) of
  916. * the <code>TextLayout</code>. It is always either positive or zero.
  917. * The descent is sufficient to accomodate subscripted text and is the
  918. * maximum of the sum of the descent, offset, and baseline of each glyph.
  919. * @return the descent of this <code>TextLayout</code>.
  920. */
  921. public float getDescent() {
  922. if (optInfo != null) {
  923. return optInfo.getCoreMetrics().descent;
  924. }
  925. ensureCache();
  926. return lineMetrics.descent;
  927. }
  928. /**
  929. * Returns the leading of the <code>TextLayout</code>.
  930. * The leading is the suggested interline spacing for this
  931. * <code>TextLayout</code>.
  932. * <p>
  933. * The leading is computed from the leading, descent, and baseline
  934. * of all glyphvectors in the <code>TextLayout</code>. The algorithm
  935. * is roughly as follows:
  936. * <blockquote><pre>
  937. * maxD = 0;
  938. * maxDL = 0;
  939. * for (GlyphVector g in all glyphvectors) {
  940. * maxD = max(maxD, g.getDescent() + offsets[g.getBaseline()]);
  941. * maxDL = max(maxDL, g.getDescent() + g.getLeading() +
  942. * offsets[g.getBaseline()]);
  943. * }
  944. * return maxDL - maxD;
  945. * </pre></blockquote>
  946. * @return the leading of this <code>TextLayout</code>.
  947. */
  948. public float getLeading() {
  949. if (optInfo != null) {
  950. return optInfo.getCoreMetrics().leading;
  951. }
  952. ensureCache();
  953. return lineMetrics.leading;
  954. }
  955. /**
  956. * Returns the bounds of this <code>TextLayout</code>.
  957. * The bounds contains all of the pixels the <code>TextLayout</code>
  958. * can draw. It might not coincide exactly with the ascent, descent,
  959. * origin or advance of the <code>TextLayout</code>.
  960. * @return a {@link Rectangle2D} that is the bounds of this
  961. * <code>TextLayout</code>.
  962. */
  963. public Rectangle2D getBounds() {
  964. if (optInfo != null) {
  965. return optInfo.getVisualBounds();
  966. }
  967. ensureCache();
  968. if (boundsRect == null) {
  969. Rectangle2D lineBounds = textLine.getBounds();
  970. if (dx != 0 || dy != 0) {
  971. lineBounds.setRect(lineBounds.getX() - dx,
  972. lineBounds.getY() - dy,
  973. lineBounds.getWidth(),
  974. lineBounds.getHeight());
  975. }
  976. boundsRect = lineBounds;
  977. }
  978. Rectangle2D bounds = new Rectangle2D.Float();
  979. bounds.setRect(boundsRect);
  980. return bounds;
  981. }
  982. /**
  983. * Returns <code>true</code> if this <code>TextLayout</code> has
  984. * a left-to-right base direction or <code>false</code> if it has
  985. * a right-to-left base direction. The <code>TextLayout</code>
  986. * has a base direction of either left-to-right (LTR) or
  987. * right-to-left (RTL). The base direction is independent of the
  988. * actual direction of text on the line, which may be either LTR,
  989. * RTL, or mixed. Left-to-right layouts by default should position
  990. * flush left. If the layout is on a tabbed line, the
  991. * tabs run left to right, so that logically successive layouts position
  992. * left to right. The opposite is true for RTL layouts. By default they
  993. * should position flush left, and tabs run right-to-left.
  994. * @return <code>true</code> if the base direction of this
  995. * <code>TextLayout</code> is left-to-right; <code>false</code>
  996. * otherwise.
  997. */
  998. public boolean isLeftToRight() {
  999. return (optInfo != null) || textLine.isDirectionLTR();
  1000. }
  1001. /**
  1002. * Returns <code>true</code> if this <code>TextLayout</code> is vertical.
  1003. * @return <code>true</code> if this <code>TextLayout</code> is vertical;
  1004. * <code>false</code> otherwise.
  1005. */
  1006. public boolean isVertical() {
  1007. return isVerticalLine;
  1008. }
  1009. /**
  1010. * Returns the number of characters represented by this
  1011. * <code>TextLayout</code>.
  1012. * @return the number of characters in this <code>TextLayout</code>.
  1013. */
  1014. public int getCharacterCount() {
  1015. return characterCount;
  1016. }
  1017. /*
  1018. * carets and hit testing
  1019. *
  1020. * Positions on a text line are represented by instances of TextHitInfo.
  1021. * Any TextHitInfo with characterOffset between 0 and characterCount-1,
  1022. * inclusive, represents a valid position on the line. Additionally,
  1023. * [-1, trailing] and [characterCount, leading] are valid positions, and
  1024. * represent positions at the logical start and end of the line,
  1025. * respectively.
  1026. *
  1027. * The characterOffsets in TextHitInfo's used and returned by TextLayout
  1028. * are relative to the beginning of the text layout, not necessarily to
  1029. * the beginning of the text storage the client is using.
  1030. *
  1031. *
  1032. * Every valid TextHitInfo has either one or two carets associated with it.
  1033. * A caret is a visual location in the TextLayout indicating where text at
  1034. * the TextHitInfo will be displayed on screen. If a TextHitInfo
  1035. * represents a location on a directional boundary, then there are two
  1036. * possible visible positions for newly inserted text. Consider the
  1037. * following example, in which capital letters indicate right-to-left text,
  1038. * and the overall line direction is left-to-right:
  1039. *
  1040. * Text Storage: [ a, b, C, D, E, f ]
  1041. * Display: a b E D C f
  1042. *
  1043. * The text hit info (1, t) represents the trailing side of 'b'. If 'q',
  1044. * a left-to-right character is inserted into the text storage at this
  1045. * location, it will be displayed between the 'b' and the 'E':
  1046. *
  1047. * Text Storage: [ a, b, q, C, D, E, f ]
  1048. * Display: a b q E D C f
  1049. *
  1050. * However, if a 'W', which is right-to-left, is inserted into the storage
  1051. * after 'b', the storage and display will be:
  1052. *
  1053. * Text Storage: [ a, b, W, C, D, E, f ]
  1054. * Display: a b E D C W f
  1055. *
  1056. * So, for the original text storage, two carets should be displayed for
  1057. * location (1, t): one visually between 'b' and 'E' and one visually
  1058. * between 'C' and 'f'.
  1059. *
  1060. *
  1061. * When two carets are displayed for a TextHitInfo, one caret is the
  1062. * 'strong' caret and the other is the 'weak' caret. The strong caret
  1063. * indicates where an inserted character will be displayed when that
  1064. * character's direction is the same as the direction of the TextLayout.
  1065. * The weak caret shows where an character inserted character will be
  1066. * displayed when the character's direction is opposite that of the
  1067. * TextLayout.
  1068. *
  1069. *
  1070. * Clients should not be overly concerned with the details of correct
  1071. * caret display. TextLayout.getCaretShapes(TextHitInfo) will return an
  1072. * array of two paths representing where carets should be displayed.
  1073. * The first path in the array is the strong caret; the second element,
  1074. * if non-null, is the weak caret. If the second element is null,
  1075. * then there is no weak caret for the given TextHitInfo.
  1076. *
  1077. *
  1078. * Since text can be visually reordered, logically consecutive
  1079. * TextHitInfo's may not be visually consecutive. One implication of this
  1080. * is that a client cannot tell from inspecting a TextHitInfo whether the
  1081. * hit represents the first (or last) caret in the layout. Clients
  1082. * can call getVisualOtherHit(); if the visual companion is
  1083. * (-1, TRAILING) or (characterCount, LEADING), then the hit is at the
  1084. * first (last) caret position in the layout.
  1085. */
  1086. private float[] getCaretInfo(int caret,
  1087. Rectangle2D bounds,
  1088. float[] info) {
  1089. float top1X, top2X;
  1090. float bottom1X, bottom2X;
  1091. if (caret == 0 || caret == characterCount) {
  1092. float pos;
  1093. int logIndex;
  1094. if (caret == characterCount) {
  1095. logIndex = textLine.visualToLogical(characterCount-1);
  1096. pos = textLine.getCharLinePosition(logIndex)
  1097. + textLine.getCharAdvance(logIndex);
  1098. }
  1099. else {
  1100. logIndex = textLine.visualToLogical(caret);
  1101. pos = textLine.getCharLinePosition(logIndex);
  1102. }
  1103. float angle = textLine.getCharAngle(logIndex);
  1104. float shift = textLine.getCharShift(logIndex);
  1105. pos += angle * shift;
  1106. top1X = top2X = pos + angle*textLine.getCharAscent(logIndex);
  1107. bottom1X = bottom2X = pos - angle*textLine.getCharDescent(logIndex);
  1108. }
  1109. else {
  1110. {
  1111. int logIndex = textLine.visualToLogical(caret-1);
  1112. float angle1 = textLine.getCharAngle(logIndex);
  1113. float pos1 = textLine.getCharLinePosition(logIndex)
  1114. + textLine.getCharAdvance(logIndex);
  1115. if (angle1 != 0) {
  1116. pos1 += angle1 * textLine.getCharShift(logIndex);
  1117. top1X = pos1 + angle1*textLine.getCharAscent(logIndex);
  1118. bottom1X = pos1 - angle1*textLine.getCharDescent(logIndex);
  1119. }
  1120. else {
  1121. top1X = bottom1X = pos1;
  1122. }
  1123. }
  1124. {
  1125. int logIndex = textLine.visualToLogical(caret);
  1126. float angle2 = textLine.getCharAngle(logIndex);
  1127. float pos2 = textLine.getCharLinePosition(logIndex);
  1128. if (angle2 != 0) {
  1129. pos2 += angle2*textLine.getCharShift(logIndex);
  1130. top2X = pos2 + angle2*textLine.getCharAscent(logIndex);
  1131. bottom2X = pos2 - angle2*textLine.getCharDescent(logIndex);
  1132. }
  1133. else {
  1134. top2X = bottom2X = pos2;
  1135. }
  1136. }
  1137. }
  1138. float topX = (top1X + top2X) / 2;
  1139. float bottomX = (bottom1X + bottom2X) / 2;
  1140. if (info == null) {
  1141. info = new float[2];
  1142. }
  1143. if (isVerticalLine) {
  1144. info[1] = (float) ((topX - bottomX) / bounds.getWidth());
  1145. info[0] = (float) (topX + (info[1]*bounds.getX()));
  1146. }
  1147. else {
  1148. info[1] = (float) ((topX - bottomX) / bounds.getHeight());
  1149. info[0] = (float) (bottomX + (info[1]*bounds.getMaxY()));
  1150. }
  1151. return info;
  1152. }
  1153. /**
  1154. * Returns information about the caret corresponding to <code>hit</code>.
  1155. * The first element of the array is the intersection of the caret with
  1156. * the baseline. The second element of the array is the inverse slope
  1157. * (run/rise) of the caret.
  1158. * <p>
  1159. * This method is meant for informational use. To display carets, it
  1160. * is better to use <code>getCaretShapes</code>.
  1161. * @param hit a hit on a character in this <code>TextLayout</code>
  1162. * @param bounds the bounds to which the caret info is constructed
  1163. * @return a two-element array containing the position and slope of
  1164. * the caret.
  1165. * @see #getCaretShapes(int, Rectangle2D, TextLayout.CaretPolicy)
  1166. * @see Font#getItalicAngle
  1167. */
  1168. public float[] getCaretInfo(TextHitInfo hit, Rectangle2D bounds) {
  1169. ensureCache();
  1170. checkTextHit(hit);
  1171. return getCaretInfoTestInternal(hit, bounds);
  1172. }
  1173. // this version provides extra info in the float array
  1174. // the first two values are as above
  1175. // the next four values are the endpoints of the caret, as computed
  1176. // using the hit character's offset (baseline + ssoffset) and
  1177. // natural ascent and descent.
  1178. // these values are trimmed to the bounds where required to fit,
  1179. // but otherwise independent of it.
  1180. private float[] getCaretInfoTestInternal(TextHitInfo hit, Rectangle2D bounds) {
  1181. ensureCache();
  1182. checkTextHit(hit);
  1183. float[] info = new float[6];
  1184. // get old data first
  1185. getCaretInfo(hitToCaret(hit), bounds, info);
  1186. // then add our new data
  1187. double iangle, ixbase, p1x, p1y, p2x, p2y;
  1188. int charix = hit.getCharIndex();
  1189. boolean lead = hit.isLeadingEdge();
  1190. boolean ltr = textLine.isDirectionLTR();
  1191. boolean horiz = !isVertical();
  1192. if (charix == -1 || charix == characterCount) {
  1193. // !!! note: want non-shifted, baseline ascent and descent here!
  1194. // TextLine should return appropriate line metrics object for these values
  1195. TextLineMetrics m = textLine.getMetrics();
  1196. boolean low = ltr == (charix == -1);
  1197. iangle = 0;
  1198. if (horiz) {
  1199. p1x = p2x = low ? 0 : m.advance;
  1200. p1y = -m.ascent;
  1201. p2y = m.descent;
  1202. } else {
  1203. p1y = p2y = low ? 0 : m.advance;
  1204. p1x = m.descent;
  1205. p2x = m.ascent;
  1206. }
  1207. } else {
  1208. CoreMetrics thiscm = textLine.getCoreMetricsAt(charix);
  1209. iangle = thiscm.italicAngle;
  1210. ixbase = textLine.getCharLinePosition(charix, lead);
  1211. if (thiscm.baselineIndex < 0) {
  1212. // this is a graphic, no italics, use entire line height for caret
  1213. TextLineMetrics m = textLine.getMetrics();
  1214. if (horiz) {
  1215. p1x = p2x = ixbase;
  1216. if (thiscm.baselineIndex == GraphicAttribute.TOP_ALIGNMENT) {
  1217. p1y = -m.ascent;
  1218. p2y = p1y + thiscm.height;
  1219. } else {
  1220. p2y = m.descent;
  1221. p1y = p2y - thiscm.height;
  1222. }
  1223. } else {
  1224. p1y = p2y = ixbase;
  1225. p1x = m.descent;
  1226. p2x = m.ascent;
  1227. // !!! top/bottom adjustment not implemented for vertical
  1228. }
  1229. } else {
  1230. float bo = baselineOffsets[thiscm.baselineIndex];
  1231. if (horiz) {
  1232. ixbase += iangle * thiscm.ssOffset;
  1233. p1x = ixbase + iangle * thiscm.ascent;
  1234. p2x = ixbase - iangle * thiscm.descent;
  1235. p1y = bo - thiscm.ascent;
  1236. p2y = bo + thiscm.descent;
  1237. } else {
  1238. ixbase -= iangle * thiscm.ssOffset;
  1239. p1y = ixbase + iangle * thiscm.ascent;
  1240. p2y = ixbase - iangle * thiscm.descent;
  1241. p1x = bo + thiscm.ascent;
  1242. p2x = bo + thiscm.descent;
  1243. }
  1244. }
  1245. }
  1246. info[2] = (float)p1x;
  1247. info[3] = (float)p1y;
  1248. info[4] = (float)p2x;
  1249. info[5] = (float)p2y;
  1250. return info;
  1251. }
  1252. /**
  1253. * Returns information about the caret corresponding to <code>hit</code>.
  1254. * This method is a convenience overload of <code>getCaretInfo</code> and
  1255. * uses the natural bounds of this <code>TextLayout</code>.
  1256. * @param hit a hit on a character in this <code>TextLayout</code>
  1257. * @return the information about a caret corresponding to a hit.
  1258. */
  1259. public float[] getCaretInfo(TextHitInfo hit) {
  1260. return getCaretInfo(hit, getNaturalBounds());
  1261. }
  1262. /**
  1263. * Returns a caret index corresponding to <code>hit</code>.
  1264. * Carets are numbered from left to right (top to bottom) starting from
  1265. * zero. This always places carets next to the character hit, on the
  1266. * indicated side of the character.
  1267. * @param hit a hit on a character in this <code>TextLayout</code>
  1268. * @return a caret index corresponding to the specified hit.
  1269. */
  1270. private int hitToCaret(TextHitInfo hit) {
  1271. int hitIndex = hit.getCharIndex();
  1272. if (hitIndex < 0) {
  1273. return textLine.isDirectionLTR() ? 0 : characterCount;
  1274. } else if (hitIndex >= characterCount) {
  1275. return textLine.isDirectionLTR() ? characterCount : 0;
  1276. }
  1277. int visIndex = textLine.logicalToVisual(hitIndex);
  1278. if (hit.isLeadingEdge() != textLine.isCharLTR(hitIndex)) {
  1279. ++visIndex;
  1280. }
  1281. return visIndex;
  1282. }
  1283. /**
  1284. * Given a caret index, return a hit whose caret is at the index.
  1285. * The hit is NOT guaranteed to be strong!!!
  1286. *
  1287. * @param caret a caret index.
  1288. * @return a hit on this layout whose strong caret is at the requested
  1289. * index.
  1290. */
  1291. private TextHitInfo caretToHit(int caret) {
  1292. if (caret == 0 || caret == characterCount) {
  1293. if ((caret == characterCount) == textLine.isDirectionLTR()) {
  1294. return TextHitInfo.leading(characterCount);
  1295. }
  1296. else {
  1297. return TextHitInfo.trailing(-1);
  1298. }
  1299. }
  1300. else {
  1301. int charIndex = textLine.visualToLogical(caret);
  1302. boolean leading = textLine.isCharLTR(charIndex);
  1303. return leading? TextHitInfo.leading(charIndex)
  1304. : TextHitInfo.trailing(charIndex);
  1305. }
  1306. }
  1307. private boolean caretIsValid(int caret) {
  1308. if (caret == characterCount || caret == 0) {
  1309. return true;
  1310. }
  1311. int offset = textLine.visualToLogical(caret);
  1312. if (!textLine.isCharLTR(offset)) {
  1313. offset = textLine.visualToLogical(caret-1);
  1314. if (textLine.isCharLTR(offset)) {
  1315. return true;
  1316. }
  1317. }
  1318. // At this point, the leading edge of the character
  1319. // at offset is at the given caret.
  1320. return textLine.caretAtOffsetIsValid(offset);
  1321. }
  1322. /**
  1323. * Returns the hit for the next caret to the right (bottom); if there
  1324. * is no such hit, returns <code>null</code>.
  1325. * If the hit character index is out of bounds, an
  1326. * {@link IllegalArgumentException} is thrown.
  1327. * @param hit a hit on a character in this layout
  1328. * @return a hit whose caret appears at the next position to the
  1329. * right (bottom) of the caret of the provided hit or <code>null</code>.
  1330. */
  1331. public TextHitInfo getNextRightHit(TextHitInfo hit) {
  1332. ensureCache();
  1333. checkTextHit(hit);
  1334. int caret = hitToCaret(hit);
  1335. if (caret == characterCount) {
  1336. return null;
  1337. }
  1338. do {
  1339. ++caret;
  1340. } while (!caretIsValid(caret));
  1341. return caretToHit(caret);
  1342. }
  1343. /**
  1344. * Returns the hit for the next caret to the right (bottom); if no
  1345. * such hit, returns <code>null</code>. The hit is to the right of
  1346. * the strong caret at the specified offset, as determined by the
  1347. * specified policy.
  1348. * The returned hit is the stronger of the two possible
  1349. * hits, as determined by the specified policy.
  1350. * @param offset an insertion offset in this <code>TextLayout</code>.
  1351. * Cannot be less than 0 or greater than this <code>TextLayout</code>
  1352. * object's character count.
  1353. * @param policy the policy used to select the strong caret
  1354. * @return a hit whose caret appears at the next position to the
  1355. * right (bottom) of the caret of the provided hit, or <code>null</code>.
  1356. */
  1357. public TextHitInfo getNextRightHit(int offset, CaretPolicy policy) {
  1358. if (offset < 0 || offset > characterCount) {
  1359. throw new IllegalArgumentException("Offset out of bounds in TextLayout.getNextRightHit()");
  1360. }
  1361. if (policy == null) {
  1362. throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getNextRightHit()");
  1363. }
  1364. TextHitInfo hit1 = TextHitInfo.afterOffset(offset);
  1365. TextHitInfo hit2 = hit1.getOtherHit();
  1366. TextHitInfo nextHit = getNextRightHit(policy.getStrongCaret(hit1, hit2, this));
  1367. if (nextHit != null) {
  1368. TextHitInfo otherHit = getVisualOtherHit(nextHit);
  1369. return policy.getStrongCaret(otherHit, nextHit, this);
  1370. }
  1371. else {
  1372. return null;
  1373. }
  1374. }
  1375. /**
  1376. * Returns the hit for the next caret to the right (bottom); if no
  1377. * such hit, returns <code>null</code>. The hit is to the right of
  1378. * the strong caret at the specified offset, as determined by the
  1379. * default policy.
  1380. * The returned hit is the stronger of the two possible
  1381. * hits, as determined by the default policy.
  1382. * @param offset an insertion offset in this <code>TextLayout</code>.
  1383. * Cannot be less than 0 or greater than the <code>TextLayout</code>
  1384. * object's character count.
  1385. * @return a hit whose caret appears at the next position to the
  1386. * right (bottom) of the caret of the provided hit, or <code>null</code>.
  1387. */
  1388. public TextHitInfo getNextRightHit(int offset) {
  1389. return getNextRightHit(offset, DEFAULT_CARET_POLICY);
  1390. }
  1391. /**
  1392. * Returns the hit for the next caret to the left (top); if no such
  1393. * hit, returns <code>null</code>.
  1394. * If the hit character index is out of bounds, an
  1395. * <code>IllegalArgumentException</code> is thrown.
  1396. * @param hit a hit on a character in this <code>TextLayout</code>.
  1397. * @return a hit whose caret appears at the next position to the
  1398. * left (top) of the caret of the provided hit, or <code>null</code>.
  1399. */
  1400. public TextHitInfo getNextLeftHit(TextHitInfo hit) {
  1401. ensureCache();
  1402. checkTextHit(hit);
  1403. int caret = hitToCaret(hit);
  1404. if (caret == 0) {
  1405. return null;
  1406. }
  1407. do {
  1408. --caret;
  1409. } while(!caretIsValid(caret));
  1410. return caretToHit(caret);
  1411. }
  1412. /**
  1413. * Returns the hit for the next caret to the left (top); if no
  1414. * such hit, returns <code>null</code>. The hit is to the left of
  1415. * the strong caret at the specified offset, as determined by the
  1416. * specified policy.
  1417. * The returned hit is the stronger of the two possible
  1418. * hits, as determined by the specified policy.
  1419. * @param offset an insertion offset in this <code>TextLayout</code>.
  1420. * Cannot be less than 0 or greater than this <code>TextLayout</code>
  1421. * object's character count.
  1422. * @param policy the policy used to select the strong caret
  1423. * @return a hit whose caret appears at the next position to the
  1424. * left (top) of the caret of the provided hit, or <code>null</code>.
  1425. */
  1426. public TextHitInfo getNextLeftHit(int offset, CaretPolicy policy) {
  1427. if (policy == null) {
  1428. throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getNextLeftHit()");
  1429. }
  1430. if (offset < 0 || offset > characterCount) {
  1431. throw new IllegalArgumentException("Offset out of bounds in TextLayout.getNextLeftHit()");
  1432. }
  1433. TextHitInfo hit1 = TextHitInfo.afterOffset(offset);
  1434. TextHitInfo hit2 = hit1.getOtherHit();
  1435. TextHitInfo nextHit = getNextLeftHit(policy.getStrongCaret(hit1, hit2, this));
  1436. if (nextHit != null) {
  1437. TextHitInfo otherHit = getVisualOtherHit(nextHit);
  1438. return policy.getStrongCaret(otherHit, nextHit, this);
  1439. }
  1440. else {
  1441. return null;
  1442. }
  1443. }
  1444. /**
  1445. * Returns the hit for the next caret to the left (top); if no
  1446. * such hit, returns <code>null</code>. The hit is to the left of
  1447. * the strong caret at the specified offset, as determined by the
  1448. * default policy.
  1449. * The returned hit is the stronger of the two possible
  1450. * hits, as determined by the default policy.
  1451. * @param offset an insertion offset in this <code>TextLayout</code>.
  1452. * Cannot be less than 0 or greater than this <code>TextLayout</code>
  1453. * object's character count.
  1454. * @return a hit whose caret appears at the next position to the
  1455. * left (top) of the caret of the provided hit, or <code>null</code>.
  1456. */
  1457. public TextHitInfo getNextLeftHit(int offset) {
  1458. return getNextLeftHit(offset, DEFAULT_CARET_POLICY);
  1459. }
  1460. /**
  1461. * Returns the hit on the opposite side of the specified hit's caret.
  1462. * @param hit the specified hit
  1463. * @return a hit that is on the opposite side of the specified hit's
  1464. * caret.
  1465. */
  1466. public TextHitInfo getVisualOtherHit(TextHitInfo hit) {
  1467. ensureCache();
  1468. checkTextHit(hit);
  1469. int hitCharIndex = hit.getCharIndex();
  1470. int charIndex;
  1471. boolean leading;
  1472. if (hitCharIndex == -1 || hitCharIndex == characterCount) {
  1473. int visIndex;
  1474. if (textLine.isDirectionLTR() == (hitCharIndex == -1)) {
  1475. visIndex = 0;
  1476. }
  1477. else {
  1478. visIndex = characterCount-1;
  1479. }
  1480. charIndex = textLine.visualToLogical(visIndex);
  1481. if (textLine.isDirectionLTR() == (hitCharIndex == -1)) {
  1482. // at left end
  1483. leading = textLine.isCharLTR(charIndex);
  1484. }
  1485. else {
  1486. // at right end
  1487. leading = !textLine.isCharLTR(charIndex);
  1488. }
  1489. }
  1490. else {
  1491. int visIndex = textLine.logicalToVisual(hitCharIndex);
  1492. boolean movedToRight;
  1493. if (textLine.isCharLTR(hitCharIndex) == hit.isLeadingEdge()) {
  1494. --visIndex;
  1495. movedToRight = false;
  1496. }
  1497. else {
  1498. ++visIndex;
  1499. movedToRight = true;
  1500. }
  1501. if (visIndex > -1 && visIndex < characterCount) {
  1502. charIndex = textLine.visualToLogical(visIndex);
  1503. leading = movedToRight == textLine.isCharLTR(charIndex);
  1504. }
  1505. else {
  1506. charIndex =
  1507. (movedToRight == textLine.isDirectionLTR())? characterCount : -1;
  1508. leading = charIndex == characterCount;
  1509. }
  1510. }
  1511. return leading? TextHitInfo.leading(charIndex) :
  1512. TextHitInfo.trailing(charIndex);
  1513. }
  1514. private double[] getCaretPath(TextHitInfo hit, Rectangle2D bounds) {
  1515. float[] info = getCaretInfo(hit, bounds);
  1516. return new double[] { info[2], info[3], info[4], info[5] };
  1517. }
  1518. /**
  1519. * Return an array of four floats corresponding the endpoints of the caret
  1520. * x0, y0, x1, y1.
  1521. *
  1522. * This creates a line along the slope of the caret intersecting the
  1523. * baseline at the caret
  1524. * position, and extending from ascent above the baseline to descent below
  1525. * it.
  1526. */
  1527. private double[] getCaretPath(int caret, Rectangle2D bounds,
  1528. boolean clipToBounds) {
  1529. float[] info = getCaretInfo(caret, bounds, null);
  1530. double pos = info[0];
  1531. double slope = info[1];
  1532. double x0, y0, x1, y1;
  1533. double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy
  1534. double left = bounds.getX();
  1535. double right = left + bounds.getWidth();
  1536. double top = bounds.getY();
  1537. double bottom = top + bounds.getHeight();
  1538. boolean threePoints = false;
  1539. if (isVerticalLine) {
  1540. if (slope >= 0) {
  1541. x0 = left;
  1542. x1 = right;
  1543. }
  1544. else {
  1545. x1 = left;
  1546. x0 = right;
  1547. }
  1548. y0 = pos + x0 * slope;
  1549. y1 = pos + x1 * slope;
  1550. // y0 <= y1, always
  1551. if (clipToBounds) {
  1552. if (y0 < top) {
  1553. if (slope <= 0 || y1 <= top) {
  1554. y0 = y1 = top;
  1555. }
  1556. else {
  1557. threePoints = true;
  1558. y0 = top;
  1559. y2 = top;
  1560. x2 = x1 + (top-y1)/slope;
  1561. if (y1 > bottom) {
  1562. y1 = bottom;
  1563. }
  1564. }
  1565. }
  1566. else if (y1 > bottom) {
  1567. if (slope >= 0 || y0 >= bottom) {
  1568. y0 = y1 = bottom;
  1569. }
  1570. else {
  1571. threePoints = true;
  1572. y1 = bottom;
  1573. y2 = bottom;
  1574. x2 = x0 + (bottom-x1)/slope;
  1575. }
  1576. }
  1577. }
  1578. }
  1579. else {
  1580. if (slope >= 0) {
  1581. y0 = bottom;
  1582. y1 = top;
  1583. }
  1584. else {
  1585. y1 = bottom;
  1586. y0 = top;
  1587. }
  1588. x0 = pos - y0 * slope;
  1589. x1 = pos - y1 * slope;
  1590. // x0 <= x1, always
  1591. if (clipToBounds) {
  1592. if (x0 < left) {
  1593. if (slope <= 0 || x1 <= left) {
  1594. x0 = x1 = left;
  1595. }
  1596. else {
  1597. threePoints = true;
  1598. x0 = left;
  1599. x2 = left;
  1600. y2 = y1 - (left-x1)/slope;
  1601. if (x1 > right) {
  1602. x1 = right;
  1603. }
  1604. }
  1605. }
  1606. else if (x1 > right) {
  1607. if (slope >= 0 || x0 >= right) {
  1608. x0 = x1 = right;
  1609. }
  1610. else {
  1611. threePoints = true;
  1612. x1 = right;
  1613. x2 = right;
  1614. y2 = y0 - (right-x0)/slope;
  1615. }
  1616. }
  1617. }
  1618. }
  1619. return threePoints?
  1620. new double[] { x0, y0, x2, y2, x1, y1 } :
  1621. new double[] { x0, y0, x1, y1 };
  1622. }
  1623. private static GeneralPath pathToShape(double[] path, boolean close) {
  1624. GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length);
  1625. result.moveTo((float)path[0], (float)path[1]);
  1626. for (int i = 2; i < path.length; i += 2) {
  1627. result.lineTo((float)path[i], (float)path[i+1]);
  1628. }
  1629. if (close) {
  1630. result.closePath();
  1631. }
  1632. return result;
  1633. }
  1634. /**
  1635. * Returns a {@link Shape} representing the caret at the specified
  1636. * hit inside the specified bounds.
  1637. * @param hit the hit at which to generate the caret
  1638. * @param bounds the bounds of the <code>TextLayout</code> to use
  1639. * in generating the caret.
  1640. * @return a <code>Shape</code> representing the caret.
  1641. */
  1642. public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) {
  1643. ensureCache();
  1644. checkTextHit(hit);
  1645. if (bounds == null) {
  1646. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()");
  1647. }
  1648. // int hitCaret = hitToCaret(hit);
  1649. // GeneralPath hitShape =
  1650. // pathToShape(getCaretPath(hitCaret, bounds, false), false);
  1651. return pathToShape(getCaretPath(hit, bounds), false);
  1652. //return new Highlight(hitShape, true);
  1653. // return hitShape;
  1654. }
  1655. /**
  1656. * Returns a <code>Shape</code> representing the caret at the specified
  1657. * hit inside the natural bounds of this <code>TextLayout</code>.
  1658. * @param hit the hit at which to generate the caret
  1659. * @return a <code>Shape</code> representing the caret.
  1660. */
  1661. public Shape getCaretShape(TextHitInfo hit) {
  1662. return getCaretShape(hit, getNaturalBounds());
  1663. }
  1664. /**
  1665. * Return the "stronger" of the TextHitInfos. The TextHitInfos
  1666. * should be logical or visual counterparts. They are not
  1667. * checked for validity.
  1668. */
  1669. private final TextHitInfo getStrongHit(TextHitInfo hit1, TextHitInfo hit2) {
  1670. // right now we're using the following rule for strong hits:
  1671. // A hit on a character with a lower level
  1672. // is stronger than one on a character with a higher level.
  1673. // If this rule ties, the hit on the leading edge of a character wins.
  1674. // If THIS rule ties, hit1 wins. Both rules shouldn't tie, unless the
  1675. // infos aren't counterparts of some sort.
  1676. byte hit1Level = getCharacterLevel(hit1.getCharIndex());
  1677. byte hit2Level = getCharacterLevel(hit2.getCharIndex());
  1678. if (hit1Level == hit2Level) {
  1679. if (hit2.isLeadingEdge() && !hit1.isLeadingEdge()) {
  1680. return hit2;
  1681. }
  1682. else {
  1683. return hit1;
  1684. }
  1685. }
  1686. else {
  1687. return (hit1Level < hit2Level)? hit1 : hit2;
  1688. }
  1689. }
  1690. /**
  1691. * Returns the level of the character at <code>index</code>.
  1692. * Indices -1 and <code>characterCount</code> are assigned the base
  1693. * level of this <code>TextLayout</code>.
  1694. * @param index the index of the character from which to get the level
  1695. * @return the level of the character at the specified index.
  1696. */
  1697. public byte getCharacterLevel(int index) {
  1698. // hmm, allow indices at endpoints? For now, yes.
  1699. if (index < -1 || index > characterCount) {
  1700. throw new IllegalArgumentException("Index is out of range in getCharacterLevel.");
  1701. }
  1702. if (optInfo != null) {
  1703. return 0;
  1704. }
  1705. ensureCache();
  1706. if (index == -1 || index == characterCount) {
  1707. return (byte) (textLine.isDirectionLTR()? 0 : 1);
  1708. }
  1709. return textLine.getCharLevel(index);
  1710. }
  1711. /**
  1712. * Returns two paths corresponding to the strong and weak caret.
  1713. * @param offset an offset in this <code>TextLayout</code>
  1714. * @param bounds the bounds to which to extend the carets
  1715. * @param policy the specified <code>CaretPolicy</code>
  1716. * @return an array of two paths. Element zero is the strong
  1717. * caret. If there are two carets, element one is the weak caret,
  1718. * otherwise it is <code>null</code>.
  1719. */
  1720. public Shape[] getCaretShapes(int offset, Rectangle2D bounds, CaretPolicy policy) {
  1721. ensureCache();
  1722. if (offset < 0 || offset > characterCount) {
  1723. throw new IllegalArgumentException("Offset out of bounds in TextLayout.getCaretShapes()");
  1724. }
  1725. if (bounds == null) {
  1726. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaretShapes()");
  1727. }
  1728. if (policy == null) {
  1729. throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getCaretShapes()");
  1730. }
  1731. Shape[] result = new Shape[2];
  1732. TextHitInfo hit = TextHitInfo.afterOffset(offset);
  1733. int hitCaret = hitToCaret(hit);
  1734. // Shape hitShape =
  1735. // pathToShape(getCaretPath(hitCaret, bounds, false), false);
  1736. Shape hitShape = pathToShape(getCaretPath(hit, bounds), false);
  1737. TextHitInfo otherHit = hit.getOtherHit();
  1738. int otherCaret = hitToCaret(otherHit);
  1739. if (hitCaret == otherCaret) {
  1740. result[0] = hitShape;
  1741. }
  1742. else { // more than one caret
  1743. // Shape otherShape =
  1744. // pathToShape(getCaretPath(otherCaret, bounds, false), false);
  1745. Shape otherShape = pathToShape(getCaretPath(otherHit, bounds), false);
  1746. TextHitInfo strongHit = policy.getStrongCaret(hit, otherHit, this);
  1747. boolean hitIsStrong = strongHit.equals(hit);
  1748. if (hitIsStrong) {// then other is weak
  1749. result[0] = hitShape;
  1750. result[1] = otherShape;
  1751. }
  1752. else {
  1753. result[0] = otherShape;
  1754. result[1] = hitShape;
  1755. }
  1756. }
  1757. return result;
  1758. }
  1759. /**
  1760. * Returns two paths corresponding to the strong and weak caret.
  1761. * This method is a convenience overload of <code>getCaretShapes</code>
  1762. * that uses the default caret policy.
  1763. * @param offset an offset in this <code>TextLayout</code>
  1764. * @param bounds the bounds to which to extend the carets
  1765. * @return two paths corresponding to the strong and weak caret as
  1766. * defined by the <code>DEFAULT_CARET_POLICY</code>
  1767. */
  1768. public Shape[] getCaretShapes(int offset, Rectangle2D bounds) {
  1769. // {sfb} parameter checking is done in overloaded version
  1770. return getCaretShapes(offset, bounds, DEFAULT_CARET_POLICY);
  1771. }
  1772. /**
  1773. * Returns two paths corresponding to the strong and weak caret.
  1774. * This method is a convenience overload of <code>getCaretShapes</code>
  1775. * that uses the default caret policy and this <code>TextLayout</code>
  1776. * object's natural bounds.
  1777. * @param offset an offset in this <code>TextLayout</code>
  1778. * @return two paths corresponding to the strong and weak caret as
  1779. * defined by the <code>DEFAULT_CARET_POLICY</code>
  1780. */
  1781. public Shape[] getCaretShapes(int offset) {
  1782. // {sfb} parameter checking is done in overloaded version
  1783. return getCaretShapes(offset, getNaturalBounds(), DEFAULT_CARET_POLICY);
  1784. }
  1785. // A utility to return a path enclosing the given path
  1786. // Path0 must be left or top of path1
  1787. // {jbr} no assumptions about size of path0, path1 anymore.
  1788. private GeneralPath boundingShape(double[] path0, double[] path1) {
  1789. // Really, we want the path to be a convex hull around all of the
  1790. // points in path0 and path1. But we can get by with less than
  1791. // that. We do need to prevent the two segments which
  1792. // join path0 to path1 from crossing each other. So, if we
  1793. // traverse path0 from top to bottom, we'll traverse path1 from
  1794. // bottom to top (and vice versa).
  1795. GeneralPath result = pathToShape(path0, false);
  1796. boolean sameDirection;
  1797. if (isVerticalLine) {
  1798. sameDirection = (path0[1] > path0[path0.length-1]) ==
  1799. (path1[1] > path1[path1.length-1]);
  1800. }
  1801. else {
  1802. sameDirection = (path0[0] > path0[path0.length-2]) ==
  1803. (path1[0] > path1[path1.length-2]);
  1804. }
  1805. int start;
  1806. int limit;
  1807. int increment;
  1808. if (sameDirection) {
  1809. start = path1.length-2;
  1810. limit = -2;
  1811. increment = -2;
  1812. }
  1813. else {
  1814. start = 0;
  1815. limit = path1.length;
  1816. increment = 2;
  1817. }
  1818. for (int i = start; i != limit; i += increment) {
  1819. result.lineTo((float)path1[i], (float)path1[i+1]);
  1820. }
  1821. result.closePath();
  1822. return result;
  1823. }
  1824. // A utility to convert a pair of carets into a bounding path
  1825. // {jbr} Shape is never outside of bounds.
  1826. private GeneralPath caretBoundingShape(int caret0,
  1827. int caret1,
  1828. Rectangle2D bounds) {
  1829. if (caret0 > caret1) {
  1830. int temp = caret0;
  1831. caret0 = caret1;
  1832. caret1 = temp;
  1833. }
  1834. return boundingShape(getCaretPath(caret0, bounds, true),
  1835. getCaretPath(caret1, bounds, true));
  1836. }
  1837. /*
  1838. * A utility to return the path bounding the area to the left (top) of the
  1839. * layout.
  1840. * Shape is never outside of bounds.
  1841. */
  1842. private GeneralPath leftShape(Rectangle2D bounds) {
  1843. double[] path0;
  1844. if (isVerticalLine) {
  1845. path0 = new double[] { bounds.getX(), bounds.getY(),
  1846. bounds.getX() + bounds.getWidth(),
  1847. bounds.getY() };
  1848. } else {
  1849. path0 = new double[] { bounds.getX(),
  1850. bounds.getY() + bounds.getHeight(),
  1851. bounds.getX(), bounds.getY() };
  1852. }
  1853. double[] path1 = getCaretPath(0, bounds, true);
  1854. return boundingShape(path0, path1);
  1855. }
  1856. /*
  1857. * A utility to return the path bounding the area to the right (bottom) of
  1858. * the layout.
  1859. */
  1860. private GeneralPath rightShape(Rectangle2D bounds) {
  1861. double[] path1;
  1862. if (isVerticalLine) {
  1863. path1 = new double[] {
  1864. bounds.getX(),
  1865. bounds.getY() + bounds.getHeight(),
  1866. bounds.getX() + bounds.getWidth(),
  1867. bounds.getY() + bounds.getHeight()
  1868. };
  1869. } else {
  1870. path1 = new double[] {
  1871. bounds.getX() + bounds.getWidth(),
  1872. bounds.getY() + bounds.getHeight(),
  1873. bounds.getX() + bounds.getWidth(),
  1874. bounds.getY()
  1875. };
  1876. }
  1877. double[] path0 = getCaretPath(characterCount, bounds, true);
  1878. return boundingShape(path0, path1);
  1879. }
  1880. /**
  1881. * Returns the logical ranges of text corresponding to a visual selection.
  1882. * @param firstEndpoint an endpoint of the visual range
  1883. * @param secondEndpoint the other endpoint of the visual range.
  1884. * This endpoint can be less than <code>firstEndpoint</code>.
  1885. * @return an array of integers representing start/limit pairs for the
  1886. * selected ranges.
  1887. * @see #getVisualHighlightShape(TextHitInfo, TextHitInfo, Rectangle2D)
  1888. */
  1889. public int[] getLogicalRangesForVisualSelection(TextHitInfo firstEndpoint,
  1890. TextHitInfo secondEndpoint) {
  1891. ensureCache();
  1892. checkTextHit(firstEndpoint);
  1893. checkTextHit(secondEndpoint);
  1894. // !!! probably want to optimize for all LTR text
  1895. boolean[] included = new boolean[characterCount];
  1896. int startIndex = hitToCaret(firstEndpoint);
  1897. int limitIndex = hitToCaret(secondEndpoint);
  1898. if (startIndex > limitIndex) {
  1899. int t = startIndex;
  1900. startIndex = limitIndex;
  1901. limitIndex = t;
  1902. }
  1903. /*
  1904. * now we have the visual indexes of the glyphs at the start and limit
  1905. * of the selection range walk through runs marking characters that
  1906. * were included in the visual range there is probably a more efficient
  1907. * way to do this, but this ought to work, so hey
  1908. */
  1909. if (startIndex < limitIndex) {
  1910. int visIndex = startIndex;
  1911. while (visIndex < limitIndex) {
  1912. included[textLine.visualToLogical(visIndex)] = true;
  1913. ++visIndex;
  1914. }
  1915. }
  1916. /*
  1917. * count how many runs we have, ought to be one or two, but perhaps
  1918. * things are especially weird
  1919. */
  1920. int count = 0;
  1921. boolean inrun = false;
  1922. for (int i = 0; i < characterCount; i++) {
  1923. if (included[i] != inrun) {
  1924. inrun = !inrun;
  1925. if (inrun) {
  1926. count++;
  1927. }
  1928. }
  1929. }
  1930. int[] ranges = new int[count * 2];
  1931. count = 0;
  1932. inrun = false;
  1933. for (int i = 0; i < characterCount; i++) {
  1934. if (included[i] != inrun) {
  1935. ranges[count++] = i;
  1936. inrun = !inrun;
  1937. }
  1938. }
  1939. if (inrun) {
  1940. ranges[count++] = characterCount;
  1941. }
  1942. return ranges;
  1943. }
  1944. /**
  1945. * Returns a path enclosing the visual selection in the specified range,
  1946. * extended to <code>bounds</code>.
  1947. * <p>
  1948. * If the selection includes the leftmost (topmost) position, the selection
  1949. * is extended to the left (top) of <code>bounds</code>. If the
  1950. * selection includes the rightmost (bottommost) position, the selection
  1951. * is extended to the right (bottom) of the bounds. The height
  1952. * (width on vertical lines) of the selection is always extended to
  1953. * <code>bounds</code>.
  1954. * <p>
  1955. * Although the selection is always contiguous, the logically selected
  1956. * text can be discontiguous on lines with mixed-direction text. The
  1957. * logical ranges of text selected can be retrieved using
  1958. * <code>getLogicalRangesForVisualSelection</code>. For example,
  1959. * consider the text 'ABCdef' where capital letters indicate
  1960. * right-to-left text, rendered on a right-to-left line, with a visual
  1961. * selection from 0L (the leading edge of 'A') to 3T (the trailing edge
  1962. * of 'd'). The text appears as follows, with bold underlined areas
  1963. * representing the selection:
  1964. * <br><pre>
  1965. * d<u><b>efCBA </b></u>
  1966. * </pre>
  1967. * The logical selection ranges are 0-3, 4-6 (ABC, ef) because the
  1968. * visually contiguous text is logically discontiguous. Also note that
  1969. * since the rightmost position on the layout (to the right of 'A') is
  1970. * selected, the selection is extended to the right of the bounds.
  1971. * @param firstEndpoint one end of the visual selection
  1972. * @param secondEndpoint the other end of the visual selection
  1973. * @param bounds the bounding rectangle to which to extend the selection
  1974. * @return a <code>Shape</code> enclosing the selection.
  1975. * @see #getLogicalRangesForVisualSelection(TextHitInfo, TextHitInfo)
  1976. * @see #getLogicalHighlightShape(int, int, Rectangle2D)
  1977. */
  1978. public Shape getVisualHighlightShape(TextHitInfo firstEndpoint,
  1979. TextHitInfo secondEndpoint,
  1980. Rectangle2D bounds)
  1981. {
  1982. ensureCache();
  1983. checkTextHit(firstEndpoint);
  1984. checkTextHit(secondEndpoint);
  1985. if(bounds == null) {
  1986. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getVisualHighlightShape()");
  1987. }
  1988. GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
  1989. int firstCaret = hitToCaret(firstEndpoint);
  1990. int secondCaret = hitToCaret(secondEndpoint);
  1991. result.append(caretBoundingShape(firstCaret, secondCaret, bounds),
  1992. false);
  1993. if (firstCaret == 0 || secondCaret == 0) {
  1994. result.append(leftShape(bounds), false);
  1995. }
  1996. if (firstCaret == characterCount || secondCaret == characterCount) {
  1997. result.append(rightShape(bounds), false);
  1998. }
  1999. //return new Highlight(result, false);
  2000. return result;
  2001. }
  2002. /**
  2003. * Returns a <code>Shape</code> enclosing the visual selection in the
  2004. * specified range, extended to the bounds. This method is a
  2005. * convenience overload of <code>getVisualHighlightShape</code> that
  2006. * uses the natural bounds of this <code>TextLayout</code>.
  2007. * @param firstEndpoint one end of the visual selection
  2008. * @param secondEndpoint the other end of the visual selection
  2009. * @return a <code>Shape</code> enclosing the selection.
  2010. */
  2011. public Shape getVisualHighlightShape(TextHitInfo firstEndpoint,
  2012. TextHitInfo secondEndpoint) {
  2013. return getVisualHighlightShape(firstEndpoint, secondEndpoint, getNaturalBounds());
  2014. }
  2015. /**
  2016. * Returns a <code>Shape</code> enclosing the logical selection in the
  2017. * specified range, extended to the specified <code>bounds</code>.
  2018. * <p>
  2019. * If the selection range includes the first logical character, the
  2020. * selection is extended to the portion of <code>bounds</code> before
  2021. * the start of this <code>TextLayout</code>. If the range includes
  2022. * the last logical character, the selection is extended to the portion
  2023. * of <code>bounds</code> after the end of this <code>TextLayout</code>.
  2024. * The height (width on vertical lines) of the selection is always
  2025. * extended to <code>bounds</code>.
  2026. * <p>
  2027. * The selection can be discontiguous on lines with mixed-direction text.
  2028. * Only those characters in the logical range between start and limit
  2029. * appear selected. For example, consider the text 'ABCdef' where capital
  2030. * letters indicate right-to-left text, rendered on a right-to-left line,
  2031. * with a logical selection from 0 to 4 ('ABCd'). The text appears as
  2032. * follows, with bold standing in for the selection, and underlining for
  2033. * the extension:
  2034. * <br><pre>
  2035. * <u><b>d</b></u>ef<u><b>CBA </b></u>
  2036. * </pre>
  2037. * The selection is discontiguous because the selected characters are
  2038. * visually discontiguous. Also note that since the range includes the
  2039. * first logical character (A), the selection is extended to the portion
  2040. * of the <code>bounds</code> before the start of the layout, which in
  2041. * this case (a right-to-left line) is the right portion of the
  2042. * <code>bounds</code>.
  2043. * @param firstEndpoint an endpoint in the range of characters to select
  2044. * @param secondEndpoint the other endpoint of the range of characters
  2045. * to select. Can be less than <code>firstEndpoint</code>. The range
  2046. * includes the character at min(firstEndpoint, secondEndpoint), but
  2047. * excludes max(firstEndpoint, secondEndpoint).
  2048. * @param bounds the bounding rectangle to which to extend the selection
  2049. * @return an area enclosing the selection.
  2050. * @see #getVisualHighlightShape(TextHitInfo, TextHitInfo, Rectangle2D)
  2051. */
  2052. public Shape getLogicalHighlightShape(int firstEndpoint,
  2053. int secondEndpoint,
  2054. Rectangle2D bounds) {
  2055. if (bounds == null) {
  2056. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getLogicalHighlightShape()");
  2057. }
  2058. ensureCache();
  2059. if (firstEndpoint > secondEndpoint) {
  2060. int t = firstEndpoint;
  2061. firstEndpoint = secondEndpoint;
  2062. secondEndpoint = t;
  2063. }
  2064. if(firstEndpoint < 0 || secondEndpoint > characterCount) {
  2065. throw new IllegalArgumentException("Range is invalid in TextLayout.getLogicalHighlightShape()");
  2066. }
  2067. GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
  2068. int[] carets = new int[10]; // would this ever not handle all cases?
  2069. int count = 0;
  2070. if (firstEndpoint < secondEndpoint) {
  2071. int logIndex = firstEndpoint;
  2072. do {
  2073. carets[count++] = hitToCaret(TextHitInfo.leading(logIndex));
  2074. boolean ltr = textLine.isCharLTR(logIndex);
  2075. do {
  2076. logIndex++;
  2077. } while (logIndex < secondEndpoint && textLine.isCharLTR(logIndex) == ltr);
  2078. int hitCh = logIndex;
  2079. carets[count++] = hitToCaret(TextHitInfo.trailing(hitCh - 1));
  2080. if (count == carets.length) {
  2081. int[] temp = new int[carets.length + 10];
  2082. System.arraycopy(carets, 0, temp, 0, count);
  2083. carets = temp;
  2084. }
  2085. } while (logIndex < secondEndpoint);
  2086. }
  2087. else {
  2088. count = 2;
  2089. carets[0] = carets[1] = hitToCaret(TextHitInfo.leading(firstEndpoint));
  2090. }
  2091. // now create paths for pairs of carets
  2092. for (int i = 0; i < count; i += 2) {
  2093. result.append(caretBoundingShape(carets[i], carets[i+1], bounds),
  2094. false);
  2095. }
  2096. if (firstEndpoint != secondEndpoint) {
  2097. if ((textLine.isDirectionLTR() && firstEndpoint == 0) || (!textLine.isDirectionLTR() &&
  2098. secondEndpoint == characterCount)) {
  2099. result.append(leftShape(bounds), false);
  2100. }
  2101. if ((textLine.isDirectionLTR() && secondEndpoint == characterCount) ||
  2102. (!textLine.isDirectionLTR() && firstEndpoint == 0)) {
  2103. result.append(rightShape(bounds), false);
  2104. }
  2105. }
  2106. return result;
  2107. }
  2108. /**
  2109. * Returns a <code>Shape</code> enclosing the logical selection in the
  2110. * specified range, extended to the natural bounds of this
  2111. * <code>TextLayout</code>. This method is a convenience overload of
  2112. * <code>getLogicalHighlightShape</code> that uses the natural bounds of
  2113. * this <code>TextLayout</code>.
  2114. * @param firstEndpoint an endpoint in the range of characters to select
  2115. * @param secondEndpoint the other endpoint of the range of characters
  2116. * to select. Can be less than <code>firstEndpoint</code>. The range
  2117. * includes the character at min(firstEndpoint, secondEndpoint), but
  2118. * excludes max(firstEndpoint, secondEndpoint).
  2119. * @return a <code>Shape</code> enclosing the selection.
  2120. */
  2121. public Shape getLogicalHighlightShape(int firstEndpoint, int secondEndpoint) {
  2122. return getLogicalHighlightShape(firstEndpoint, secondEndpoint, getNaturalBounds());
  2123. }
  2124. /**
  2125. * Returns the black box bounds of the characters in the specified range.
  2126. * The black box bounds is an area consisting of the union of the bounding
  2127. * boxes of all the glyphs corresponding to the characters between start
  2128. * and limit. This path may be disjoint.
  2129. * @param firstEndpoint one end of the character range
  2130. * @param secondEndpoint the other end of the character range. Can be
  2131. * less than <code>firstEndpoint</code>.
  2132. * @return a <code>path</code> enclosing the black box bounds.
  2133. */
  2134. public Shape getBlackBoxBounds(int firstEndpoint, int secondEndpoint) {
  2135. ensureCache();
  2136. if (firstEndpoint > secondEndpoint) {
  2137. int t = firstEndpoint;
  2138. firstEndpoint = secondEndpoint;
  2139. secondEndpoint = t;
  2140. }
  2141. if (firstEndpoint < 0 || secondEndpoint > characterCount) {
  2142. throw new IllegalArgumentException("Invalid range passed to TextLayout.getBlackBoxBounds()");
  2143. }
  2144. /*
  2145. * return an area that consists of the bounding boxes of all the
  2146. * characters from firstEndpoint to limit
  2147. */
  2148. GeneralPath result = new GeneralPath(GeneralPath.WIND_NON_ZERO);
  2149. if (firstEndpoint < characterCount) {
  2150. for (int logIndex = firstEndpoint;
  2151. logIndex < secondEndpoint;
  2152. logIndex++) {
  2153. Rectangle2D r = textLine.getCharBounds(logIndex);
  2154. if (!r.isEmpty()) {
  2155. result.append(r, false);
  2156. }
  2157. }
  2158. }
  2159. if (dx != 0 || dy != 0) {
  2160. AffineTransform translate = new AffineTransform();
  2161. translate.setToTranslation(dx, dy);
  2162. result = (GeneralPath) result.createTransformedShape(translate);
  2163. }
  2164. //return new Highlight(result, false);
  2165. return result;
  2166. }
  2167. /**
  2168. * Returns the distance from the point (x, y) to the caret along
  2169. * the line direction defined in <code>caretInfo</code>. Distance is
  2170. * negative if the point is to the left of the caret on a horizontal
  2171. * line, or above the caret on a vertical line.
  2172. * Utility for use by hitTestChar.
  2173. */
  2174. private float caretToPointDistance(float[] caretInfo, float x, float y) {
  2175. // distanceOffBaseline is negative if you're 'above' baseline
  2176. float lineDistance = isVerticalLine? y : x;
  2177. float distanceOffBaseline = isVerticalLine? -x : y;
  2178. return lineDistance - caretInfo[0] +
  2179. (distanceOffBaseline*caretInfo[1]);
  2180. }
  2181. /**
  2182. * Returns a <code>TextHitInfo</code> corresponding to the
  2183. * specified point.
  2184. * Coordinates outside the bounds of the <code>TextLayout</code>
  2185. * map to hits on the leading edge of the first logical character,
  2186. * or the trailing edge of the last logical character, as appropriate,
  2187. * regardless of the position of that character in the line. Only the
  2188. * direction along the baseline is used to make this evaluation.
  2189. * @param x the x offset from the origin of this
  2190. * <code>TextLayout</code>
  2191. * @param y the y offset from the origin of this
  2192. * <code>TextLayout</code>
  2193. * @param bounds the bounds of the <code>TextLayout</code>
  2194. * @return a hit describing the character and edge (leading or trailing)
  2195. * under the specified point.
  2196. */
  2197. public TextHitInfo hitTestChar(float x, float y, Rectangle2D bounds) {
  2198. // check boundary conditions
  2199. if (isVertical()) {
  2200. if (y < bounds.getMinY()) {
  2201. return TextHitInfo.leading(0);
  2202. } else if (y >= bounds.getMaxY()) {
  2203. return TextHitInfo.trailing(characterCount-1);
  2204. }
  2205. } else {
  2206. if (x < bounds.getMinX()) {
  2207. return isLeftToRight() ? TextHitInfo.leading(0) : TextHitInfo.trailing(characterCount-1);
  2208. } else if (x >= bounds.getMaxX()) {
  2209. return isLeftToRight() ? TextHitInfo.trailing(characterCount-1) : TextHitInfo.leading(0);
  2210. }
  2211. }
  2212. // revised hit test
  2213. // the original seems too complex and fails miserably with italic offsets
  2214. // the natural tendency is to move towards the character you want to hit
  2215. // so we'll just measure distance to the center of each character's visual
  2216. // bounds, pick the closest one, then see which side of the character's
  2217. // center line (italic) the point is on.
  2218. // this tends to make it easier to hit narrow characters, which can be a
  2219. // bit odd if you're visually over an adjacent wide character. this makes
  2220. // a difference with bidi, so perhaps i need to revisit this yet again.
  2221. double distance = Double.MAX_VALUE;
  2222. int index = 0;
  2223. int trail = -1;
  2224. CoreMetrics lcm = null;
  2225. float icx = 0, icy = 0, ia = 0, cy = 0, dya = 0, ydsq = 0;
  2226. for (int i = 0; i < characterCount; ++i) {
  2227. if (!textLine.caretAtOffsetIsValid(i)) {
  2228. continue;
  2229. }
  2230. if (trail == -1) {
  2231. trail = i;
  2232. }
  2233. CoreMetrics cm = textLine.getCoreMetricsAt(i);
  2234. if (cm != lcm) {
  2235. lcm = cm;
  2236. // just work around baseline mess for now
  2237. if (cm.baselineIndex == GraphicAttribute.TOP_ALIGNMENT) {
  2238. cy = -(textLine.getMetrics().ascent - cm.ascent) + cm.ssOffset;
  2239. } else if (cm.baselineIndex == GraphicAttribute.BOTTOM_ALIGNMENT) {
  2240. cy = textLine.getMetrics().descent - cm.descent + cm.ssOffset;
  2241. } else {
  2242. cy = cm.effectiveBaselineOffset(baselineOffsets) + cm.ssOffset;
  2243. }
  2244. float dy = (cm.descent - cm.ascent) / 2 - cy;
  2245. dya = dy * cm.italicAngle;
  2246. cy += dy;
  2247. ydsq = (cy - y)*(cy - y);
  2248. }
  2249. float cx = textLine.getCharXPosition(i);
  2250. float ca = textLine.getCharAdvance(i);
  2251. float dx = ca / 2;
  2252. cx += dx - dya;
  2253. // proximity in x (along baseline) is two times as important as proximity in y
  2254. double nd = Math.sqrt(4*(cx - x)*(cx - x) + ydsq);
  2255. if (nd < distance) {
  2256. distance = nd;
  2257. index = i;
  2258. trail = -1;
  2259. icx = cx; icy = cy; ia = cm.italicAngle;
  2260. }
  2261. }
  2262. boolean left = x < icx - (y - icy) * ia;
  2263. boolean leading = textLine.isCharLTR(index) == left;
  2264. if (trail == -1) {
  2265. trail = characterCount;
  2266. }
  2267. TextHitInfo result = leading ? TextHitInfo.leading(index) :
  2268. TextHitInfo.trailing(trail-1);
  2269. return result;
  2270. }
  2271. /**
  2272. * Returns a <code>TextHitInfo</code> corresponding to the
  2273. * specified point. This method is a convenience overload of
  2274. * <code>hitTestChar</code> that uses the natural bounds of this
  2275. * <code>TextLayout</code>.
  2276. * @param x the x offset from the origin of this <code>TextLayout</code>
  2277. * @param y the y offset from the origin of this
  2278. * <code>TextLayout</code>
  2279. * @return a hit describing the character and edge (leading or trailing)
  2280. * under the specified point.
  2281. */
  2282. public TextHitInfo hitTestChar(float x, float y) {
  2283. return hitTestChar(x, y, getNaturalBounds());
  2284. }
  2285. /**
  2286. * Returns the hash code of this <code>TextLayout</code>.
  2287. * @return the hash code of this <code>TextLayout</code>.
  2288. */
  2289. public int hashCode() {
  2290. if (hashCodeCache == 0) {
  2291. ensureCache();
  2292. hashCodeCache = textLine.hashCode();
  2293. }
  2294. return hashCodeCache;
  2295. }
  2296. /**
  2297. * Returns <code>true</code> if the specified <code>Object</code> is a
  2298. * <code>TextLayout</code> object and if the specified <code>Object</code>
  2299. * equals this <code>TextLayout</code>.
  2300. * @param obj an <code>Object</code> to test for equality
  2301. * @return <code>true</code> if the specified <code>Object</code>
  2302. * equals this <code>TextLayout</code> <code>false</code>
  2303. * otherwise.
  2304. */
  2305. public boolean equals(Object obj) {
  2306. return (obj instanceof TextLayout) && equals((TextLayout)obj);
  2307. }
  2308. /**
  2309. * Returns <code>true</code> if the two layouts are equal.
  2310. * Two layouts are equal if they contain equal glyphvectors in the same order.
  2311. * @param rhs the <code>TextLayout</code> to compare to this
  2312. * <code>TextLayout</code>
  2313. * @return <code>true</code> if the specified <code>TextLayout</code>
  2314. * equals this <code>TextLayout</code>.
  2315. *
  2316. */
  2317. public boolean equals(TextLayout rhs) {
  2318. if (rhs == null) {
  2319. return false;
  2320. }
  2321. if (rhs == this) {
  2322. return true;
  2323. }
  2324. ensureCache();
  2325. return textLine.equals(rhs.textLine);
  2326. }
  2327. /**
  2328. * Returns debugging information for this <code>TextLayout</code>.
  2329. * @return the <code>textLine</code> of this <code>TextLayout</code>
  2330. * as a <code>String</code>.
  2331. */
  2332. public String toString() {
  2333. ensureCache();
  2334. return textLine.toString();
  2335. }
  2336. /**
  2337. * Renders this <code>TextLayout</code> at the specified location in
  2338. * the specified {@link java.awt.Graphics2D Graphics2D} context.
  2339. * The origin of the layout is placed at x, y. Rendering may touch
  2340. * any point within <code>getBounds()</code> of this position. This
  2341. * leaves the <code>g2</code> unchanged.
  2342. * @param g2 the <code>Graphics2D</code> context into which to render
  2343. * the layout
  2344. * @param x, y the coordinates of the origin of this
  2345. * <code>TextLayout</code>
  2346. * @see #getBounds()
  2347. */
  2348. public void draw(Graphics2D g2, float x, float y) {
  2349. if (g2 == null) {
  2350. throw new IllegalArgumentException("Null Graphics2D passed to TextLayout.draw()");
  2351. }
  2352. if (optInfo != null) {
  2353. if (optInfo.draw(g2, x, y)) { // might fail to draw because of frc change
  2354. return;
  2355. }
  2356. // replace with TextLine and fall through
  2357. initTextLine();
  2358. }
  2359. textLine.draw(g2, x - dx, y - dy);
  2360. }
  2361. /**
  2362. * Package-only method for testing ONLY. Please don't abuse.
  2363. */
  2364. TextLine getTextLineForTesting() {
  2365. return textLine;
  2366. }
  2367. /**
  2368. *
  2369. * Return the index of the first character with a different baseline from the
  2370. * character at start, or limit if all characters between start and limit have
  2371. * the same baseline.
  2372. */
  2373. private static int sameBaselineUpTo(Font font, char[] text,
  2374. int start, int limit) {
  2375. // current implementation doesn't support multiple baselines
  2376. return limit;
  2377. /*
  2378. byte bl = font.getBaselineFor(text[start++]);
  2379. while (start < limit && font.getBaselineFor(text[start]) == bl) {
  2380. ++start;
  2381. }
  2382. return start;
  2383. */
  2384. }
  2385. static byte getBaselineFromGraphic(GraphicAttribute graphic) {
  2386. byte alignment = (byte) graphic.getAlignment();
  2387. if (alignment == GraphicAttribute.BOTTOM_ALIGNMENT ||
  2388. alignment == GraphicAttribute.TOP_ALIGNMENT) {
  2389. return (byte)GraphicAttribute.ROMAN_BASELINE;
  2390. }
  2391. else {
  2392. return alignment;
  2393. }
  2394. }
  2395. /**
  2396. * Returns a <code>Shape</code> representing the outline of this
  2397. * <code>TextLayout</code>.
  2398. * @param tx an optional {@link AffineTransform} to apply to the
  2399. * outline of this <code>TextLayout</code>.
  2400. * @return a <code>Shape</code> that is the outline of this
  2401. * <code>TextLayout</code>.
  2402. */
  2403. public Shape getOutline(AffineTransform tx) {
  2404. ensureCache();
  2405. return textLine.getOutline(tx);
  2406. }
  2407. }