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