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