1. /*
  2. * @(#)PlainView.java 1.59 01/11/29
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text;
  8. import java.util.Vector;
  9. import java.util.Properties;
  10. import java.awt.*;
  11. import javax.swing.event.*;
  12. /**
  13. * Implements View interface for a simple multi-line text view
  14. * that has text in one font and color. The view represents each
  15. * child element as a line of text.
  16. *
  17. * @author Timothy Prinzing
  18. * @version 1.59 11/29/01
  19. * @see View
  20. */
  21. public class PlainView extends View implements TabExpander {
  22. /**
  23. * Constructs a new PlainView wrapped on an element.
  24. *
  25. * @param elem the element
  26. */
  27. public PlainView(Element elem) {
  28. super(elem);
  29. lineBuffer = new Segment();
  30. }
  31. /**
  32. * Returns the tab size set for the document, defaulting to 8.
  33. *
  34. * @return the tab size
  35. */
  36. protected int getTabSize() {
  37. Integer i = (Integer) getDocument().getProperty(PlainDocument.tabSizeAttribute);
  38. int size = (i != null) ? i.intValue() : 8;
  39. return size;
  40. }
  41. /**
  42. * Renders a line of text, suppressing whitespace at the end
  43. * and exanding any tabs. This is implemented to make calls
  44. * to the methods <code>drawUnselectedText</code> and
  45. * <code>drawSelectedText</code> so that the way selected and
  46. * unselected text are rendered can be customized.
  47. *
  48. * @param lineIndex the line to draw >= 0
  49. * @param g the graphics context
  50. * @param x the starting X position >= 0
  51. * @param y the starting Y position >= 0
  52. * @see #drawUnselectedText
  53. * @see #drawSelectedText
  54. */
  55. protected void drawLine(int lineIndex, Graphics g, int x, int y) {
  56. Element line = getElement().getElement(lineIndex);
  57. Element elem;
  58. try {
  59. if (line.isLeaf()) {
  60. drawElement(line, g, x, y);
  61. } else {
  62. // this line contains the composed text.
  63. int count = line.getElementCount();
  64. for(int i = 0; i < count; i++) {
  65. elem = line.getElement(i);
  66. x = drawElement(elem, g, x, y);
  67. }
  68. }
  69. } catch (BadLocationException e) {
  70. throw new StateInvariantError("Can't render line: " + lineIndex);
  71. }
  72. }
  73. private int drawElement(Element elem, Graphics g, int x, int y) throws BadLocationException {
  74. int p0 = elem.getStartOffset();
  75. int p1 = elem.getEndOffset();
  76. p1 = Math.min(getDocument().getLength(), p1);
  77. AttributeSet attr = elem.getAttributes();
  78. if (Utilities.isComposedTextAttributeDefined(attr)) {
  79. g.setColor(unselected);
  80. x = Utilities.drawComposedText(attr, g, x, y,
  81. p0-elem.getStartOffset(),
  82. p1-elem.getStartOffset());
  83. } else {
  84. if (sel0 == sel1) {
  85. // no selection
  86. x = drawUnselectedText(g, x, y, p0, p1);
  87. } else if ((p0 >= sel0 && p0 <= sel1) && (p1 >= sel0 && p1 <= sel1)) {
  88. x = drawSelectedText(g, x, y, p0, p1);
  89. } else if (sel0 >= p0 && sel0 <= p1) {
  90. if (sel1 >= p0 && sel1 <= p1) {
  91. x = drawUnselectedText(g, x, y, p0, sel0);
  92. x = drawSelectedText(g, x, y, sel0, sel1);
  93. x = drawUnselectedText(g, x, y, sel1, p1);
  94. } else {
  95. x = drawUnselectedText(g, x, y, p0, sel0);
  96. x = drawSelectedText(g, x, y, sel0, p1);
  97. }
  98. } else if (sel1 >= p0 && sel1 <= p1) {
  99. x = drawSelectedText(g, x, y, p0, sel1);
  100. x = drawUnselectedText(g, x, y, sel1, p1);
  101. } else {
  102. x = drawUnselectedText(g, x, y, p0, p1);
  103. }
  104. }
  105. return x;
  106. }
  107. /**
  108. * Renders the given range in the model as normal unselected
  109. * text. Uses the foreground or disabled color to render the text.
  110. *
  111. * @param g the graphics context
  112. * @param x the starting X coordinate >= 0
  113. * @param y the starting Y coordinate >= 0
  114. * @param p0 the beginning position in the model >= 0
  115. * @param p1 the ending position in the model >= 0
  116. * @returns the X location of the end of the range >= 0
  117. * @exception BadLocationException if the range is invalid
  118. */
  119. protected int drawUnselectedText(Graphics g, int x, int y,
  120. int p0, int p1) throws BadLocationException {
  121. g.setColor(unselected);
  122. Document doc = getDocument();
  123. doc.getText(p0, p1 - p0, lineBuffer);
  124. return Utilities.drawTabbedText(lineBuffer, x, y, g, this, p0);
  125. }
  126. /**
  127. * Renders the given range in the model as selected text. This
  128. * is implemented to render the text in the color specified in
  129. * the hosting component. It assumes the highlighter will render
  130. * the selected background.
  131. *
  132. * @param g the graphics context
  133. * @param x the starting X coordinate >= 0
  134. * @param y the starting Y coordinate >= 0
  135. * @param p0 the beginning position in the model >= 0
  136. * @param p1 the ending position in the model >= 0
  137. * @returns the location of the end of the range.
  138. * @exception BadLocationException if the range is invalid
  139. */
  140. protected int drawSelectedText(Graphics g, int x,
  141. int y, int p0, int p1) throws BadLocationException {
  142. g.setColor(selected);
  143. Document doc = getDocument();
  144. doc.getText(p0, p1 - p0, lineBuffer);
  145. return Utilities.drawTabbedText(lineBuffer, x, y, g, this, p0);
  146. }
  147. /**
  148. * Gives access to a buffer that can be used to fetch
  149. * text from the associated document.
  150. *
  151. * @returns the buffer
  152. */
  153. protected final Segment getLineBuffer() {
  154. return lineBuffer;
  155. }
  156. /**
  157. * Checks to see if the font metrics and longest line
  158. * are up-to-date.
  159. */
  160. final void updateMetrics() {
  161. Component host = getContainer();
  162. Font f = host.getFont();
  163. if (font != f) {
  164. // The font changed, we need to recalculate the
  165. // longest line.
  166. calculateLongestLine();
  167. tabSize = getTabSize() * metrics.charWidth('m');
  168. }
  169. }
  170. // ---- View methods ----------------------------------------------------
  171. /**
  172. * Determines the preferred span for this view along an
  173. * axis.
  174. *
  175. * @param axis may be either View.X_AXIS or View.Y_AXIS
  176. * @returns the span the view would like to be rendered into >= 0.
  177. * Typically the view is told to render into the span
  178. * that is returned, although there is no guarantee.
  179. * The parent may choose to resize or break the view.
  180. * @exception IllegalArgumentException for an invalid axis
  181. */
  182. public float getPreferredSpan(int axis) {
  183. updateMetrics();
  184. switch (axis) {
  185. case View.X_AXIS:
  186. return getLineWidth(longLine);
  187. case View.Y_AXIS:
  188. return getElement().getElementCount() * metrics.getHeight();
  189. default:
  190. throw new IllegalArgumentException("Invalid axis: " + axis);
  191. }
  192. }
  193. /**
  194. * Renders using the given rendering surface and area on that surface.
  195. * The view may need to do layout and create child views to enable
  196. * itself to render into the given allocation.
  197. *
  198. * @param g the rendering surface to use
  199. * @param a the allocated region to render into
  200. *
  201. * @see View#paint
  202. */
  203. public void paint(Graphics g, Shape a) {
  204. Shape originalA = a;
  205. a = adjustPaintRegion(a);
  206. Rectangle alloc = (Rectangle) a;
  207. tabBase = alloc.x;
  208. JTextComponent host = (JTextComponent) getContainer();
  209. g.setFont(host.getFont());
  210. sel0 = host.getSelectionStart();
  211. sel1 = host.getSelectionEnd();
  212. unselected = (host.isEnabled()) ?
  213. host.getForeground() : host.getDisabledTextColor();
  214. Caret c = host.getCaret();
  215. selected = c.isSelectionVisible() ? host.getSelectedTextColor() : unselected;
  216. updateMetrics();
  217. // If the lines are clipped then we don't expend the effort to
  218. // try and paint them. Since all of the lines are the same height
  219. // with this object, determination of what lines need to be repainted
  220. // is quick.
  221. Rectangle clip = g.getClipBounds();
  222. int fontHeight = metrics.getHeight();
  223. int heightBelow = (alloc.y + alloc.height) - (clip.y + clip.height);
  224. int linesBelow = Math.max(0, heightBelow / fontHeight);
  225. int heightAbove = clip.y - alloc.y;
  226. int linesAbove = Math.max(0, heightAbove / fontHeight);
  227. int linesTotal = alloc.height / fontHeight;
  228. if (alloc.height % fontHeight != 0) {
  229. linesTotal++;
  230. }
  231. // update the visible lines
  232. Rectangle lineArea = lineToRect(a, linesAbove);
  233. int y = lineArea.y + metrics.getAscent();
  234. int x = lineArea.x;
  235. Element map = getElement();
  236. int lineCount = map.getElementCount();
  237. int endLine = Math.min(lineCount, linesTotal - linesBelow);
  238. lineCount--;
  239. Highlighter h = host.getHighlighter();
  240. LayeredHighlighter dh = (h instanceof LayeredHighlighter) ?
  241. (LayeredHighlighter)h : null;
  242. for (int line = linesAbove; line < endLine; line++) {
  243. if (dh != null) {
  244. Element lineElement = map.getElement(line);
  245. if (line == lineCount) {
  246. dh.paintLayeredHighlights(g, lineElement.getStartOffset(),
  247. lineElement.getEndOffset(),
  248. originalA, host, this);
  249. }
  250. else {
  251. dh.paintLayeredHighlights(g, lineElement.getStartOffset(),
  252. lineElement.getEndOffset() - 1,
  253. originalA, host, this);
  254. }
  255. }
  256. drawLine(line, g, x, y);
  257. y += fontHeight;
  258. }
  259. }
  260. /**
  261. * Should return a shape ideal for painting based on the passed in
  262. * Shape <code>a</code>. This is useful if painting in a different
  263. * region. The default implementation returns <code>a</code>.
  264. */
  265. Shape adjustPaintRegion(Shape a) {
  266. return a;
  267. }
  268. /**
  269. * Signals that the desired span has changed.
  270. *
  271. * @param child the child view
  272. * @param width true if the width preference has changed
  273. * @param height true if the height preference has changed
  274. * @see javax.swing.JComponent#revalidate
  275. */
  276. public void preferenceChanged(View child, boolean width, boolean height) {
  277. getDocument().putProperty(PlainDocument.lineLimitAttribute, null);
  278. super.preferenceChanged(child, width, height);
  279. }
  280. /**
  281. * Provides a mapping from the document model coordinate space
  282. * to the coordinate space of the view mapped to it.
  283. *
  284. * @param pos the position to convert >= 0
  285. * @param a the allocated region to render into
  286. * @return the bounding box of the given position
  287. * @exception BadLocationException if the given position does not
  288. * represent a valid location in the associated document
  289. * @see View#modelToView
  290. */
  291. public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
  292. // line coordinates
  293. Document doc = getDocument();
  294. Element map = getElement();
  295. int lineIndex = map.getElementIndex(pos);
  296. Rectangle lineArea = lineToRect(a, lineIndex);
  297. // determine span from the start of the line
  298. tabBase = lineArea.x;
  299. Element line = map.getElement(lineIndex);
  300. int p0 = line.getStartOffset();
  301. doc.getText(p0, pos - p0, lineBuffer);
  302. int xOffs = Utilities.getTabbedTextWidth(lineBuffer, metrics, tabBase, this, p0);
  303. // fill in the results and return
  304. lineArea.x += xOffs;
  305. lineArea.width = 1;
  306. lineArea.height = metrics.getHeight();
  307. return lineArea;
  308. }
  309. /**
  310. * Provides a mapping from the view coordinate space to the logical
  311. * coordinate space of the model.
  312. *
  313. * @param fx the X coordinate >= 0
  314. * @param fy the Y coordinate >= 0
  315. * @param a the allocated region to render into
  316. * @return the location within the model that best represents the
  317. * given point in the view >= 0
  318. * @see View#viewToModel
  319. */
  320. public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) {
  321. // PENDING(prinz) properly calculate bias
  322. bias[0] = Position.Bias.Forward;
  323. Rectangle alloc = a.getBounds();
  324. Document doc = getDocument();
  325. int x = (int) fx;
  326. int y = (int) fy;
  327. if (y < alloc.y) {
  328. // above the area covered by this icon, so the the position
  329. // is assumed to be the start of the coverage for this view.
  330. return getStartOffset();
  331. } else if (y > alloc.y + alloc.height) {
  332. // below the area covered by this icon, so the the position
  333. // is assumed to be the end of the coverage for this view.
  334. return getEndOffset() - 1;
  335. } else {
  336. // positioned within the coverage of this view vertically,
  337. // so we figure out which line the point corresponds to.
  338. // if the line is greater than the number of lines contained, then
  339. // simply use the last line as it represents the last possible place
  340. // we can position to.
  341. Element map = doc.getDefaultRootElement();
  342. int lineIndex = Math.abs((y - alloc.y) / metrics.getHeight() );
  343. if (lineIndex >= map.getElementCount()) {
  344. return getEndOffset() - 1;
  345. }
  346. Element line = map.getElement(lineIndex);
  347. if (x < alloc.x) {
  348. // point is to the left of the line
  349. return line.getStartOffset();
  350. } else if (x > alloc.x + alloc.width) {
  351. // point is to the right of the line
  352. return line.getEndOffset() - 1;
  353. } else {
  354. // Determine the offset into the text
  355. try {
  356. int p0 = line.getStartOffset();
  357. int p1 = line.getEndOffset() - 1;
  358. doc.getText(p0, p1 - p0, lineBuffer);
  359. tabBase = alloc.x;
  360. int offs = p0 + Utilities.getTabbedTextOffset(lineBuffer, metrics,
  361. tabBase, x, this, p0);
  362. return offs;
  363. } catch (BadLocationException e) {
  364. // should not happen
  365. return -1;
  366. }
  367. }
  368. }
  369. }
  370. /**
  371. * Gives notification that something was inserted into the document
  372. * in a location that this view is responsible for.
  373. *
  374. * @param changes the change information from the associated document
  375. * @param a the current allocation of the view
  376. * @param f the factory to use to rebuild if the view has children
  377. * @see View#insertUpdate
  378. */
  379. public void insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
  380. updateDamage(changes, a, f);
  381. }
  382. /**
  383. * Gives notification that something was removed from the document
  384. * in a location that this view is responsible for.
  385. *
  386. * @param changes the change information from the associated document
  387. * @param a the current allocation of the view
  388. * @param f the factory to use to rebuild if the view has children
  389. * @see View#removeUpdate
  390. */
  391. public void removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
  392. updateDamage(changes, a, f);
  393. }
  394. /**
  395. * Gives notification from the document that attributes were changed
  396. * in a location that this view is responsible for.
  397. *
  398. * @param changes the change information from the associated document
  399. * @param a the current allocation of the view
  400. * @param f the factory to use to rebuild if the view has children
  401. * @see View#changedUpdate
  402. */
  403. public void changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
  404. updateDamage(changes, a, f);
  405. }
  406. // --- TabExpander methods ------------------------------------------
  407. /**
  408. * Returns the next tab stop position after a given reference position.
  409. * This implementation does not support things like centering so it
  410. * ignores the tabOffset argument.
  411. *
  412. * @param x the current position >= 0
  413. * @param tabOffset the position within the text stream
  414. * that the tab occurred at >= 0.
  415. * @return the tab stop, measured in points >= 0
  416. */
  417. public float nextTabStop(float x, int tabOffset) {
  418. if (tabSize == 0) {
  419. return x;
  420. }
  421. int ntabs = (((int) x) - tabBase) / tabSize;
  422. return tabBase + ((ntabs + 1) * tabSize);
  423. }
  424. // --- local methods ------------------------------------------------
  425. /*
  426. * We can damage the line that begins the range to cover
  427. * the case when the insert/remove is only on one line.
  428. * If lines are added or removed we will damage the whole
  429. * view. The longest line is checked to see if it has
  430. * changed.
  431. */
  432. void updateDamage(DocumentEvent changes, Shape a, ViewFactory f) {
  433. Component host = getContainer();
  434. if (host.isShowing()) {
  435. updateMetrics();
  436. Element elem = getElement();
  437. DocumentEvent.ElementChange ec = changes.getChange(elem);
  438. Element[] added = (ec != null) ? ec.getChildrenAdded() : null;
  439. Element[] removed = (ec != null) ? ec.getChildrenRemoved() : null;
  440. if (((added != null) && (added.length > 0)) ||
  441. ((removed != null) && (removed.length > 0))) {
  442. // lines were added or removed...
  443. if (added != null) {
  444. int currWide = getLineWidth(longLine);
  445. for (int i = 0; i < added.length; i++) {
  446. int w = getLineWidth(added[i]);
  447. if (w > currWide) {
  448. currWide = w;
  449. longLine = added[i];
  450. }
  451. }
  452. }
  453. if (removed != null) {
  454. for (int i = 0; i < removed.length; i++) {
  455. if (removed[i] == longLine) {
  456. calculateLongestLine();
  457. break;
  458. }
  459. }
  460. }
  461. preferenceChanged(null, true, true);
  462. host.repaint();
  463. } else {
  464. Element map = getElement();
  465. int line = map.getElementIndex(changes.getOffset());
  466. damageLineRange(line, line, a, host);
  467. if (changes.getType() == DocumentEvent.EventType.INSERT) {
  468. // check to see if the line is longer than current
  469. // longest line.
  470. int w = getLineWidth(longLine);
  471. Element e = map.getElement(line);
  472. if (e == longLine) {
  473. preferenceChanged(null, true, false);
  474. } else if (getLineWidth(e) > w) {
  475. longLine = e;
  476. preferenceChanged(null, true, false);
  477. }
  478. } else if (changes.getType() == DocumentEvent.EventType.REMOVE) {
  479. if (map.getElement(line) == longLine) {
  480. // removed from longest line... recalc
  481. calculateLongestLine();
  482. preferenceChanged(null, true, false);
  483. }
  484. }
  485. }
  486. }
  487. }
  488. private void damageLineRange(int line0, int line1, Shape a, Component host) {
  489. if (a != null) {
  490. Rectangle area0 = lineToRect(a, line0);
  491. Rectangle area1 = lineToRect(a, line1);
  492. if ((area0 != null) && (area1 != null)) {
  493. Rectangle damage = area0.union(area1);
  494. host.repaint(damage.x, damage.y, damage.width, damage.height);
  495. } else {
  496. host.repaint();
  497. }
  498. }
  499. }
  500. private Rectangle lineToRect(Shape a, int line) {
  501. Rectangle r = null;
  502. if (metrics != null) {
  503. Rectangle alloc = a.getBounds();
  504. r = new Rectangle(alloc.x, alloc.y + (line * metrics.getHeight()),
  505. alloc.width, metrics.getHeight());
  506. }
  507. return r;
  508. }
  509. /**
  510. * Iterate over the lines represented by the child elements
  511. * of the element this view represents, looking for the line
  512. * that is the longest. The <em>longLine</em> variable is updated to
  513. * represent the longest line contained. The <em>font</em> variable
  514. * is updated to indicate the font used to calculate the
  515. * longest line.
  516. */
  517. private void calculateLongestLine() {
  518. Component c = getContainer();
  519. font = c.getFont();
  520. metrics = c.getFontMetrics(font);
  521. Document doc = getDocument();
  522. Element lines = getElement();
  523. int n = lines.getElementCount();
  524. int maxWidth = -1;
  525. for (int i = 0; i < n; i++) {
  526. Element line = lines.getElement(i);
  527. int w = getLineWidth(line);
  528. if (w > maxWidth) {
  529. maxWidth = w;
  530. longLine = line;
  531. }
  532. }
  533. }
  534. /**
  535. * Calculate the width of the line represented by
  536. * the given element. It is assumed that the font
  537. * and font metrics are up-to-date.
  538. */
  539. private int getLineWidth(Element line) {
  540. int p0 = line.getStartOffset();
  541. int p1 = line.getEndOffset();
  542. int w;
  543. try {
  544. line.getDocument().getText(p0, p1 - p0, lineBuffer);
  545. w = Utilities.getTabbedTextWidth(lineBuffer, metrics, tabBase,
  546. this, p0);
  547. } catch (BadLocationException ble) {
  548. w = 0;
  549. }
  550. return w;
  551. }
  552. // --- member variables -----------------------------------------------
  553. /**
  554. * Font metrics for the currrent font.
  555. */
  556. protected FontMetrics metrics;
  557. /**
  558. * The current longest line. This is used to calculate
  559. * the preferred width of the view. Since the calculation
  560. * is potentially expensive we try to avoid it by stashing
  561. * which line is currently the longest.
  562. */
  563. Element longLine;
  564. /**
  565. * Font used to calculate the longest line... if this
  566. * changes we need to recalculate the longest line
  567. */
  568. Font font;
  569. Segment lineBuffer;
  570. int tabSize;
  571. int tabBase;
  572. int sel0;
  573. int sel1;
  574. Color unselected;
  575. Color selected;
  576. }