1. /*
  2. * @(#)TextLayout.java 1.74 00/02/02
  3. *
  4. * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. /*
  11. * (C) Copyright Taligent, Inc. 1996 - 1997, All Rights Reserved
  12. * (C) Copyright IBM Corp. 1996 - 1998, All Rights Reserved
  13. *
  14. * The original version of this source code and documentation is
  15. * copyrighted and owned by Taligent, Inc., a wholly-owned subsidiary
  16. * of IBM. These materials are provided under terms of a License
  17. * Agreement between Taligent and Sun. This technology is protected
  18. * by multiple US and International patents.
  19. *
  20. * This notice and attribution to Taligent may not be removed.
  21. * Taligent is a registered trademark of Taligent, Inc.
  22. *
  23. */
  24. package java.awt.font;
  25. import java.awt.Color;
  26. import java.awt.Font;
  27. import java.awt.Graphics2D;
  28. import java.awt.Shape;
  29. import java.awt.geom.AffineTransform;
  30. import java.awt.geom.GeneralPath;
  31. import java.awt.geom.Point2D;
  32. import java.awt.geom.Rectangle2D;
  33. import java.text.AttributedString;
  34. import java.text.AttributedCharacterIterator;
  35. import java.util.Map;
  36. import java.util.Hashtable;
  37. import sun.awt.font.NativeFontWrapper;
  38. import sun.java2d.SunGraphicsEnvironment;
  39. /**
  40. *
  41. * <code>TextLayout</code> is an immutable graphical representation of styled
  42. * character data.
  43. * <p>
  44. * It provides the following capabilities:
  45. * <ul>
  46. * <li>implicit bidirectional analysis and reordering,
  47. * <li>cursor positioning and movement, including split cursors for
  48. * mixed directional text,
  49. * <li>highlighting, including both logical and visual highlighting
  50. * for mixed directional text,
  51. * <li>multiple baselines (roman, hanging, and centered),
  52. * <li>hit testing,
  53. * <li>justification,
  54. * <li>default font substitution,
  55. * <li>metric information such as ascent, descent, and advance, and
  56. * <li>rendering
  57. * </ul>
  58. * <p>
  59. * A <code>TextLayout</code> object can be rendered using
  60. * its <code>draw</code> method.
  61. * <p>
  62. * <code>TextLayout</code> can be constructed either directly or through
  63. * the use of a {@link LineBreakMeasurer}. When constructed directly, the
  64. * source text represents a single paragraph. <code>LineBreakMeasurer</code>
  65. * allows styled text to be broken into lines that fit within a particular
  66. * width. See the <code>LineBreakMeasurer</code> documentation for more
  67. * information.
  68. * <p>
  69. * <code>TextLayout</code> construction logically proceeds as follows:
  70. * <ul>
  71. * <li>paragraph attributes are extracted and examined,
  72. * <li>text is analyzed for bidirectional reordering, and reordering
  73. * information is computed if needed,
  74. * <li>text is segmented into style runs
  75. * <li>fonts are chosen for style runs, first by using a font if the
  76. * attribute {@link TextAttribute#FONT} is present, otherwise by computing
  77. * a default font using the attributes that have been defined
  78. * <li>if text is on multiple baselines, the runs or subruns are further
  79. * broken into subruns sharing a common baseline,
  80. * <li>glyphvectors are generated for each run using the chosen font,
  81. * <li>final bidirectional reordering is performed on the glyphvectors
  82. * </ul>
  83. * <p>
  84. * All graphical information returned from a <code>TextLayout</code>
  85. * object's methods is relative to the origin of the
  86. * <code>TextLayout</code>, which is the intersection of the
  87. * <code>TextLayout</code> object's baseline with its left edge. Also,
  88. * coordinates passed into a <code>TextLayout</code> object's methods
  89. * are assumed to be relative to the <code>TextLayout</code> object's
  90. * origin. Clients usually need to translate between a
  91. * <code>TextLayout</code> object's coordinate system and the coordinate
  92. * system in another object (such as a
  93. * {@link java.awt.Graphics Graphics} object).
  94. * <p>
  95. * <code>TextLayout</code> objects are constructed from styled text,
  96. * but they do not retain a reference to their source text. Thus,
  97. * changes in the text previously used to generate a <code>TextLayout</code>
  98. * do not affect the <code>TextLayout</code>.
  99. * <p>
  100. * Three methods on a <code>TextLayout</code> object
  101. * (<code>getNextRightHit</code>, <code>getNextLeftHit</code>, and
  102. * <code>hitTestChar</code>) return instances of {@link TextHitInfo}.
  103. * The offsets contained in these <code>TextHitInfo</code> objects
  104. * are relative to the start of the <code>TextLayout</code>, <b>not</b>
  105. * to the text used to create the <code>TextLayout</code>. Similarly,
  106. * <code>TextLayout</code> methods that accept <code>TextHitInfo</code>
  107. * instances as parameters expect the <code>TextHitInfo</code> object's
  108. * offsets to be relative to the <code>TextLayout</code>, not to any
  109. * underlying text storage model.
  110. * <p>
  111. * <strong>Examples</strong>:<p>
  112. * Constructing and drawing a <code>TextLayout</code> and its bounding
  113. * rectangle:
  114. * <blockquote><pre>
  115. * Graphics2D g = ...;
  116. * Point2D loc = ...;
  117. * Font font = Font.getFont("Helvetica-bold-italic");
  118. * FontRenderContext frc = g.getFontRenderContext();
  119. * TextLayout layout = new TextLayout("This is a string", font, frc);
  120. * layout.draw(g, loc.getX(), loc.getY());
  121. *
  122. * Rectangle2D bounds = layout.getBounds();
  123. * bounds.setRect(bounds.getX()+loc.getX(),
  124. * bounds.getY()+loc.getY(),
  125. * bounds.getWidth(),
  126. * bounds.getHeight())
  127. * g.draw(bounds);
  128. * </pre>
  129. * </blockquote>
  130. * <p>
  131. * Hit-testing a <code>TextLayout</code> (determining which character is at
  132. * a particular graphical location):
  133. * <blockquote><pre>
  134. * Point2D click = ...;
  135. * TextHitInfo hit = layout.hitTestChar(
  136. * (float) (click.getX() - loc.getX()),
  137. * (float) (click.getY() - loc.getY()));
  138. * </pre>
  139. * </blockquote>
  140. * <p>
  141. * Responding to a right-arrow key press:
  142. * <blockquoute><pre>
  143. * int insertionIndex = ...;
  144. * TextHitInfo next = layout.getNextRightHit(insertionIndex);
  145. * if (next != null) {
  146. * // translate graphics to origin of layout on screen
  147. * g.translate(loc.getX(), loc.getY());
  148. * Shape[] carets = layout.getCaretShapes(next.getInsertionIndex());
  149. * g.draw(carets[0]);
  150. * if (carets[1] != null) {
  151. * g.draw(carets[1]);
  152. * }
  153. * }
  154. * </pre></blockquote>
  155. * <p>
  156. * Drawing a selection range corresponding to a substring in the source text.
  157. * The selected area may not be visually contiguous:
  158. * <blockquoute><pre>
  159. * // selStart, selLimit should be relative to the layout,
  160. * // not to the source text
  161. *
  162. * int selStart = ..., selLimit = ...;
  163. * Color selectionColor = ...;
  164. * Shape selection = layout.getLogicalHighlightShape(selStart, selLimit);
  165. * // selection may consist of disjoint areas
  166. * // graphics is assumed to be tranlated to origin of layout
  167. * g.setColor(selectionColor);
  168. * g.fill(selection);
  169. * </pre></blockquote>
  170. * <p>
  171. * Drawing a visually contiguous selection range. The selection range may
  172. * correspond to more than one substring in the source text. The ranges of
  173. * the corresponding source text substrings can be obtained with
  174. * <code>getLogicalRangesForVisualSelection()</code>:
  175. * <blockquoute><pre>
  176. * TextHitInfo selStart = ..., selLimit = ...;
  177. * Shape selection = layout.getVisualHighlightShape(selStart, selLimit);
  178. * g.setColor(selectionColor);
  179. * g.fill(selection);
  180. * int[] ranges = getLogicalRangesForVisualSelection(selStart, selLimit);
  181. * // ranges[0], ranges[1] is the first selection range,
  182. * // ranges[2], ranges[3] is the second selection range, etc.
  183. * </pre></blockquote>
  184. * <p>
  185. * @see LineBreakMeasurer
  186. * @see TextAttribute
  187. * @see TextHitInfo
  188. */
  189. public final class TextLayout implements Cloneable {
  190. private int characterCount;
  191. private boolean isVerticalLine = false;
  192. private byte baseline;
  193. private float[] baselineOffsets; // why have these ?
  194. private TextLine textLine;
  195. // cached values computed from GlyphSets and set info:
  196. // all are recomputed from scratch in buildCache()
  197. private TextLine.TextLineMetrics lineMetrics = null;
  198. private float visibleAdvance;
  199. private int hashCodeCache;
  200. /*
  201. * TextLayouts are supposedly immutable. If you mutate a TextLayout under
  202. * the covers (like the justification code does) you'll need to set this
  203. * back to false. Could be replaced with textLine != null <--> cacheIsValid.
  204. */
  205. private boolean cacheIsValid = false;
  206. // This value is obtained from an attribute, and constrained to the
  207. // interval [0,1]. If 0, the layout cannot be justified.
  208. private float justifyRatio;
  209. // If a layout is produced by justification, then that layout
  210. // cannot be justified. To enforce this constraint the
  211. // justifyRatio of the justified layout is set to this value.
  212. private static final float ALREADY_JUSTIFIED = -53.9f;
  213. // dx and dy specify the distance between the TextLayout's origin
  214. // and the origin of the leftmost GlyphSet (TextLayoutComponent,
  215. // actually). They were used for hanging punctuation support,
  216. // which is no longer implemented. Currently they are both always 0,
  217. // and TextLayout is not guaranteed to work with non-zero dx, dy
  218. // values right now. They were left in as an aide and reminder to
  219. // anyone who implements hanging punctuation or other similar stuff.
  220. // They are static now so they don't take up space in TextLayout
  221. // instances.
  222. private static float dx;
  223. private static float dy;
  224. /*
  225. * Natural bounds is used internally. It is built on demand in
  226. * getNaturalBounds.
  227. */
  228. private Rectangle2D naturalBounds = null;
  229. /*
  230. * boundsRect encloses all of the bits this TextLayout can draw. It
  231. * is build on demand in getBounds.
  232. */
  233. private Rectangle2D boundsRect = null;
  234. /*
  235. * flag to supress/allow carets inside of ligatures when hit testing or
  236. * arrow-keying
  237. */
  238. private boolean caretsInLigaturesAreAllowed = false;
  239. /**
  240. * Defines a policy for determining the strong caret location.
  241. * This class contains one method, <code>getStrongCaret</code>, which
  242. * is used to specify the policy that determines the strong caret in
  243. * dual-caret text. The strong caret is used to move the caret to the
  244. * left or right. Instances of this class can be passed to
  245. * <code>getCaretShapes</code>, <code>getNextLeftHit</code> and
  246. * <code>getNextRightHit</code> to customize strong caret
  247. * selection.
  248. * <p>
  249. * To specify alternate caret policies, subclass <code>CaretPolicy</code>
  250. * and override <code>getStrongCaret</code>. <code>getStrongCaret</code>
  251. * should inspect the two <code>TextHitInfo</code> arguments and choose
  252. * one of them as the strong caret.
  253. * <p>
  254. * Most clients do not need to use this class.
  255. */
  256. public static class CaretPolicy {
  257. /**
  258. * Constructs a <code>CaretPolicy</code>.
  259. */
  260. public CaretPolicy() {
  261. }
  262. /**
  263. * Chooses one of the specified <code>TextHitInfo</code> instances as
  264. * a strong caret in the specified <code>TextLayout</code>.
  265. * @param hit1 a valid hit in <code>layout</code>
  266. * @param hit2 a valid hit in <code>layout</code>
  267. * @param layout the <code>TextLayout</code> in which
  268. * <code>hit1</code> and <code>hit2</code> are used
  269. * @return <code>hit1</code> or <code>hit2</code>
  270. * (or an equivalent <code>TextHitInfo</code>), indicating the
  271. * strong caret.
  272. */
  273. public TextHitInfo getStrongCaret(TextHitInfo hit1,
  274. TextHitInfo hit2,
  275. TextLayout layout) {
  276. // default implmentation just calls private method on layout
  277. return layout.getStrongHit(hit1, hit2);
  278. }
  279. }
  280. /**
  281. * This <code>CaretPolicy</code> is used when a policy is not specified
  282. * by the client. With this policy, a hit on a character whose direction
  283. * is the same as the line direction is stronger than a hit on a
  284. * counterdirectional character. If the characters' directions are
  285. * the same, a hit on the leading edge of a character is stronger
  286. * than a hit on the trailing edge of a character.
  287. */
  288. public static final CaretPolicy DEFAULT_CARET_POLICY = new CaretPolicy();
  289. /**
  290. * Constructs a <code>TextLayout</code> from a <code>String</code>
  291. * and a {@link Font}. All the text is styled using the specified
  292. * <code>Font</code>.
  293. * <p>
  294. * The <code>String</code> must specify a single paragraph of text,
  295. * because an entire paragraph is required for the bidirectional
  296. * algorithm.
  297. * @param str the text to display
  298. * @param font a <code>Font</code> used to style the text
  299. * @param frc contains information about a graphics device which is needed
  300. * to measure the text correctly.
  301. * Text measurements can vary slightly depending on the
  302. * device resolution, and attributes such as antialiasing. This
  303. * parameter does not specify a translation between the
  304. * <code>TextLayout</code> and user space.
  305. */
  306. public TextLayout(String string, Font font, FontRenderContext frc) {
  307. if (font == null) {
  308. throw new IllegalArgumentException("Null font passed to TextLayout constructor.");
  309. }
  310. if (string == null) {
  311. throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
  312. }
  313. if (string.length() == 0) {
  314. throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
  315. }
  316. char[] text = string.toCharArray();
  317. if (sameBaselineUpTo(font, text, 0, text.length) == text.length) {
  318. fastInit(text, 0, text.length, font, null, frc);
  319. } else {
  320. AttributedString as = new AttributedString(string);
  321. as.addAttribute(TextAttribute.FONT, font);
  322. standardInit(as.getIterator(), text, frc);
  323. }
  324. }
  325. /**
  326. * Constructs a <code>TextLayout</code> from a <code>String</code>
  327. * and an attribute set.
  328. * <p>
  329. * All the text is styled using the provided attributes.
  330. * <p>
  331. * <code>string</code> must specify a single paragraph of text because an
  332. * entire paragraph is required for the bidirectional algorithm.
  333. * @param str the text to display
  334. * @param attributes the attributes used to style the text
  335. * @param frc contains information about a graphics device which is needed
  336. * to measure the text correctly.
  337. * Text measurements can vary slightly depending on the
  338. * device resolution, and attributes such as antialiasing. This
  339. * parameter does not specify a translation between the
  340. * <code>TextLayout</code> and user space.
  341. */
  342. public TextLayout(String string, Map attributes, FontRenderContext frc) {
  343. if (string == null) {
  344. throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
  345. }
  346. if (attributes == null) {
  347. throw new IllegalArgumentException("Null map passed to TextLayout constructor.");
  348. }
  349. if (string.length() == 0) {
  350. throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
  351. }
  352. char[] text = string.toCharArray();
  353. Font font = singleFont(text, 0, text.length, attributes);
  354. if (font != null) {
  355. fastInit(text, 0, text.length, font, attributes, frc);
  356. } else {
  357. AttributedString as = new AttributedString(string, attributes);
  358. standardInit(as.getIterator(), text, frc);
  359. }
  360. }
  361. /*
  362. * Determines a font for the attributes, and if a single font can render
  363. * all the text on one baseline, return it, otherwise null. If the
  364. * attributes specify a font, assume it can display all the text without
  365. * checking.
  366. * If the AttributeSet contains an embedded graphic, return null.
  367. */
  368. private static Font singleFont(char[] text,
  369. int start,
  370. int limit,
  371. Map attributes) {
  372. if (attributes.get(TextAttribute.CHAR_REPLACEMENT) != null) {
  373. return null;
  374. }
  375. Font font = (Font)attributes.get(TextAttribute.FONT);
  376. if (font == null) {
  377. font = Font.getFont(attributes); // uses static cache in Font;
  378. if (font.canDisplayUpTo(text, start, limit) != limit) {
  379. return null;
  380. }
  381. }
  382. if (sameBaselineUpTo(font, text, start, limit) != limit) {
  383. return null;
  384. }
  385. return font;
  386. }
  387. /**
  388. * Constructs a <code>TextLayout</code> from an iterator over styled text.
  389. * <p>
  390. * The iterator must specify a single paragraph of text because an
  391. * entire paragraph is required for the bidirectional
  392. * algorithm.
  393. * @param text the styled text to display
  394. * @param frc contains information about a graphics device which is needed
  395. * to measure the text correctly.
  396. * Text measurements can vary slightly depending on the
  397. * device resolution, and attributes such as antialiasing. This
  398. * parameter does not specify a translation between the
  399. * <code>TextLayout</code> and user space.
  400. */
  401. public TextLayout(AttributedCharacterIterator text, FontRenderContext frc) {
  402. if (text == null) {
  403. throw new IllegalArgumentException("Null iterator passed to TextLayout constructor.");
  404. }
  405. int start = text.getBeginIndex();
  406. int limit = text.getEndIndex();
  407. if (start == limit) {
  408. throw new IllegalArgumentException("Zero length iterator passed to TextLayout constructor.");
  409. }
  410. int len = limit - start;
  411. text.first();
  412. char[] chars = new char[len];
  413. int n = 0;
  414. for (char c = text.first(); c != text.DONE; c = text.next()) {
  415. chars[n++] = c;
  416. }
  417. text.first();
  418. if (text.getRunLimit() == limit) {
  419. text.first();
  420. Map attributes = text.getAttributes();
  421. Font font = singleFont(chars, 0, len, attributes);
  422. if (font != null) {
  423. fastInit(chars, 0, len, font, attributes, frc);
  424. return;
  425. }
  426. }
  427. standardInit(text, chars, frc);
  428. }
  429. /**
  430. * Creates a <code>TextLayout</code> from a {@link TextLine} and
  431. * some paragraph data. This method is used by {@link TextMeasurer}.
  432. * @param textLine the line measurement attributes to apply to the
  433. * the resulting <code>TextLayout</code>
  434. * @param baseline the baseline of the text
  435. * @param baselineOffsets the baseline offsets for this
  436. * <code>TextLayout</code>. This should already be normalized to
  437. * <code>baseline</code>
  438. * @param justifyRatio <code>0</code> if the <code>TextLayout</code>
  439. * cannot be justified; <code>1</code> otherwise.
  440. */
  441. TextLayout(TextLine textLine,
  442. byte baseline,
  443. float[] baselineOffsets,
  444. float justifyRatio) {
  445. this.characterCount = textLine.characterCount();
  446. this.baseline = baseline;
  447. this.baselineOffsets = baselineOffsets;
  448. this.textLine = textLine;
  449. this.justifyRatio = justifyRatio;
  450. }
  451. /**
  452. * Initialize the paragraph-specific data.
  453. */
  454. private void paragraphInit(byte aBaseline, LineMetrics lm, Map paragraphAttrs) {
  455. // Object vf = paragraphAttrs.get(TextAttribute.ORIENTATION);
  456. // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
  457. isVerticalLine = false;
  458. baseline = aBaseline;
  459. baselineOffsets = lm.getBaselineOffsets();
  460. // normalize to current baseline
  461. if (baselineOffsets[baseline] != 0) {
  462. float base = baselineOffsets[baseline];
  463. float[] temp = new float[baselineOffsets.length];
  464. for (int i = 0; i < temp.length; i++)
  465. temp[i] = baselineOffsets[i] - base;
  466. baselineOffsets = temp;
  467. }
  468. /*
  469. * if justification is defined, use it (forcing to valid range)
  470. * otherwise set to 1.0
  471. */
  472. Float justifyLF = (Float) paragraphAttrs.get(TextAttribute.JUSTIFICATION);
  473. if (justifyLF == null) {
  474. justifyRatio = 1;
  475. } else {
  476. justifyRatio = justifyLF.floatValue();
  477. if (justifyRatio < 0) {
  478. justifyRatio = 0;
  479. } else if (justifyRatio > 1) {
  480. justifyRatio = 1;
  481. }
  482. }
  483. }
  484. /*
  485. * the fast init generates a single glyph set. This requires:
  486. * all one style
  487. * all renderable by one font (ie no embedded graphics)
  488. * all on one baseline
  489. */
  490. private void fastInit(char[] text, int start, int limit, Font font, Map attrs, FontRenderContext frc) {
  491. // Object vf = attrs.get(TextAttribute.ORIENTATION);
  492. // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
  493. isVerticalLine = false;
  494. LineMetrics lm = font.getLineMetrics(text, start, start+1, frc);
  495. byte glyphBaseline = (byte) lm.getBaselineIndex();
  496. if (attrs == null) {
  497. baseline = glyphBaseline;
  498. baselineOffsets = lm.getBaselineOffsets();
  499. justifyRatio = 1.0f;
  500. } else {
  501. paragraphInit(glyphBaseline, lm, attrs);
  502. }
  503. characterCount = limit-start;
  504. textLine = TextLine.fastCreateTextLine(frc, text, start, limit, font, lm, attrs);
  505. }
  506. /*
  507. * the standard init generates multiple glyph sets based on style,
  508. * renderable, and baseline runs.
  509. * @param chars the text in the iterator, extracted into a char array
  510. */
  511. private void standardInit(AttributedCharacterIterator text, char[] chars, FontRenderContext frc) {
  512. characterCount = text.getEndIndex() - text.getBeginIndex();
  513. // set paragraph attributes
  514. {
  515. // If there's an embedded graphic at the start of the
  516. // paragraph, look for the first non-graphic character
  517. // and use it and its font to initialize the paragraph.
  518. // If not, use the first graphic to initialize.
  519. char firstChar = text.first();
  520. Map paragraphAttrs = text.getAttributes();
  521. Map fontAttrs = paragraphAttrs;
  522. GraphicAttribute firstGraphic = (GraphicAttribute)
  523. paragraphAttrs.get(TextAttribute.CHAR_REPLACEMENT);
  524. boolean useFirstGraphic = false;
  525. if (firstGraphic != null) {
  526. useFirstGraphic = true;
  527. for (firstChar = text.setIndex(text.getRunLimit());
  528. firstChar != text.DONE;
  529. firstChar = text.setIndex(text.getRunLimit())) {
  530. fontAttrs = text.getAttributes();
  531. if (fontAttrs.get(TextAttribute.CHAR_REPLACEMENT) == null) {
  532. useFirstGraphic = false;
  533. break;
  534. }
  535. }
  536. if (useFirstGraphic) {
  537. firstChar = text.first();
  538. }
  539. }
  540. if (useFirstGraphic) {
  541. // hmmm what to do here? Just try to supply reasonable
  542. // values I guess.
  543. byte defaultBaseline = getBaselineFromGraphic(firstGraphic);
  544. Font dummyFont = new Font(new Hashtable(5, (float)0.9));
  545. LineMetrics lm = dummyFont.getLineMetrics(chars, 0, 1, frc);
  546. float[] defaultOffsets = lm.getBaselineOffsets();
  547. paragraphInit(defaultBaseline, lm, paragraphAttrs);
  548. }
  549. else {
  550. Font defaultFont = (Font)fontAttrs.get(TextAttribute.FONT);
  551. if (defaultFont == null) {
  552. defaultFont = SunGraphicsEnvironment.getBestFontFor(
  553. text, text.getIndex(), text.getEndIndex());
  554. }
  555. int charsStart = text.getIndex() - text.getBeginIndex();
  556. LineMetrics lm = defaultFont.getLineMetrics(chars, charsStart, charsStart+1, frc);
  557. paragraphInit(defaultFont.getBaselineFor(firstChar), lm, paragraphAttrs);
  558. }
  559. }
  560. textLine = TextLine.standardCreateTextLine(frc, text, chars, baselineOffsets);
  561. }
  562. /*
  563. * A utility to rebuild the ascent/descent/leading/advance cache.
  564. * You'll need to call this if you clone and mutate (like justification,
  565. * editing methods do)
  566. */
  567. private void ensureCache() {
  568. if (!cacheIsValid) {
  569. buildCache();
  570. }
  571. }
  572. private void buildCache() {
  573. lineMetrics = textLine.getMetrics();
  574. // compute visibleAdvance
  575. if (textLine.isDirectionLTR()) {
  576. int lastNonSpace = characterCount-1;
  577. while (lastNonSpace != -1) {
  578. int logIndex = textLine.visualToLogical(lastNonSpace);
  579. if (!textLine.isCharSpace(logIndex)) {
  580. break;
  581. }
  582. else {
  583. --lastNonSpace;
  584. }
  585. }
  586. if (lastNonSpace == characterCount-1) {
  587. visibleAdvance = lineMetrics.advance;
  588. }
  589. else if (lastNonSpace == -1) {
  590. visibleAdvance = 0;
  591. }
  592. else {
  593. int logIndex = textLine.visualToLogical(lastNonSpace);
  594. visibleAdvance = textLine.getCharLinePosition(logIndex)
  595. + textLine.getCharAdvance(logIndex);
  596. }
  597. }
  598. else {
  599. int leftmostNonSpace = 0;
  600. while (leftmostNonSpace != characterCount) {
  601. int logIndex = textLine.visualToLogical(leftmostNonSpace);
  602. if (!textLine.isCharSpace(logIndex)) {
  603. break;
  604. }
  605. else {
  606. ++leftmostNonSpace;
  607. }
  608. }
  609. if (leftmostNonSpace == characterCount) {
  610. visibleAdvance = 0;
  611. }
  612. else if (leftmostNonSpace == 0) {
  613. visibleAdvance = lineMetrics.advance;
  614. }
  615. else {
  616. int logIndex = textLine.visualToLogical(leftmostNonSpace);
  617. float pos = textLine.getCharLinePosition(logIndex);
  618. visibleAdvance = lineMetrics.advance - pos;
  619. }
  620. }
  621. // naturalBounds, boundsRect will be generated on demand
  622. naturalBounds = null;
  623. boundsRect = null;
  624. // hashCode will be regenerated on demand
  625. hashCodeCache = 0;
  626. cacheIsValid = true;
  627. }
  628. private Rectangle2D getNaturalBounds() {
  629. ensureCache();
  630. if (naturalBounds == null) {
  631. int leftmostCharIndex = textLine.visualToLogical(0);
  632. float angle = textLine.getCharAngle(leftmostCharIndex);
  633. float leftOrTop = isVerticalLine? -dy : -dx;
  634. if (angle < 0) {
  635. leftOrTop += angle*textLine.getCharAscent(leftmostCharIndex);
  636. }
  637. else if (angle > 0) {
  638. leftOrTop -= angle*textLine.getCharDescent(leftmostCharIndex);
  639. }
  640. int rightmostCharIndex = textLine.visualToLogical(characterCount-1);
  641. angle = textLine.getCharAngle(rightmostCharIndex);
  642. float rightOrBottom = lineMetrics.advance;
  643. if (angle < 0) {
  644. rightOrBottom -=
  645. angle*textLine.getCharDescent(rightmostCharIndex);
  646. }
  647. else if (angle > 0) {
  648. rightOrBottom +=
  649. angle*textLine.getCharAscent(rightmostCharIndex);
  650. }
  651. float lineDim = rightOrBottom - leftOrTop;
  652. if (isVerticalLine) {
  653. naturalBounds = new Rectangle2D.Float(
  654. -lineMetrics.descent, leftOrTop,
  655. lineMetrics.ascent + lineMetrics.descent, lineDim);
  656. }
  657. else {
  658. naturalBounds = new Rectangle2D.Float(
  659. leftOrTop, -lineMetrics.ascent,
  660. lineDim, lineMetrics.ascent + lineMetrics.descent);
  661. }
  662. }
  663. return naturalBounds;
  664. }
  665. /**
  666. * Creates a copy of this <code>TextLayout</code>.
  667. */
  668. protected Object clone() {
  669. /*
  670. * !!! I think this is safe. Once created, nothing mutates the
  671. * glyphvectors or arrays. But we need to make sure.
  672. * {jbr} actually, that's not quite true. The justification code
  673. * mutates after cloning. It doesn't actually change the glyphvectors
  674. * (that's impossible) but it replaces them with justified sets. This
  675. * is a problem for GlyphIterator creation, since new GlyphIterators
  676. * are created by cloning a prototype. If the prototype has outdated
  677. * glyphvectors, so will the new ones. A partial solution is to set the
  678. * prototypical GlyphIterator to null when the glyphvectors change. If
  679. * you forget this one time, you're hosed.
  680. */
  681. try {
  682. return super.clone();
  683. }
  684. catch (CloneNotSupportedException e) {
  685. throw new InternalError();
  686. }
  687. }
  688. /*
  689. * Utility to throw an expection if an invalid TextHitInfo is passed
  690. * as a parameter. Avoids code duplication.
  691. */
  692. private void checkTextHit(TextHitInfo hit) {
  693. if (hit == null) {
  694. throw new IllegalArgumentException("TextHitInfo is null.");
  695. }
  696. if (hit.getInsertionIndex() < 0 ||
  697. hit.getInsertionIndex() > characterCount) {
  698. throw new IllegalArgumentException("TextHitInfo is out of range");
  699. }
  700. }
  701. /**
  702. * Creates a copy of this <code>TextLayout</code> justified to the
  703. * specified width.
  704. * <p>
  705. * If this <code>TextLayout</code> has already been justified, an
  706. * exception is thrown. If this <code>TextLayout</code> object's
  707. * justification ratio is zero, a <code>TextLayout</code> identical
  708. * to this <code>TextLayout</code> is returned.
  709. * @param justificationWidth the width to use when justifying the line.
  710. * For best results, it should not be too different from the current
  711. * advance of the line.
  712. * @return a <code>TextLayout</code> justified to the specified width.
  713. * @exception Error if this layout has already been justified, an Error is
  714. * thrown.
  715. */
  716. public TextLayout getJustifiedLayout(float justificationWidth) {
  717. if (justificationWidth <= 0) {
  718. throw new IllegalArgumentException("justificationWidth <= 0 passed to TextLayout.getJustifiedLayout()");
  719. }
  720. if (justifyRatio == ALREADY_JUSTIFIED) {
  721. throw new Error("Can't justify again.");
  722. }
  723. // default justification range to exclude trailing logical whitespace
  724. int limit = characterCount;
  725. while (limit > 0 && textLine.isCharWhitespace(limit-1)) {
  726. --limit;
  727. }
  728. TextLine newLine = textLine.getJustifiedLine(justificationWidth, justifyRatio, 0, limit);
  729. if (newLine != null) {
  730. return new TextLayout(newLine, baseline, baselineOffsets, ALREADY_JUSTIFIED);
  731. }
  732. return this;
  733. }
  734. /**
  735. * Justify this layout. Overridden by subclassers to control justification
  736. * (if there were subclassers, that is...)
  737. *
  738. * The layout will only justify if the paragraph attributes (from the
  739. * source text, possibly defaulted by the layout attributes) indicate a
  740. * non-zero justification ratio. The text will be justified to the
  741. * indicated width. The current implementation also adjusts hanging
  742. * punctuation and trailing whitespace to overhang the justification width.
  743. * Once justified, the layout may not be rejustified.
  744. * <p>
  745. * Some code may rely on immutablity of layouts. Subclassers should not
  746. * call this directly, but instead should call getJustifiedLayout, which
  747. * will call this method on a clone of this layout, preserving
  748. * the original.
  749. *
  750. * @param justificationWidth the width to use when justifying the line.
  751. * For best results, it should not be too different from the current
  752. * advance of the line.
  753. * @see #getJustifiedLayout(float)
  754. */
  755. protected void handleJustify(float justificationWidth) {
  756. // never called
  757. }
  758. /**
  759. * Returns the baseline for this <code>TextLayout</code>.
  760. * The baseline is one of the values defined in <code>Font</code>,
  761. * which are roman, centered and hanging. Ascent and descent are
  762. * relative to this baseline. The <code>baselineOffsets</code>
  763. * are also relative to this baseline.
  764. * @return the baseline of this <code>TextLayout</code>.
  765. * @see #getBaselineOffsets()
  766. * @see Font
  767. */
  768. public byte getBaseline() {
  769. return baseline;
  770. }
  771. /**
  772. * Returns the offsets array for the baselines used for this
  773. * <code>TextLayout</code>.
  774. * <p>
  775. * The array is indexed by one of the values defined in
  776. * <code>Font</code>, which are roman, centered and hanging. The
  777. * values are relative to this <code>TextLayout</code> object's
  778. * baseline, so that <code>getBaselineOffsets[getBaseline()] == 0</code>.
  779. * Offsets are added to the position of the <code>TextLayout</code>
  780. * object's baseline to get the position for the new baseline.
  781. * @return the offsets array containing the baselines used for this
  782. * <code>TextLayout</code>.
  783. * @see #getBaseline()
  784. * @see Font
  785. */
  786. public float[] getBaselineOffsets() {
  787. float[] offsets = new float[baselineOffsets.length];
  788. System.arraycopy(baselineOffsets, 0, offsets, 0, offsets.length);
  789. return offsets;
  790. }
  791. /**
  792. * Returns the advance of this <code>TextLayout</code>.
  793. * The advance is the distance from the origin to the advance of the
  794. * rightmost (bottommost) character measuring in the line direction.
  795. * @return the advance of this <code>TextLayout</code>.
  796. */
  797. public float getAdvance() {
  798. ensureCache();
  799. return lineMetrics.advance;
  800. }
  801. /**
  802. * Returns the advance of this <code>TextLayout</code>, minus trailing
  803. * whitespace.
  804. * @return the advance of this <code>TextLayout</code> without the
  805. * trailing whitespace.
  806. * @see #getAdvance()
  807. */
  808. public float getVisibleAdvance() {
  809. ensureCache();
  810. return visibleAdvance;
  811. }
  812. /**
  813. * Returns the ascent of this <code>TextLayout</code>.
  814. * The ascent is the distance from the top (right) of the
  815. * <code>TextLayout</code> to the baseline. It is always either
  816. * positive or zero. The ascent is sufficient to
  817. * accomodate superscripted text and is the maximum of the sum of the
  818. * ascent, offset, and baseline of each glyph.
  819. * @return the ascent of this <code>TextLayout</code>.
  820. */
  821. public float getAscent() {
  822. ensureCache();
  823. return lineMetrics.ascent;
  824. }
  825. /**
  826. * Returns the descent of this <code>TextLayout</code>.
  827. * The descent is the distance from the baseline to the bottom (left) of
  828. * the <code>TextLayout</code>. It is always either positive or zero.
  829. * The descent is sufficient to accomodate subscripted text and is the
  830. * maximum of the sum of the descent, offset, and baseline of each glyph.
  831. * @return the descent of this <code>TextLayout</code>.
  832. */
  833. public float getDescent() {
  834. ensureCache();
  835. return lineMetrics.descent;
  836. }
  837. /**
  838. * Returns the leading of the <code>TextLayout</code>.
  839. * The leading is the suggested interline spacing for this
  840. * <code>TextLayout</code>.
  841. * <p>
  842. * The leading is computed from the leading, descent, and baseline
  843. * of all glyphvectors in the <code>TextLayout</code>. The algorithm
  844. * is roughly as follows:
  845. * <blockquote><pre>
  846. * maxD = 0;
  847. * maxDL = 0;
  848. * for (GlyphVector g in all glyphvectors) {
  849. * maxD = max(maxD, g.getDescent() + offsets[g.getBaseline()]);
  850. * maxDL = max(maxDL, g.getDescent() + g.getLeading() +
  851. * offsets[g.getBaseline()]);
  852. * }
  853. * return maxDL - maxD;
  854. * </pre></blockquote>
  855. * @return the leading of this <code>TextLayout</code>.
  856. */
  857. public float getLeading() {
  858. ensureCache();
  859. return lineMetrics.leading;
  860. }
  861. /**
  862. * Returns the bounds of this <code>TextLayout</code>.
  863. * The bounds contains all of the pixels the <code>TextLayout</code>
  864. * can draw. It might not coincide exactly with the ascent, descent,
  865. * origin or advance of the <code>TextLayout</code>.
  866. * @return a {@link Rectangle2D} that is the bounds of this
  867. * <code>TextLayout</code>.
  868. */
  869. public Rectangle2D getBounds() {
  870. ensureCache();
  871. if (boundsRect == null) {
  872. Rectangle2D lineBounds = textLine.getBounds();
  873. if (dx != 0 || dy != 0) {
  874. lineBounds.setRect(lineBounds.getX() - dx,
  875. lineBounds.getY() - dy,
  876. lineBounds.getWidth(),
  877. lineBounds.getHeight());
  878. }
  879. boundsRect = lineBounds;
  880. }
  881. Rectangle2D bounds = new Rectangle2D.Float();
  882. bounds.setRect(boundsRect);
  883. return bounds;
  884. }
  885. /**
  886. * Returns <code>true</code> if this <code>TextLayout</code> has
  887. * a left-to-right base direction or <code>false</code> if it has
  888. * a right-to-left base direction. The <code>TextLayout</code>
  889. * has a base direction of either left-to-right (LTR) or
  890. * right-to-left (RTL). The base direction is independent of the
  891. * actual direction of text on the line, which may be either LTR,
  892. * RTL, or mixed. Left-to-right layouts by default should position
  893. * flush left. If the layout is on a tabbed line, the
  894. * tabs run left to right, so that logically successive layouts position
  895. * left to right. The opposite is true for RTL layouts. By default they
  896. * should position flush left, and tabs run right-to-left.
  897. * @return <code>true</code> if the base direction of this
  898. * <code>TextLayout</code> is left-to-right; <code>false</code>
  899. * otherwise.
  900. */
  901. public boolean isLeftToRight() {
  902. return textLine.isDirectionLTR();
  903. }
  904. /**
  905. * Returns <code>true</code> if this <code>TextLayout</code> is vertical.
  906. * @return <code>true</code> if this <code>TextLayout</code> is vertical;
  907. * <code>false</code> otherwise.
  908. */
  909. public boolean isVertical() {
  910. return isVerticalLine;
  911. }
  912. /**
  913. * Returns the number of characters represented by this
  914. * <code>TextLayout</code>.
  915. * @return the number of characters in this <code>TextLayout</code>.
  916. */
  917. public int getCharacterCount() {
  918. return characterCount;
  919. }
  920. /*
  921. * carets and hit testing
  922. *
  923. * Positions on a text line are represented by instances of TextHitInfo.
  924. * Any TextHitInfo with characterOffset between 0 and characterCount-1,
  925. * inclusive, represents a valid position on the line. Additionally,
  926. * [-1, trailing] and [characterCount, leading] are valid positions, and
  927. * represent positions at the logical start and end of the line,
  928. * respectively.
  929. *
  930. * The characterOffsets in TextHitInfo's used and returned by TextLayout
  931. * are relative to the beginning of the text layout, not necessarily to
  932. * the beginning of the text storage the client is using.
  933. *
  934. *
  935. * Every valid TextHitInfo has either one or two carets associated with it.
  936. * A caret is a visual location in the TextLayout indicating where text at
  937. * the TextHitInfo will be displayed on screen. If a TextHitInfo
  938. * represents a location on a directional boundary, then there are two
  939. * possible visible positions for newly inserted text. Consider the
  940. * following example, in which capital letters indicate right-to-left text,
  941. * and the overall line direction is left-to-right:
  942. *
  943. * Text Storage: [ a, b, C, D, E, f ]
  944. * Display: a b E D C f
  945. *
  946. * The text hit info (1, t) represents the trailing side of 'b'. If 'q',
  947. * a left-to-right character is inserted into the text storage at this
  948. * location, it will be displayed between the 'b' and the 'E':
  949. *
  950. * Text Storage: [ a, b, q, C, D, E, f ]
  951. * Display: a b q E D C f
  952. *
  953. * However, if a 'W', which is right-to-left, is inserted into the storage
  954. * after 'b', the storage and display will be:
  955. *
  956. * Text Storage: [ a, b, W, C, D, E, f ]
  957. * Display: a b E D C W f
  958. *
  959. * So, for the original text storage, two carets should be displayed for
  960. * location (1, t): one visually between 'b' and 'E' and one visually
  961. * between 'C' and 'f'.
  962. *
  963. *
  964. * When two carets are displayed for a TextHitInfo, one caret is the
  965. * 'strong' caret and the other is the 'weak' caret. The strong caret
  966. * indicates where an inserted character will be displayed when that
  967. * character's direction is the same as the direction of the TextLayout.
  968. * The weak caret shows where an character inserted character will be
  969. * displayed when the character's direction is opposite that of the
  970. * TextLayout.
  971. *
  972. *
  973. * Clients should not be overly concerned with the details of correct
  974. * caret display. TextLayout.getCaretShapes(TextHitInfo) will return an
  975. * array of two paths representing where carets should be displayed.
  976. * The first path in the array is the strong caret; the second element,
  977. * if non-null, is the weak caret. If the second element is null,
  978. * then there is no weak caret for the given TextHitInfo.
  979. *
  980. *
  981. * Since text can be visually reordered, logically consecutive
  982. * TextHitInfo's may not be visually consecutive. One implication of this
  983. * is that a client cannot tell from inspecting a TextHitInfo whether the
  984. * hit represents the first (or last) caret in the layout. Clients
  985. * can call getVisualOtherHit(); if the visual companion is
  986. * (-1, TRAILING) or (characterCount, LEADING), then the hit is at the
  987. * first (last) caret position in the layout.
  988. */
  989. private float[] getCaretInfo(int caret,
  990. Rectangle2D bounds,
  991. float[] info) {
  992. float top1X, top2X;
  993. float bottom1X, bottom2X;
  994. if (caret == 0 || caret == characterCount) {
  995. float pos;
  996. int logIndex;
  997. if (caret == characterCount) {
  998. logIndex = textLine.visualToLogical(characterCount-1);
  999. pos = textLine.getCharLinePosition(logIndex)
  1000. + textLine.getCharAdvance(logIndex);
  1001. }
  1002. else {
  1003. logIndex = textLine.visualToLogical(caret);
  1004. pos = textLine.getCharLinePosition(logIndex);
  1005. }
  1006. float angle = textLine.getCharAngle(logIndex);
  1007. top1X = top2X = pos + angle*textLine.getCharAscent(logIndex);
  1008. bottom1X = bottom2X = pos - angle*textLine.getCharDescent(logIndex);
  1009. }
  1010. else {
  1011. {
  1012. int logIndex = textLine.visualToLogical(caret-1);
  1013. float angle1 = textLine.getCharAngle(logIndex);
  1014. float pos1 = textLine.getCharLinePosition(logIndex)
  1015. + textLine.getCharAdvance(logIndex);
  1016. if (angle1 != 0) {
  1017. top1X = pos1 + angle1*textLine.getCharAscent(logIndex);
  1018. bottom1X = pos1 - angle1*textLine.getCharDescent(logIndex);
  1019. }
  1020. else {
  1021. top1X = bottom1X = pos1;
  1022. }
  1023. }
  1024. {
  1025. int logIndex = textLine.visualToLogical(caret);
  1026. float angle2 = textLine.getCharAngle(logIndex);
  1027. float pos2 = textLine.getCharLinePosition(logIndex);
  1028. if (angle2 != 0) {
  1029. top2X = pos2 + angle2*textLine.getCharAscent(logIndex);
  1030. bottom2X = pos2 - angle2*textLine.getCharDescent(logIndex);
  1031. }
  1032. else {
  1033. top2X = bottom2X = pos2;
  1034. }
  1035. }
  1036. }
  1037. float topX = (top1X + top2X) / 2;
  1038. float bottomX = (bottom1X + bottom2X) / 2;
  1039. if (info == null) {
  1040. info = new float[2];
  1041. }
  1042. if (isVerticalLine) {
  1043. info[1] = (float) ((topX - bottomX) / bounds.getWidth());
  1044. info[0] = (float) (topX + (info[1]*bounds.getX()));
  1045. }
  1046. else {
  1047. info[1] = (float) ((topX - bottomX) / bounds.getHeight());
  1048. info[0] = (float) (bottomX + (info[1]*bounds.getMaxY()));
  1049. }
  1050. return info;
  1051. }
  1052. /**
  1053. * Returns information about the caret corresponding to <code>hit</code>.
  1054. * The first element of the array is the intersection of the caret with
  1055. * the baseline. The second element of the array is the inverse slope
  1056. * (run/rise) of the caret.
  1057. * <p>
  1058. * This method is meant for informational use. To display carets, it
  1059. * is better to use <code>getCaretShapes</code>.
  1060. * @param hit a hit on a character in this <code>TextLayout</code>
  1061. * @param bounds the bounds to which the caret info is constructed
  1062. * @return a two-element array containing the position and slope of
  1063. * the caret.
  1064. * @see #getCaretShapes(int, Rectangle2D, TextLayout.CaretPolicy)
  1065. * @see Font#getItalicAngle
  1066. */
  1067. public float[] getCaretInfo(TextHitInfo hit, Rectangle2D bounds) {
  1068. ensureCache();
  1069. checkTextHit(hit);
  1070. return getCaretInfo(hitToCaret(hit), bounds, null);
  1071. }
  1072. /**
  1073. * Returns information about the caret corresponding to <code>hit</code>.
  1074. * This method is a convenience overload of <code>getCaretInfo</code> and
  1075. * uses the natural bounds of this <code>TextLayout</code>.
  1076. * @param hit a hit on a character in this <code>TextLayout</code>
  1077. * @return the information about a caret corresponding to a hit.
  1078. */
  1079. public float[] getCaretInfo(TextHitInfo hit) {
  1080. return getCaretInfo(hit, getNaturalBounds());
  1081. }
  1082. /**
  1083. * Returns a caret index corresponding to <code>hit</code>.
  1084. * Carets are numbered from left to right (top to bottom) starting from
  1085. * zero. This always places carets next to the character hit, on the
  1086. * indicated side of the character.
  1087. * @param hit a hit on a character in this <code>TextLayout</code>
  1088. * @return a caret index corresponding to the specified hit.
  1089. */
  1090. private int hitToCaret(TextHitInfo hit) {
  1091. int hitIndex = hit.getCharIndex();
  1092. if (hitIndex < 0) {
  1093. return textLine.isDirectionLTR() ? 0 : characterCount;
  1094. } else if (hitIndex >= characterCount) {
  1095. return textLine.isDirectionLTR() ? characterCount : 0;
  1096. }
  1097. int visIndex = textLine.logicalToVisual(hitIndex);
  1098. if (hit.isLeadingEdge() != textLine.isCharLTR(hitIndex)) {
  1099. ++visIndex;
  1100. }
  1101. return visIndex;
  1102. }
  1103. /**
  1104. * Given a caret index, return a hit whose caret is at the index.
  1105. * The hit is NOT guaranteed to be strong!!!
  1106. *
  1107. * @param caret a caret index.
  1108. * @return a hit on this layout whose strong caret is at the requested
  1109. * index.
  1110. */
  1111. private TextHitInfo caretToHit(int caret) {
  1112. if (caret == 0 || caret == characterCount) {
  1113. if ((caret == characterCount) == textLine.isDirectionLTR()) {
  1114. return TextHitInfo.leading(characterCount);
  1115. }
  1116. else {
  1117. return TextHitInfo.trailing(-1);
  1118. }
  1119. }
  1120. else {
  1121. int charIndex = textLine.visualToLogical(caret);
  1122. boolean leading = textLine.isCharLTR(charIndex);
  1123. return leading? TextHitInfo.leading(charIndex)
  1124. : TextHitInfo.trailing(charIndex);
  1125. }
  1126. }
  1127. private boolean caretIsValid(int caret) {
  1128. if (caret == characterCount || caret == 0) {
  1129. return true;
  1130. }
  1131. int offset = textLine.visualToLogical(caret);
  1132. if (!textLine.isCharLTR(offset)) {
  1133. offset = textLine.visualToLogical(caret-1);
  1134. if (textLine.isCharLTR(offset)) {
  1135. return true;
  1136. }
  1137. }
  1138. // At this point, the leading edge of the character
  1139. // at offset is at the given caret.
  1140. return textLine.caretAtOffsetIsValid(offset);
  1141. }
  1142. /**
  1143. * Returns the hit for the next caret to the right (bottom); if there
  1144. * is no such hit, returns <code>null</code>.
  1145. * If the hit character index is out of bounds, an
  1146. * {@link IllegalArgumentException} is thrown.
  1147. * @param hit a hit on a character in this layout
  1148. * @return a hit whose caret appears at the next position to the
  1149. * right (bottom) of the caret of the provided hit or <code>null</code>.
  1150. */
  1151. public TextHitInfo getNextRightHit(TextHitInfo hit) {
  1152. ensureCache();
  1153. checkTextHit(hit);
  1154. int caret = hitToCaret(hit);
  1155. if (caret == characterCount) {
  1156. return null;
  1157. }
  1158. do {
  1159. ++caret;
  1160. } while (!caretIsValid(caret));
  1161. return caretToHit(caret);
  1162. }
  1163. /**
  1164. * Returns the hit for the next caret to the right (bottom); if no
  1165. * such hit, returns <code>null</code>. The hit is to the right of
  1166. * the strong caret at the specified offset, as determined by the
  1167. * specified policy.
  1168. * The returned hit is the stronger of the two possible
  1169. * hits, as determined by the specified policy.
  1170. * @param offset an insertion offset in this <code>TextLayout</code>.
  1171. * Cannot be less than 0 or greater than this <code>TextLayout</code>
  1172. * object's character count.
  1173. * @param policy the policy used to select the strong caret
  1174. * @return a hit whose caret appears at the next position to the
  1175. * right (bottom) of the caret of the provided hit, or <code>null</code>.
  1176. */
  1177. public TextHitInfo getNextRightHit(int offset, CaretPolicy policy) {
  1178. if (offset < 0 || offset > characterCount) {
  1179. throw new IllegalArgumentException("Offset out of bounds in TextLayout.getNextRightHit()");
  1180. }
  1181. if (policy == null) {
  1182. throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getNextRightHit()");
  1183. }
  1184. TextHitInfo hit1 = TextHitInfo.afterOffset(offset);
  1185. TextHitInfo hit2 = hit1.getOtherHit();
  1186. TextHitInfo nextHit = getNextRightHit(policy.getStrongCaret(hit1, hit2, this));
  1187. if (nextHit != null) {
  1188. TextHitInfo otherHit = getVisualOtherHit(nextHit);
  1189. return policy.getStrongCaret(otherHit, nextHit, this);
  1190. }
  1191. else {
  1192. return null;
  1193. }
  1194. }
  1195. /**
  1196. * Returns the hit for the next caret to the right (bottom); if no
  1197. * such hit, returns <code>null</code>. The hit is to the right of
  1198. * the strong caret at the specified offset, as determined by the
  1199. * default policy.
  1200. * The returned hit is the stronger of the two possible
  1201. * hits, as determined by the default policy.
  1202. * @param offset an insertion offset in this <code>TextLayout</code>.
  1203. * Cannot be less than 0 or greater than the <code>TextLayout</code>
  1204. * object's character count.
  1205. * @return a hit whose caret appears at the next position to the
  1206. * right (bottom) of the caret of the provided hit, or <code>null</code>.
  1207. */
  1208. public TextHitInfo getNextRightHit(int offset) {
  1209. return getNextRightHit(offset, DEFAULT_CARET_POLICY);
  1210. }
  1211. /**
  1212. * Returns the hit for the next caret to the left (top); if no such
  1213. * hit, returns <code>null</code>.
  1214. * If the hit character index is out of bounds, an
  1215. * <code>IllegalArgumentException</code> is thrown.
  1216. * @param hit a hit on a character in this <code>TextLayout</code>.
  1217. * @return a hit whose caret appears at the next position to the
  1218. * left (top) of the caret of the provided hit, or <code>null</code>.
  1219. */
  1220. public TextHitInfo getNextLeftHit(TextHitInfo hit) {
  1221. ensureCache();
  1222. checkTextHit(hit);
  1223. int caret = hitToCaret(hit);
  1224. if (caret == 0) {
  1225. return null;
  1226. }
  1227. do {
  1228. --caret;
  1229. } while(!caretIsValid(caret));
  1230. return caretToHit(caret);
  1231. }
  1232. /**
  1233. * Returns the hit for the next caret to the left (top); if no
  1234. * such hit, returns <code>null</code>. The hit is to the left of
  1235. * the strong caret at the specified offset, as determined by the
  1236. * specified policy.
  1237. * The returned hit is the stronger of the two possible
  1238. * hits, as determined by the specified policy.
  1239. * @param offset an insertion offset in this <code>TextLayout</code>.
  1240. * Cannot be less than 0 or greater than this <code>TextLayout</code>
  1241. * object's character count.
  1242. * @param policy the policy used to select the strong caret
  1243. * @return a hit whose caret appears at the next position to the
  1244. * left (top) of the caret of the provided hit, or <code>null</code>.
  1245. */
  1246. public TextHitInfo getNextLeftHit(int offset, CaretPolicy policy) {
  1247. if (policy == null) {
  1248. throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getNextLeftHit()");
  1249. }
  1250. if (offset < 0 || offset > characterCount) {
  1251. throw new IllegalArgumentException("Offset out of bounds in TextLayout.getNextLeftHit()");
  1252. }
  1253. TextHitInfo hit1 = TextHitInfo.afterOffset(offset);
  1254. TextHitInfo hit2 = hit1.getOtherHit();
  1255. TextHitInfo nextHit = getNextLeftHit(policy.getStrongCaret(hit1, hit2, this));
  1256. if (nextHit != null) {
  1257. TextHitInfo otherHit = getVisualOtherHit(nextHit);
  1258. return policy.getStrongCaret(otherHit, nextHit, this);
  1259. }
  1260. else {
  1261. return null;
  1262. }
  1263. }
  1264. /**
  1265. * Returns the hit for the next caret to the left (top); if no
  1266. * such hit, returns <code>null</code>. The hit is to the left of
  1267. * the strong caret at the specified offset, as determined by the
  1268. * default policy.
  1269. * The returned hit is the stronger of the two possible
  1270. * hits, as determined by the default policy.
  1271. * @param offset an insertion offset in this <code>TextLayout</code>.
  1272. * Cannot be less than 0 or greater than this <code>TextLayout</code>
  1273. * object's character count.
  1274. * @return a hit whose caret appears at the next position to the
  1275. * left (top) of the caret of the provided hit, or <code>null</code>.
  1276. */
  1277. public TextHitInfo getNextLeftHit(int offset) {
  1278. return getNextLeftHit(offset, DEFAULT_CARET_POLICY);
  1279. }
  1280. /**
  1281. * Returns the hit on the opposite side of the specified hit's caret.
  1282. * @param hit the specified hit
  1283. * @return a hit that is on the opposite side of the specified hit's
  1284. * caret.
  1285. */
  1286. public TextHitInfo getVisualOtherHit(TextHitInfo hit) {
  1287. ensureCache();
  1288. checkTextHit(hit);
  1289. int hitCharIndex = hit.getCharIndex();
  1290. int charIndex;
  1291. boolean leading;
  1292. if (hitCharIndex == -1 || hitCharIndex == characterCount) {
  1293. int visIndex;
  1294. if (textLine.isDirectionLTR() == (hitCharIndex == -1)) {
  1295. visIndex = 0;
  1296. }
  1297. else {
  1298. visIndex = characterCount-1;
  1299. }
  1300. charIndex = textLine.visualToLogical(visIndex);
  1301. if (textLine.isDirectionLTR() == (hitCharIndex == -1)) {
  1302. // at left end
  1303. leading = textLine.isCharLTR(charIndex);
  1304. }
  1305. else {
  1306. // at right end
  1307. leading = !textLine.isCharLTR(charIndex);
  1308. }
  1309. }
  1310. else {
  1311. int visIndex = textLine.logicalToVisual(hitCharIndex);
  1312. boolean movedToRight;
  1313. if (textLine.isCharLTR(hitCharIndex) == hit.isLeadingEdge()) {
  1314. --visIndex;
  1315. movedToRight = false;
  1316. }
  1317. else {
  1318. ++visIndex;
  1319. movedToRight = true;
  1320. }
  1321. if (visIndex > -1 && visIndex < characterCount) {
  1322. charIndex = textLine.visualToLogical(visIndex);
  1323. leading = movedToRight == textLine.isCharLTR(charIndex);
  1324. }
  1325. else {
  1326. charIndex =
  1327. (movedToRight == textLine.isDirectionLTR())? characterCount : -1;
  1328. leading = charIndex == characterCount;
  1329. }
  1330. }
  1331. return leading? TextHitInfo.leading(charIndex) :
  1332. TextHitInfo.trailing(charIndex);
  1333. }
  1334. /**
  1335. * Return an array of four floats corresponding the endpoints of the caret
  1336. * x0, y0, x1, y1.
  1337. *
  1338. * This creates a line along the slope of the caret intersecting the
  1339. * baseline at the caret
  1340. * position, and extending from ascent above the baseline to descent below
  1341. * it.
  1342. */
  1343. private double[] getCaretPath(int caret, Rectangle2D bounds,
  1344. boolean clipToBounds) {
  1345. float[] info = getCaretInfo(caret, bounds, null);
  1346. double pos = info[0];
  1347. double slope = info[1];
  1348. double x0, y0, x1, y1;
  1349. double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy
  1350. double left = bounds.getX();
  1351. double right = left + bounds.getWidth();
  1352. double top = bounds.getY();
  1353. double bottom = top + bounds.getHeight();
  1354. boolean threePoints = false;
  1355. if (isVerticalLine) {
  1356. if (slope >= 0) {
  1357. x0 = left;
  1358. x1 = right;
  1359. }
  1360. else {
  1361. x1 = left;
  1362. x0 = right;
  1363. }
  1364. y0 = pos + x0 * slope;
  1365. y1 = pos + x1 * slope;
  1366. // y0 <= y1, always
  1367. if (clipToBounds) {
  1368. if (y0 < top) {
  1369. if (slope <= 0 || y1 <= top) {
  1370. y0 = y1 = top;
  1371. }
  1372. else {
  1373. threePoints = true;
  1374. y0 = top;
  1375. y2 = top;
  1376. x2 = x1 + (top-y1)/slope;
  1377. if (y1 > bottom) {
  1378. y1 = bottom;
  1379. }
  1380. }
  1381. }
  1382. else if (y1 > bottom) {
  1383. if (slope >= 0 || y0 >= bottom) {
  1384. y0 = y1 = bottom;
  1385. }
  1386. else {
  1387. threePoints = true;
  1388. y1 = bottom;
  1389. y2 = bottom;
  1390. x2 = x0 + (bottom-x1)/slope;
  1391. }
  1392. }
  1393. }
  1394. }
  1395. else {
  1396. if (slope >= 0) {
  1397. y0 = bottom;
  1398. y1 = top;
  1399. }
  1400. else {
  1401. y1 = bottom;
  1402. y0 = top;
  1403. }
  1404. x0 = pos - y0 * slope;
  1405. x1 = pos - y1 * slope;
  1406. // x0 <= x1, always
  1407. if (clipToBounds) {
  1408. if (x0 < left) {
  1409. if (slope <= 0 || x1 <= left) {
  1410. x0 = x1 = left;
  1411. }
  1412. else {
  1413. threePoints = true;
  1414. x0 = left;
  1415. x2 = left;
  1416. y2 = y1 - (left-x1)/slope;
  1417. if (x1 > right) {
  1418. x1 = right;
  1419. }
  1420. }
  1421. }
  1422. else if (x1 > right) {
  1423. if (slope >= 0 || x0 >= r