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 >= right) {
  1424. x0 = x1 = right;
  1425. }
  1426. else {
  1427. threePoints = true;
  1428. x1 = right;
  1429. x2 = right;
  1430. y2 = y0 - (right-x0)/slope;
  1431. }
  1432. }
  1433. }
  1434. }
  1435. return threePoints?
  1436. new double[] { x0, y0, x2, y2, x1, y1 } :
  1437. new double[] { x0, y0, x1, y1 };
  1438. }
  1439. private static GeneralPath pathToShape(double[] path, boolean close) {
  1440. GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length);
  1441. result.moveTo((float)path[0], (float)path[1]);
  1442. for (int i = 2; i < path.length; i += 2) {
  1443. result.lineTo((float)path[i], (float)path[i+1]);
  1444. }
  1445. if (close) {
  1446. result.closePath();
  1447. }
  1448. return result;
  1449. }
  1450. /**
  1451. * Returns a {@link Shape} representing the caret at the specified
  1452. * hit inside the specified bounds.
  1453. * @param hit the hit at which to generate the caret
  1454. * @param bounds the bounds of the <code>TextLayout</code> to use
  1455. * in generating the caret.
  1456. * @return a <code>Shape</code> representing the caret.
  1457. */
  1458. public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) {
  1459. checkTextHit(hit);
  1460. if (bounds == null) {
  1461. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()");
  1462. }
  1463. int hitCaret = hitToCaret(hit);
  1464. GeneralPath hitShape =
  1465. pathToShape(getCaretPath(hitCaret, bounds, false), false);
  1466. //return new Highlight(hitShape, true);
  1467. return hitShape;
  1468. }
  1469. /**
  1470. * Returns a <code>Shape</code> representing the caret at the specified
  1471. * hit inside the natural bounds of this <code>TextLayout</code>.
  1472. * @param hit the hit at which to generate the caret
  1473. * @return a <code>Shape</code> representing the caret.
  1474. */
  1475. public Shape getCaretShape(TextHitInfo hit) {
  1476. return getCaretShape(hit, getNaturalBounds());
  1477. }
  1478. /**
  1479. * Return the "stronger" of the TextHitInfos. The TextHitInfos
  1480. * should be logical or visual counterparts. They are not
  1481. * checked for validity.
  1482. */
  1483. private final TextHitInfo getStrongHit(TextHitInfo hit1, TextHitInfo hit2) {
  1484. // right now we're using the following rule for strong hits:
  1485. // A hit on a character with a lower level
  1486. // is stronger than one on a character with a higher level.
  1487. // If this rule ties, the hit on the leading edge of a character wins.
  1488. // If THIS rule ties, hit1 wins. Both rules shouldn't tie, unless the
  1489. // infos aren't counterparts of some sort.
  1490. byte hit1Level = getCharacterLevel(hit1.getCharIndex());
  1491. byte hit2Level = getCharacterLevel(hit2.getCharIndex());
  1492. if (hit1Level == hit2Level) {
  1493. if (hit2.isLeadingEdge() && !hit1.isLeadingEdge()) {
  1494. return hit2;
  1495. }
  1496. else {
  1497. return hit1;
  1498. }
  1499. }
  1500. else {
  1501. return (hit1Level < hit2Level)? hit1 : hit2;
  1502. }
  1503. }
  1504. /**
  1505. * Returns the level of the character at <code>index</code>.
  1506. * Indices -1 and <code>characterCount</code> are assigned the base
  1507. * level of this <code>TextLayout</code>.
  1508. * @param index the index of the character from which to get the level
  1509. * @return the level of the character at the specified index.
  1510. */
  1511. public byte getCharacterLevel(int index) {
  1512. // hmm, allow indices at endpoints? For now, yes.
  1513. if (index == -1 || index == characterCount) {
  1514. return (byte) (textLine.isDirectionLTR()? 0 : 1);
  1515. }
  1516. if (index < 0 || index >= characterCount) {
  1517. throw new IllegalArgumentException("Index is out of range in getCharacterLevel.");
  1518. }
  1519. return textLine.getCharLevel(index);
  1520. }
  1521. /**
  1522. * Returns two paths corresponding to the strong and weak caret.
  1523. * @param offset an offset in this <code>TextLayout</code>
  1524. * @param bounds the bounds to which to extend the carets
  1525. * @param policy the specified <code>CaretPolicy</code>
  1526. * @return an array of two paths. Element zero is the strong
  1527. * caret. If there are two carets, element one is the weak caret,
  1528. * otherwise it is <code>null</code>.
  1529. */
  1530. public Shape[] getCaretShapes(int offset, Rectangle2D bounds, CaretPolicy policy) {
  1531. ensureCache();
  1532. if (offset < 0 || offset > characterCount) {
  1533. throw new IllegalArgumentException("Offset out of bounds in TextLayout.getCaretShapes()");
  1534. }
  1535. if (bounds == null) {
  1536. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaretShapes()");
  1537. }
  1538. if (policy == null) {
  1539. throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getCaretShapes()");
  1540. }
  1541. Shape[] result = new Shape[2];
  1542. TextHitInfo hit = TextHitInfo.afterOffset(offset);
  1543. int hitCaret = hitToCaret(hit);
  1544. Shape hitShape =
  1545. pathToShape(getCaretPath(hitCaret, bounds, false), false);
  1546. TextHitInfo otherHit = hit.getOtherHit();
  1547. int otherCaret = hitToCaret(otherHit);
  1548. if (hitCaret == otherCaret) {
  1549. result[0] = hitShape;
  1550. }
  1551. else { // more than one caret
  1552. Shape otherShape =
  1553. pathToShape(getCaretPath(otherCaret, bounds, false), false);
  1554. TextHitInfo strongHit = policy.getStrongCaret(hit, otherHit, this);
  1555. boolean hitIsStrong = strongHit.equals(hit);
  1556. if (hitIsStrong) {// then other is weak
  1557. result[0] = hitShape;
  1558. result[1] = otherShape;
  1559. }
  1560. else {
  1561. result[0] = otherShape;
  1562. result[1] = hitShape;
  1563. }
  1564. }
  1565. return result;
  1566. }
  1567. /**
  1568. * Returns two paths corresponding to the strong and weak caret.
  1569. * This method is a convenience overload of <code>getCaretShapes</code>
  1570. * that uses the default caret policy.
  1571. * @param offset an offset in this <code>TextLayout</code>
  1572. * @param bounds the bounds to which to extend the carets
  1573. * @return two paths corresponding to the strong and weak caret as
  1574. * defined by the <code>DEFAULT_CARET_POLICY</code>
  1575. */
  1576. public Shape[] getCaretShapes(int offset, Rectangle2D bounds) {
  1577. // {sfb} parameter checking is done in overloaded version
  1578. return getCaretShapes(offset, bounds, DEFAULT_CARET_POLICY);
  1579. }
  1580. /**
  1581. * Returns two paths corresponding to the strong and weak caret.
  1582. * This method is a convenience overload of <code>getCaretShapes</code>
  1583. * that uses the default caret policy and this <code>TextLayout</code>
  1584. * object's natural bounds.
  1585. * @param offset an offset in this <code>TextLayout</code>
  1586. * @param bounds the bounds to which to extend the carets
  1587. * @return two paths corresponding to the strong and weak caret as
  1588. * defined by the <code>DEFAULT_CARET_POLICY</code>
  1589. */
  1590. public Shape[] getCaretShapes(int offset) {
  1591. // {sfb} parameter checking is done in overloaded version
  1592. return getCaretShapes(offset, getNaturalBounds(), DEFAULT_CARET_POLICY);
  1593. }
  1594. // A utility to return a path enclosing the given path
  1595. // Path0 must be left or top of path1
  1596. // {jbr} no assumptions about size of path0, path1 anymore.
  1597. private GeneralPath boundingShape(double[] path0, double[] path1) {
  1598. // Really, we want the path to be a convex hull around all of the
  1599. // points in path0 and path1. But we can get by with less than
  1600. // that. We do need to prevent the two segments which
  1601. // join path0 to path1 from crossing each other. So, if we
  1602. // traverse path0 from top to bottom, we'll traverse path1 from
  1603. // bottom to top (and vice versa).
  1604. GeneralPath result = pathToShape(path0, false);
  1605. boolean sameDirection;
  1606. if (isVerticalLine) {
  1607. sameDirection = (path0[1] > path0[path0.length-1]) ==
  1608. (path1[1] > path1[path1.length-1]);
  1609. }
  1610. else {
  1611. sameDirection = (path0[0] > path0[path0.length-2]) ==
  1612. (path1[0] > path1[path1.length-2]);
  1613. }
  1614. int start;
  1615. int limit;
  1616. int increment;
  1617. if (sameDirection) {
  1618. start = path1.length-2;
  1619. limit = -2;
  1620. increment = -2;
  1621. }
  1622. else {
  1623. start = 0;
  1624. limit = path1.length;
  1625. increment = 2;
  1626. }
  1627. for (int i = start; i != limit; i += increment) {
  1628. result.lineTo((float)path1[i], (float)path1[i+1]);
  1629. }
  1630. result.closePath();
  1631. return result;
  1632. }
  1633. // A utility to convert a pair of carets into a bounding path
  1634. // {jbr} Shape is never outside of bounds.
  1635. private GeneralPath caretBoundingShape(int caret0,
  1636. int caret1,
  1637. Rectangle2D bounds) {
  1638. if (caret0 > caret1) {
  1639. int temp = caret0;
  1640. caret0 = caret1;
  1641. caret1 = temp;
  1642. }
  1643. return boundingShape(getCaretPath(caret0, bounds, true),
  1644. getCaretPath(caret1, bounds, true));
  1645. }
  1646. /*
  1647. * A utility to return the path bounding the area to the left (top) of the
  1648. * layout.
  1649. * Shape is never outside of bounds.
  1650. */
  1651. private GeneralPath leftShape(Rectangle2D bounds) {
  1652. double[] path0;
  1653. if (isVerticalLine) {
  1654. path0 = new double[] { bounds.getX(), bounds.getY(),
  1655. bounds.getX() + bounds.getWidth(),
  1656. bounds.getY() };
  1657. } else {
  1658. path0 = new double[] { bounds.getX(),
  1659. bounds.getY() + bounds.getHeight(),
  1660. bounds.getX(), bounds.getY() };
  1661. }
  1662. double[] path1 = getCaretPath(0, bounds, true);
  1663. return boundingShape(path0, path1);
  1664. }
  1665. /*
  1666. * A utility to return the path bounding the area to the right (bottom) of
  1667. * the layout.
  1668. */
  1669. private GeneralPath rightShape(Rectangle2D bounds) {
  1670. double[] path1;
  1671. if (isVerticalLine) {
  1672. path1 = new double[] {
  1673. bounds.getX(),
  1674. bounds.getY() + bounds.getHeight(),
  1675. bounds.getX() + bounds.getWidth(),
  1676. bounds.getY() + bounds.getHeight()
  1677. };
  1678. } else {
  1679. path1 = new double[] {
  1680. bounds.getX() + bounds.getWidth(),
  1681. bounds.getY() + bounds.getHeight(),
  1682. bounds.getX() + bounds.getWidth(),
  1683. bounds.getY()
  1684. };
  1685. }
  1686. double[] path0 = getCaretPath(characterCount, bounds, true);
  1687. return boundingShape(path0, path1);
  1688. }
  1689. /**
  1690. * Returns the logical ranges of text corresponding to a visual selection.
  1691. * @param firstEndpoint an endpoint of the visual range
  1692. * @param secondEndpoint the other endpoint of the visual range.
  1693. * This endpoint can be less than <code>firstEndpoint</code>.
  1694. * @return an array of integers representing start/limit pairs for the
  1695. * selected ranges.
  1696. * @see #getVisualHighlightShape(TextHitInfo, TextHitInfo, Rectangle2D)
  1697. */
  1698. public int[] getLogicalRangesForVisualSelection(TextHitInfo firstEndpoint,
  1699. TextHitInfo secondEndpoint) {
  1700. ensureCache();
  1701. checkTextHit(firstEndpoint);
  1702. checkTextHit(secondEndpoint);
  1703. // !!! probably want to optimize for all LTR text
  1704. boolean[] included = new boolean[characterCount];
  1705. int startIndex = hitToCaret(firstEndpoint);
  1706. int limitIndex = hitToCaret(secondEndpoint);
  1707. if (startIndex > limitIndex) {
  1708. int t = startIndex;
  1709. startIndex = limitIndex;
  1710. limitIndex = t;
  1711. }
  1712. /*
  1713. * now we have the visual indexes of the glyphs at the start and limit
  1714. * of the selection range walk through runs marking characters that
  1715. * were included in the visual range there is probably a more efficient
  1716. * way to do this, but this ought to work, so hey
  1717. */
  1718. if (startIndex < limitIndex) {
  1719. int visIndex = startIndex;
  1720. while (visIndex < limitIndex) {
  1721. included[textLine.visualToLogical(visIndex)] = true;
  1722. ++visIndex;
  1723. }
  1724. }
  1725. /*
  1726. * count how many runs we have, ought to be one or two, but perhaps
  1727. * things are especially weird
  1728. */
  1729. int count = 0;
  1730. boolean inrun = false;
  1731. for (int i = 0; i < characterCount; i++) {
  1732. if (included[i] != inrun) {
  1733. inrun = !inrun;
  1734. if (inrun) {
  1735. count++;
  1736. }
  1737. }
  1738. }
  1739. int[] ranges = new int[count * 2];
  1740. count = 0;
  1741. inrun = false;
  1742. for (int i = 0; i < characterCount; i++) {
  1743. if (included[i] != inrun) {
  1744. ranges[count++] = i;
  1745. inrun = !inrun;
  1746. }
  1747. }
  1748. if (inrun) {
  1749. ranges[count++] = characterCount;
  1750. }
  1751. return ranges;
  1752. }
  1753. /**
  1754. * Returns a path enclosing the visual selection in the specified range,
  1755. * extended to <code>bounds</code>.
  1756. * <p>
  1757. * If the selection includes the leftmost (topmost) position, the selection
  1758. * is extended to the left (top) of <code>bounds</code>. If the
  1759. * selection includes the rightmost (bottommost) position, the selection
  1760. * is extended to the right (bottom) of the bounds. The height
  1761. * (width on vertical lines) of the selection is always extended to
  1762. * <code>bounds</code>.
  1763. * <p>
  1764. * Although the selection is always contiguous, the logically selected
  1765. * text can be discontiguous on lines with mixed-direction text. The
  1766. * logical ranges of text selected can be retrieved using
  1767. * <code>getLogicalRangesForVisualSelection</code>. For example,
  1768. * consider the text 'ABCdef' where capital letters indicate
  1769. * right-to-left text, rendered on a right-to-left line, with a visual
  1770. * selection from 0L (the leading edge of 'A') to 3T (the trailing edge
  1771. * of 'd'). The text appears as follows, with bold underlined areas
  1772. * representing the selection:
  1773. * <br><pre>
  1774. * d<u><b>efCBA </b></u>
  1775. * </pre>
  1776. * The logical selection ranges are 0-3, 4-6 (ABC, ef) because the
  1777. * visually contiguous text is logically discontiguous. Also note that
  1778. * since the rightmost position on the layout (to the right of 'A') is
  1779. * selected, the selection is extended to the right of the bounds.
  1780. * @param firstEndpoint one end of the visual selection
  1781. * @param secondEndpoint the other end of the visual selection
  1782. * @param bounds the bounding rectangle to which to extend the selection
  1783. * @return a <code>Shape</code> enclosing the selection.
  1784. * @see #getLogicalRangesForVisualSelection(TextHitInfo, TextHitInfo)
  1785. * @see #getLogicalHighlightShape(int, int, Rectangle2D)
  1786. */
  1787. public Shape getVisualHighlightShape(TextHitInfo firstEndpoint,
  1788. TextHitInfo secondEndpoint,
  1789. Rectangle2D bounds)
  1790. {
  1791. ensureCache();
  1792. checkTextHit(firstEndpoint);
  1793. checkTextHit(secondEndpoint);
  1794. if(bounds == null) {
  1795. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getVisualHighlightShape()");
  1796. }
  1797. GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
  1798. int firstCaret = hitToCaret(firstEndpoint);
  1799. int secondCaret = hitToCaret(secondEndpoint);
  1800. result.append(caretBoundingShape(firstCaret, secondCaret, bounds),
  1801. false);
  1802. if (firstCaret == 0 || secondCaret == 0) {
  1803. result.append(leftShape(bounds), false);
  1804. }
  1805. if (firstCaret == characterCount || secondCaret == characterCount) {
  1806. result.append(rightShape(bounds), false);
  1807. }
  1808. //return new Highlight(result, false);
  1809. return result;
  1810. }
  1811. /**
  1812. * Returns a <code>Shape</code> enclosing the visual selection in the
  1813. * specified range, extended to the bounds. This method is a
  1814. * convenience overload of <code>getVisualHighlightShape</code> that
  1815. * uses the natural bounds of this <code>TextLayout</code>.
  1816. * @param firstEndpoint one end of the visual selection
  1817. * @param secondEndpoint the other end of the visual selection
  1818. * @return a <code>Shape</code> enclosing the selection.
  1819. */
  1820. public Shape getVisualHighlightShape(TextHitInfo firstEndpoint,
  1821. TextHitInfo secondEndpoint) {
  1822. return getVisualHighlightShape(firstEndpoint, secondEndpoint, getNaturalBounds());
  1823. }
  1824. /**
  1825. * Returns a <code>Shape</code> enclosing the logical selection in the
  1826. * specified range, extended to the specified <code>bounds</code>.
  1827. * <p>
  1828. * If the selection range includes the first logical character, the
  1829. * selection is extended to the portion of <code>bounds</code> before
  1830. * the start of this <code>TextLayout</code>. If the range includes
  1831. * the last logical character, the selection is extended to the portion
  1832. * of <code>bounds</code> after the end of this <code>TextLayout</code>.
  1833. * The height (width on vertical lines) of the selection is always
  1834. * extended to <code>bounds</code>.
  1835. * <p>
  1836. * The selection can be discontiguous on lines with mixed-direction text.
  1837. * Only those characters in the logical range between start and limit
  1838. * appear selected. For example, consider the text 'ABCdef' where capital
  1839. * letters indicate right-to-left text, rendered on a right-to-left line,
  1840. * with a logical selection from 0 to 4 ('ABCd'). The text appears as
  1841. * follows, with bold standing in for the selection, and underlining for
  1842. * the extension:
  1843. * <br><pre>
  1844. * <u><b>d</b></u>ef<u><b>CBA </b></u>
  1845. * </pre>
  1846. * The selection is discontiguous because the selected characters are
  1847. * visually discontiguous. Also note that since the range includes the
  1848. * first logical character (A), the selection is extended to the portion
  1849. * of the <code>bounds</code> before the start of the layout, which in
  1850. * this case (a right-to-left line) is the right portion of the
  1851. * <code>bounds</code>.
  1852. * @param firstEndpoint an endpoint in the range of characters to select
  1853. * @param secondEndpoint the other endpoint of the range of characters
  1854. * to select. Can be less than <code>firstEndpoint</code>. The range
  1855. * includes the character at min(firstEndpoint, secondEndpoint), but
  1856. * excludes max(firstEndpoint, secondEndpoint).
  1857. * @param bounds the bounding rectangle to which to extend the selection
  1858. * @return an area enclosing the selection.
  1859. * @see #getVisualHighlightShape(TextHitInfo, TextHitInfo, Rectangle2D)
  1860. */
  1861. public Shape getLogicalHighlightShape(int firstEndpoint,
  1862. int secondEndpoint,
  1863. Rectangle2D bounds) {
  1864. if (bounds == null) {
  1865. throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getLogicalHighlightShape()");
  1866. }
  1867. ensureCache();
  1868. if (firstEndpoint > secondEndpoint) {
  1869. int t = firstEndpoint;
  1870. firstEndpoint = secondEndpoint;
  1871. secondEndpoint = t;
  1872. }
  1873. if(firstEndpoint < 0 || secondEndpoint > characterCount) {
  1874. throw new IllegalArgumentException("Range is invalid in TextLayout.getLogicalHighlightShape()");
  1875. }
  1876. int[] carets = new int[10]; // would this ever not handle all cases?
  1877. int count = 0;
  1878. if (firstEndpoint < secondEndpoint) {
  1879. int logIndex = firstEndpoint;
  1880. do {
  1881. carets[count++] = hitToCaret(TextHitInfo.leading(logIndex));
  1882. boolean ltr = textLine.isCharLTR(logIndex);
  1883. do {
  1884. logIndex++;
  1885. } while (logIndex < secondEndpoint && textLine.isCharLTR(logIndex) == ltr);
  1886. int hitCh = logIndex;
  1887. carets[count++] = hitToCaret(TextHitInfo.trailing(hitCh - 1));
  1888. if (count == carets.length) {
  1889. int[] temp = new int[carets.length + 10];
  1890. System.arraycopy(carets, 0, temp, 0, count);
  1891. carets = temp;
  1892. }
  1893. } while (logIndex < secondEndpoint);
  1894. }
  1895. else {
  1896. count = 2;
  1897. carets[0] = carets[1] = hitToCaret(TextHitInfo.leading(firstEndpoint));
  1898. }
  1899. // now create paths for pairs of carets
  1900. GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
  1901. for (int i = 0; i < count; i += 2) {
  1902. result.append(caretBoundingShape(carets[i], carets[i+1], bounds),
  1903. false);
  1904. }
  1905. if ((textLine.isDirectionLTR() && firstEndpoint == 0) || (!textLine.isDirectionLTR() &&
  1906. secondEndpoint == characterCount)) {
  1907. result.append(leftShape(bounds), false);
  1908. }
  1909. if ((textLine.isDirectionLTR() && secondEndpoint == characterCount) ||
  1910. (!textLine.isDirectionLTR() && firstEndpoint == 0)) {
  1911. result.append(rightShape(bounds), false);
  1912. }
  1913. return result;
  1914. }
  1915. /**
  1916. * Returns a <code>Shape</code> enclosing the logical selection in the
  1917. * specified range, extended to the natural bounds of this
  1918. * <code>TextLayout</code>. This method is a convenience overload of
  1919. * <code>getLogicalHighlightShape</code> that uses the natural bounds of
  1920. * this <code>TextLayout</code>.
  1921. * @param firstEndpoint an endpoint in the range of characters to select
  1922. * @param secondEndpoint the other endpoint of the range of characters
  1923. * to select. Can be less than <code>firstEndpoint</code>. The range
  1924. * includes the character at min(firstEndpoint, secondEndpoint), but
  1925. * excludes max(firstEndpoint, secondEndpoint).
  1926. * @return a <code>Shape</code> enclosing the selection.
  1927. */
  1928. public Shape getLogicalHighlightShape(int firstEndpoint, int secondEndpoint) {
  1929. return getLogicalHighlightShape(firstEndpoint, secondEndpoint, getNaturalBounds());
  1930. }
  1931. /**
  1932. * Returns the black box bounds of the characters in the specified range.
  1933. * The black box bounds is an area consisting of the union of the bounding
  1934. * boxes of all the glyphs corresponding to the characters between start
  1935. * and limit. This path may be disjoint.
  1936. * @param firstEndpoint one end of the character range
  1937. * @param secondEndpoint the other end of the character range. Can be
  1938. * less than <code>firstEndpoint</code>.
  1939. * @return a <code>path</code> enclosing the black box bounds.
  1940. */
  1941. public Shape getBlackBoxBounds(int firstEndpoint, int secondEndpoint) {
  1942. ensureCache();
  1943. if (firstEndpoint > secondEndpoint) {
  1944. int t = firstEndpoint;
  1945. firstEndpoint = secondEndpoint;
  1946. secondEndpoint = t;
  1947. }
  1948. if (firstEndpoint < 0 || secondEndpoint > characterCount) {
  1949. throw new IllegalArgumentException("Invalid range passed to TextLayout.getBlackBoxBounds()");
  1950. }
  1951. /*
  1952. * return an area that consists of the bounding boxes of all the
  1953. * characters from firstEndpoint to limit
  1954. */
  1955. GeneralPath result = new GeneralPath(GeneralPath.WIND_NON_ZERO);
  1956. if (firstEndpoint < characterCount) {
  1957. for (int logIndex = firstEndpoint;
  1958. logIndex < secondEndpoint;
  1959. logIndex++) {
  1960. if (!textLine.isCharWhitespace(logIndex)) {
  1961. Rectangle2D r = textLine.getCharBounds(logIndex);
  1962. result.append(r, false);
  1963. }
  1964. }
  1965. }
  1966. if (dx != 0 || dy != 0) {
  1967. AffineTransform translate = new AffineTransform();
  1968. translate.setToTranslation(dx, dy);
  1969. result = (GeneralPath) result.createTransformedShape(translate);
  1970. }
  1971. //return new Highlight(result, false);
  1972. return result;
  1973. }
  1974. /**
  1975. * Returns the distance from the point (x, y) to the caret along
  1976. * the line direction defined in <code>caretInfo</code>. Distance is
  1977. * negative if the point is to the left of the caret on a horizontal
  1978. * line, or above the caret on a vertical line.
  1979. * Utility for use by hitTestChar.
  1980. */
  1981. private float caretToPointDistance(float[] caretInfo, float x, float y) {
  1982. // distanceOffBaseline is negative if you're 'above' baseline
  1983. float lineDistance = isVerticalLine? y : x;
  1984. float distanceOffBaseline = isVerticalLine? -x : y;
  1985. return lineDistance - caretInfo[0] +
  1986. (distanceOffBaseline*caretInfo[1]);
  1987. }
  1988. /**
  1989. * Returns a <code>TextHitInfo</code> corresponding to the
  1990. * specified point.
  1991. * Coordinates outside the bounds of the <code>TextLayout</code>
  1992. * map to hits on the leading edge of the first logical character,
  1993. * or the trailing edge of the last logical character, as appropriate,
  1994. * regardless of the position of that character in the line. Only the
  1995. * direction along the baseline is used to make this evaluation.
  1996. * @param x the x offset from the origin of this
  1997. * <code>TextLayout</code>
  1998. * @param y the y offset from the origin of this
  1999. * <code>TextLayout</code>
  2000. * @param bounds the bounds of the <code>TextLayout</code>
  2001. * @return a hit describing the character and edge (leading or trailing)
  2002. * under the specified point.
  2003. */
  2004. public TextHitInfo hitTestChar(float x, float y, Rectangle2D bounds) {
  2005. ensureCache();
  2006. int hitLB, hitUB;
  2007. float[] caretInfo = new float[2];
  2008. hitLB = 0;
  2009. caretInfo = getCaretInfo(hitLB, bounds, caretInfo);
  2010. if (caretToPointDistance(caretInfo, x, y) < 0) {
  2011. return textLine.isDirectionLTR()? TextHitInfo.trailing(-1) :
  2012. TextHitInfo.leading(characterCount);
  2013. }
  2014. hitUB = characterCount;
  2015. caretInfo = getCaretInfo(hitUB, bounds, caretInfo);
  2016. if (caretToPointDistance(caretInfo, x, y) >= 0) {
  2017. return textLine.isDirectionLTR()? TextHitInfo.leading(characterCount) :
  2018. TextHitInfo.trailing(-1);
  2019. }
  2020. while (true) {
  2021. // if there are no valid caret positions between
  2022. // hitLB and hitUB then exit this loop; otherwise
  2023. // set test to a valid caret position in the
  2024. // interval (hitLB, hitUB)
  2025. if (hitLB + 1 == hitUB)
  2026. break;
  2027. int test = (hitLB + hitUB) / 2;
  2028. while(!caretIsValid(test)) {
  2029. test++;
  2030. }
  2031. if (test == hitUB) {
  2032. // If we're here then there were no valid caret
  2033. // positions between the halfway point and the
  2034. // end of the test region. Reset test and back
  2035. // up to a valid caret position.
  2036. test = (hitLB + hitUB) / 2;
  2037. do {
  2038. --test;
  2039. } while(!caretIsValid(test));
  2040. if (test == hitLB)
  2041. break;
  2042. }
  2043. caretInfo = getCaretInfo(test, bounds, caretInfo);
  2044. float caretDist = caretToPointDistance(caretInfo, x, y);
  2045. if (caretDist == 0) {
  2046. // return a hit on the left side of the glyph at test
  2047. // test is a valid position, since it is less than characterCount
  2048. int charIndex = textLine.visualToLogical(test);
  2049. boolean leading = textLine.isCharLTR(charIndex);
  2050. return leading? TextHitInfo.leading(charIndex) :
  2051. TextHitInfo.trailing(charIndex);
  2052. }
  2053. else if (caretDist < 0) {
  2054. hitUB = test;
  2055. }
  2056. else {
  2057. hitLB = test;
  2058. }
  2059. }
  2060. // now hit char is either to the right of hitLB
  2061. // or left of hitUB
  2062. // make caretInfo be center of glyph:
  2063. int logIndex = textLine.visualToLogical(hitLB);
  2064. float hitAdvance = textLine.getCharLinePosition(logIndex) +
  2065. (isVerticalLine? -dy : -dx);
  2066. // this positions hitAdvance at the "center" of the character(s)
  2067. // between hitLB and hitUB
  2068. {
  2069. int tempLogIndex = textLine.visualToLogical(hitUB - 1);
  2070. if (hitUB - hitLB > 1) {
  2071. float tempPos = textLine.getCharLinePosition(tempLogIndex);
  2072. hitAdvance += (tempPos - hitAdvance) / 2;
  2073. }
  2074. hitAdvance += textLine.getCharAdvance(tempLogIndex) / 2;
  2075. }
  2076. caretInfo[0] = hitAdvance;
  2077. caretInfo[1] = textLine.getCharAngle(logIndex);
  2078. if (caretInfo[1] != 0) {
  2079. caretInfo[0] += caretInfo[1] * (isVerticalLine?
  2080. textLine.getCharXPosition(logIndex) :
  2081. textLine.getCharYPosition(logIndex));
  2082. }
  2083. float centerDist = caretToPointDistance(caretInfo, x, y);
  2084. TextHitInfo rval;
  2085. if (centerDist < 0) {
  2086. rval = textLine.isCharLTR(logIndex)?
  2087. TextHitInfo.leading(logIndex) :
  2088. TextHitInfo.trailing(logIndex);
  2089. }
  2090. else {
  2091. logIndex = textLine.visualToLogical(hitUB - 1);
  2092. boolean leading = !textLine.isCharLTR(logIndex);
  2093. rval = leading? TextHitInfo.leading(logIndex) :
  2094. TextHitInfo.trailing(logIndex);
  2095. }
  2096. return rval;
  2097. }
  2098. /**
  2099. * Returns a <code>TextHitInfo</code> corresponding to the
  2100. * specified point. This method is a convenience overload of
  2101. * <code>hitTestChar</code> that uses the natural bounds of this
  2102. * <code>TextLayout</code>.
  2103. * @param x the x offset from the origin of this <code>TextLayout</code>
  2104. * @param y the y offset from the origin of this
  2105. * <code>TextLayout</code>
  2106. * @return a hit describing the character and edge (leading or trailing)
  2107. * under the specified point.
  2108. */
  2109. public TextHitInfo hitTestChar(float x, float y) {
  2110. return hitTestChar(x, y, getNaturalBounds());
  2111. }
  2112. /**
  2113. * Returns the hash code of this <code>TextLayout</code>.
  2114. * @return the hash code of this <code>TextLayout</code>.
  2115. */
  2116. public int hashCode() {
  2117. if (hashCodeCache == 0) {
  2118. hashCodeCache = textLine.hashCode();
  2119. }
  2120. return hashCodeCache;
  2121. }
  2122. /**
  2123. * Returns <code>true</code> if the specified <code>Object</code> is a
  2124. * <code>TextLayout</code> object and if the specified <code>Object</code>
  2125. * equals this <code>TextLayout</code>.
  2126. * @param obj an <code>Object</code> to test for equality
  2127. * @return <code>true</code> if the specified <code>Object</code>
  2128. * equals this <code>TextLayout</code> <code>false</code>
  2129. * otherwise.
  2130. */
  2131. public boolean equals(Object obj) {
  2132. return (obj instanceof TextLayout) && equals((TextLayout)obj);
  2133. }
  2134. /**
  2135. * Returns <code>true</code> if the two layouts are equal.
  2136. * Two layouts are equal if they contain equal glyphvectors in the same order.
  2137. * @param rhs the <code>TextLayout</code> to compare to this
  2138. * <code>TextLayout</code>
  2139. * @return <code>true</code> if the specified <code>TextLayout</code>
  2140. * equals this <code>TextLayout</code>.
  2141. *
  2142. */
  2143. public boolean equals(TextLayout rhs) {
  2144. if (rhs == null) {
  2145. return false;
  2146. }
  2147. if (rhs == this) {
  2148. return true;
  2149. }
  2150. return textLine.equals(rhs.textLine);
  2151. }
  2152. /**
  2153. * Returns debugging information for this <code>TextLayout</code>.
  2154. * @return the <code>textLine</code> of this <code>TextLayout</code>
  2155. * as a <code>String</code>.
  2156. */
  2157. public String toString() {
  2158. return textLine.toString();
  2159. }
  2160. /**
  2161. * Renders this <code>TextLayout</code> at the specified location in
  2162. * the specified {@link java.awt.Graphics2D Graphics2D} context.
  2163. * The origin of the layout is placed at x, y. Rendering may touch
  2164. * any point within <code>getBounds()</code> of this position. This
  2165. * leaves the <code>g2</code> unchanged.
  2166. * @param g2 the <code>Graphics2D</code> context into which to render
  2167. * the layout
  2168. * @param x, y the coordinates of the origin of this
  2169. * <code>TextLayout</code>
  2170. * @see #getBounds()
  2171. */
  2172. public void draw(Graphics2D g2, float x, float y) {
  2173. if (g2 == null) {
  2174. throw new IllegalArgumentException("Null Graphics2D passed to TextLayout.draw()");
  2175. }
  2176. textLine.draw(g2, x - dx, y - dy);
  2177. }
  2178. /**
  2179. * Package-only method for testing ONLY. Please don't abuse.
  2180. */
  2181. TextLine getTextLineForTesting() {
  2182. return textLine;
  2183. }
  2184. /**
  2185. *
  2186. * Return the index of the first character with a different baseline from the
  2187. * character at start, or limit if all characters between start and limit have
  2188. * the same baseline.
  2189. */
  2190. private static int sameBaselineUpTo(Font font, char[] text,
  2191. int start, int limit) {
  2192. byte bl = font.getBaselineFor(text[start++]);
  2193. while (start < limit && font.getBaselineFor(text[start]) == bl) {
  2194. ++start;
  2195. }
  2196. return start;
  2197. }
  2198. static byte getBaselineFromGraphic(GraphicAttribute graphic) {
  2199. byte alignment = (byte) graphic.getAlignment();
  2200. if (alignment == GraphicAttribute.BOTTOM_ALIGNMENT ||
  2201. alignment == GraphicAttribute.TOP_ALIGNMENT) {
  2202. return (byte)GraphicAttribute.ROMAN_BASELINE;
  2203. }
  2204. else {
  2205. return alignment;
  2206. }
  2207. }
  2208. /**
  2209. * Returns a <code>Shape</code> representing the outline of this
  2210. * <code>TextLayout</code>.
  2211. * @param tx an optional {@link AffineTransform} to apply to the
  2212. * outline of this <code>TextLayout</code>.
  2213. * @return a <code>Shape</code> that is the outline of this
  2214. * <code>TextLayout</code>.
  2215. */
  2216. public Shape getOutline(AffineTransform tx) {
  2217. return textLine.getOutline(tx);
  2218. }
  2219. }