1 /*
   2  * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package javax.swing.text;
  26 
  27 import java.awt.*;
  28 import java.lang.ref.SoftReference;
  29 import javax.swing.event.*;
  30 
  31 /**
  32  * View of plain text (text with only one font and color)
  33  * that does line-wrapping.  This view expects that its
  34  * associated element has child elements that represent
  35  * the lines it should be wrapping.  It is implemented
  36  * as a vertical box that contains logical line views.
  37  * The logical line views are nested classes that render
  38  * the logical line as multiple physical line if the logical
  39  * line is too wide to fit within the allocation.  The
  40  * line views draw upon the outer class for its state
  41  * to reduce their memory requirements.
  42  * <p>
  43  * The line views do all of their rendering through the
  44  * <code>drawLine</code> method which in turn does all of
  45  * its rendering through the <code>drawSelectedText</code>
  46  * and <code>drawUnselectedText</code> methods.  This
  47  * enables subclasses to easily specialize the rendering
  48  * without concern for the layout aspects.
  49  *
  50  * @author  Timothy Prinzing
  51  * @see     View
  52  */
  53 public class WrappedPlainView extends BoxView implements TabExpander {
  54 
  55     /**
  56      * Creates a new WrappedPlainView.  Lines will be wrapped
  57      * on character boundaries.
  58      *
  59      * @param elem the element underlying the view
  60      */
  61     public WrappedPlainView(Element elem) {
  62         this(elem, false);
  63     }
  64 
  65     /**
  66      * Creates a new WrappedPlainView.  Lines can be wrapped on
  67      * either character or word boundaries depending upon the
  68      * setting of the wordWrap parameter.
  69      *
  70      * @param elem the element underlying the view
  71      * @param wordWrap should lines be wrapped on word boundaries?
  72      */
  73     public WrappedPlainView(Element elem, boolean wordWrap) {
  74         super(elem, Y_AXIS);
  75         this.wordWrap = wordWrap;
  76     }
  77 
  78     /**
  79      * Returns the tab size set for the document, defaulting to 8.
  80      *
  81      * @return the tab size
  82      */
  83     protected int getTabSize() {
  84         Integer i = (Integer) getDocument().getProperty(PlainDocument.tabSizeAttribute);
  85         int size = (i != null) ? i.intValue() : 8;
  86         return size;
  87     }
  88 
  89     /**
  90      * Renders a line of text, suppressing whitespace at the end
  91      * and expanding any tabs.  This is implemented to make calls
  92      * to the methods <code>drawUnselectedText</code> and
  93      * <code>drawSelectedText</code> so that the way selected and
  94      * unselected text are rendered can be customized.
  95      *
  96      * @param p0 the starting document location to use >= 0
  97      * @param p1 the ending document location to use >= p1
  98      * @param g the graphics context
  99      * @param x the starting X position >= 0
 100      * @param y the starting Y position >= 0
 101      * @see #drawUnselectedText
 102      * @see #drawSelectedText
 103      */
 104     protected void drawLine(int p0, int p1, Graphics g, int x, int y) {
 105         Element lineMap = getElement();
 106         Element line = lineMap.getElement(lineMap.getElementIndex(p0));
 107         Element elem;
 108 
 109         try {
 110             if (line.isLeaf()) {
 111                  drawText(line, p0, p1, g, x, y);
 112             } else {
 113                 // this line contains the composed text.
 114                 int idx = line.getElementIndex(p0);
 115                 int lastIdx = line.getElementIndex(p1);
 116                 for(; idx <= lastIdx; idx++) {
 117                     elem = line.getElement(idx);
 118                     int start = Math.max(elem.getStartOffset(), p0);
 119                     int end = Math.min(elem.getEndOffset(), p1);
 120                     x = drawText(elem, start, end, g, x, y);
 121                 }
 122             }
 123         } catch (BadLocationException e) {
 124             throw new StateInvariantError("Can't render: " + p0 + "," + p1);
 125         }
 126     }
 127 
 128     private int drawText(Element elem, int p0, int p1, Graphics g, int x, int y) throws BadLocationException {
 129         p1 = Math.min(getDocument().getLength(), p1);
 130         AttributeSet attr = elem.getAttributes();
 131 
 132         if (Utilities.isComposedTextAttributeDefined(attr)) {
 133             g.setColor(unselected);
 134             x = Utilities.drawComposedText(this, attr, g, x, y,
 135                                         p0-elem.getStartOffset(),
 136                                         p1-elem.getStartOffset());
 137         } else {
 138             if (sel0 == sel1 || selected == unselected) {
 139                 // no selection, or it is invisible
 140                 x = drawUnselectedText(g, x, y, p0, p1);
 141             } else if ((p0 >= sel0 && p0 <= sel1) && (p1 >= sel0 && p1 <= sel1)) {
 142                 x = drawSelectedText(g, x, y, p0, p1);
 143             } else if (sel0 >= p0 && sel0 <= p1) {
 144                 if (sel1 >= p0 && sel1 <= p1) {
 145                     x = drawUnselectedText(g, x, y, p0, sel0);
 146                     x = drawSelectedText(g, x, y, sel0, sel1);
 147                     x = drawUnselectedText(g, x, y, sel1, p1);
 148                 } else {
 149                     x = drawUnselectedText(g, x, y, p0, sel0);
 150                     x = drawSelectedText(g, x, y, sel0, p1);
 151                 }
 152             } else if (sel1 >= p0 && sel1 <= p1) {
 153                 x = drawSelectedText(g, x, y, p0, sel1);
 154                 x = drawUnselectedText(g, x, y, sel1, p1);
 155             } else {
 156                 x = drawUnselectedText(g, x, y, p0, p1);
 157             }
 158         }
 159 
 160         return x;
 161     }
 162 
 163     /**
 164      * Renders the given range in the model as normal unselected
 165      * text.
 166      *
 167      * @param g the graphics context
 168      * @param x the starting X coordinate >= 0
 169      * @param y the starting Y coordinate >= 0
 170      * @param p0 the beginning position in the model >= 0
 171      * @param p1 the ending position in the model >= p0
 172      * @return the X location of the end of the range >= 0
 173      * @exception BadLocationException if the range is invalid
 174      */
 175     protected int drawUnselectedText(Graphics g, int x, int y,
 176                                      int p0, int p1) throws BadLocationException {
 177         g.setColor(unselected);
 178         Document doc = getDocument();
 179         Segment segment = SegmentCache.getSharedSegment();
 180         doc.getText(p0, p1 - p0, segment);
 181         int ret = Utilities.drawTabbedText(this, segment, x, y, g, this, p0);
 182         SegmentCache.releaseSharedSegment(segment);
 183         return ret;
 184     }
 185 
 186     /**
 187      * Renders the given range in the model as selected text.  This
 188      * is implemented to render the text in the color specified in
 189      * the hosting component.  It assumes the highlighter will render
 190      * the selected background.
 191      *
 192      * @param g the graphics context
 193      * @param x the starting X coordinate >= 0
 194      * @param y the starting Y coordinate >= 0
 195      * @param p0 the beginning position in the model >= 0
 196      * @param p1 the ending position in the model >= p0
 197      * @return the location of the end of the range.
 198      * @exception BadLocationException if the range is invalid
 199      */
 200     protected int drawSelectedText(Graphics g, int x,
 201                                    int y, int p0, int p1) throws BadLocationException {
 202         g.setColor(selected);
 203         Document doc = getDocument();
 204         Segment segment = SegmentCache.getSharedSegment();
 205         doc.getText(p0, p1 - p0, segment);
 206         int ret = Utilities.drawTabbedText(this, segment, x, y, g, this, p0);
 207         SegmentCache.releaseSharedSegment(segment);
 208         return ret;
 209     }
 210 
 211     /**
 212      * Gives access to a buffer that can be used to fetch
 213      * text from the associated document.
 214      *
 215      * @return the buffer
 216      */
 217     protected final Segment getLineBuffer() {
 218         if (lineBuffer == null) {
 219             lineBuffer = new Segment();
 220         }
 221         return lineBuffer;
 222     }
 223 
 224     /**
 225      * This is called by the nested wrapped line
 226      * views to determine the break location.  This can
 227      * be reimplemented to alter the breaking behavior.
 228      * It will either break at word or character boundaries
 229      * depending upon the break argument given at
 230      * construction.
 231      */
 232     protected int calculateBreakPosition(int p0, int p1) {
 233         int p;
 234         Segment segment = SegmentCache.getSharedSegment();
 235         loadText(segment, p0, p1);
 236         int currentWidth = getWidth();
 237         if (wordWrap) {
 238             p = p0 + Utilities.getBreakLocation(segment, metrics,
 239                                                 tabBase, tabBase + currentWidth,
 240                                                 this, p0);
 241         } else {
 242             int offset = Utilities.getTabbedTextOffset(segment, metrics,
 243                     tabBase, tabBase + currentWidth, this, p0, false);
 244             offset = Utilities.adjustOffsetForFractionalMetrics(
 245                     segment, metrics, offset, currentWidth);
 246             p = p0 + offset;
 247         }
 248         SegmentCache.releaseSharedSegment(segment);
 249         return p;
 250     }
 251 
 252     /**
 253      * Loads all of the children to initialize the view.
 254      * This is called by the <code>setParent</code> method.
 255      * Subclasses can reimplement this to initialize their
 256      * child views in a different manner.  The default
 257      * implementation creates a child view for each
 258      * child element.
 259      *
 260      * @param f the view factory
 261      */
 262     protected void loadChildren(ViewFactory f) {
 263         Element e = getElement();
 264         int n = e.getElementCount();
 265         if (n > 0) {
 266             View[] added = new View[n];
 267             for (int i = 0; i < n; i++) {
 268                 added[i] = new WrappedLine(e.getElement(i));
 269             }
 270             replace(0, 0, added);
 271         }
 272     }
 273 
 274     /**
 275      * Update the child views in response to a
 276      * document event.
 277      */
 278     void updateChildren(DocumentEvent e, Shape a) {
 279         Element elem = getElement();
 280         DocumentEvent.ElementChange ec = e.getChange(elem);
 281         if (ec != null) {
 282             // the structure of this element changed.
 283             Element[] removedElems = ec.getChildrenRemoved();
 284             Element[] addedElems = ec.getChildrenAdded();
 285             View[] added = new View[addedElems.length];
 286             for (int i = 0; i < addedElems.length; i++) {
 287                 added[i] = new WrappedLine(addedElems[i]);
 288             }
 289             replace(ec.getIndex(), removedElems.length, added);
 290 
 291             // should damge a little more intelligently.
 292             if (a != null) {
 293                 preferenceChanged(null, true, true);
 294                 getContainer().repaint();
 295             }
 296         }
 297 
 298         // update font metrics which may be used by the child views
 299         updateMetrics();
 300     }
 301 
 302     /**
 303      * Load the text buffer with the given range
 304      * of text.  This is used by the fragments
 305      * broken off of this view as well as this
 306      * view itself.
 307      */
 308     final void loadText(Segment segment, int p0, int p1) {
 309         try {
 310             Document doc = getDocument();
 311             doc.getText(p0, p1 - p0, segment);
 312         } catch (BadLocationException bl) {
 313             throw new StateInvariantError("Can't get line text");
 314         }
 315     }
 316 
 317     final void updateMetrics() {
 318         Component host = getContainer();
 319         Font f = host.getFont();
 320         metrics = host.getFontMetrics(f);
 321         tabSize = getTabSize() * metrics.charWidth('m');
 322     }
 323 
 324     // --- TabExpander methods ------------------------------------------
 325 
 326     /**
 327      * Returns the next tab stop position after a given reference position.
 328      * This implementation does not support things like centering so it
 329      * ignores the tabOffset argument.
 330      *
 331      * @param x the current position >= 0
 332      * @param tabOffset the position within the text stream
 333      *   that the tab occurred at >= 0.
 334      * @return the tab stop, measured in points >= 0
 335      */
 336     public float nextTabStop(float x, int tabOffset) {
 337         if (tabSize == 0)
 338             return x;
 339         int ntabs = ((int) x - tabBase) / tabSize;
 340         return tabBase + ((ntabs + 1) * tabSize);
 341     }
 342 
 343 
 344     // --- View methods -------------------------------------
 345 
 346     /**
 347      * Renders using the given rendering surface and area
 348      * on that surface.  This is implemented to stash the
 349      * selection positions, selection colors, and font
 350      * metrics for the nested lines to use.
 351      *
 352      * @param g the rendering surface to use
 353      * @param a the allocated region to render into
 354      *
 355      * @see View#paint
 356      */
 357     public void paint(Graphics g, Shape a) {
 358         Rectangle alloc = (Rectangle) a;
 359         tabBase = alloc.x;
 360         JTextComponent host = (JTextComponent) getContainer();
 361         sel0 = host.getSelectionStart();
 362         sel1 = host.getSelectionEnd();
 363         unselected = (host.isEnabled()) ?
 364             host.getForeground() : host.getDisabledTextColor();
 365         Caret c = host.getCaret();
 366         selected = c.isSelectionVisible() && host.getHighlighter() != null ?
 367                         host.getSelectedTextColor() : unselected;
 368         g.setFont(host.getFont());
 369 
 370         // superclass paints the children
 371         super.paint(g, a);
 372     }
 373 
 374     /**
 375      * Sets the size of the view.  This should cause
 376      * layout of the view along the given axis, if it
 377      * has any layout duties.
 378      *
 379      * @param width the width >= 0
 380      * @param height the height >= 0
 381      */
 382     public void setSize(float width, float height) {
 383         updateMetrics();
 384         if ((int) width != getWidth()) {
 385             // invalidate the view itself since the childrens
 386             // desired widths will be based upon this views width.
 387             preferenceChanged(null, true, true);
 388             widthChanging = true;
 389         }
 390         super.setSize(width, height);
 391         widthChanging = false;
 392     }
 393 
 394     /**
 395      * Determines the preferred span for this view along an
 396      * axis.  This is implemented to provide the superclass
 397      * behavior after first making sure that the current font
 398      * metrics are cached (for the nested lines which use
 399      * the metrics to determine the height of the potentially
 400      * wrapped lines).
 401      *
 402      * @param axis may be either View.X_AXIS or View.Y_AXIS
 403      * @return  the span the view would like to be rendered into.
 404      *           Typically the view is told to render into the span
 405      *           that is returned, although there is no guarantee.
 406      *           The parent may choose to resize or break the view.
 407      * @see View#getPreferredSpan
 408      */
 409     public float getPreferredSpan(int axis) {
 410         updateMetrics();
 411         return super.getPreferredSpan(axis);
 412     }
 413 
 414     /**
 415      * Determines the minimum span for this view along an
 416      * axis.  This is implemented to provide the superclass
 417      * behavior after first making sure that the current font
 418      * metrics are cached (for the nested lines which use
 419      * the metrics to determine the height of the potentially
 420      * wrapped lines).
 421      *
 422      * @param axis may be either View.X_AXIS or View.Y_AXIS
 423      * @return  the span the view would like to be rendered into.
 424      *           Typically the view is told to render into the span
 425      *           that is returned, although there is no guarantee.
 426      *           The parent may choose to resize or break the view.
 427      * @see View#getMinimumSpan
 428      */
 429     public float getMinimumSpan(int axis) {
 430         updateMetrics();
 431         return super.getMinimumSpan(axis);
 432     }
 433 
 434     /**
 435      * Determines the maximum span for this view along an
 436      * axis.  This is implemented to provide the superclass
 437      * behavior after first making sure that the current font
 438      * metrics are cached (for the nested lines which use
 439      * the metrics to determine the height of the potentially
 440      * wrapped lines).
 441      *
 442      * @param axis may be either View.X_AXIS or View.Y_AXIS
 443      * @return  the span the view would like to be rendered into.
 444      *           Typically the view is told to render into the span
 445      *           that is returned, although there is no guarantee.
 446      *           The parent may choose to resize or break the view.
 447      * @see View#getMaximumSpan
 448      */
 449     public float getMaximumSpan(int axis) {
 450         updateMetrics();
 451         return super.getMaximumSpan(axis);
 452     }
 453 
 454     /**
 455      * Gives notification that something was inserted into the
 456      * document in a location that this view is responsible for.
 457      * This is implemented to simply update the children.
 458      *
 459      * @param e the change information from the associated document
 460      * @param a the current allocation of the view
 461      * @param f the factory to use to rebuild if the view has children
 462      * @see View#insertUpdate
 463      */
 464     public void insertUpdate(DocumentEvent e, Shape a, ViewFactory f) {
 465         updateChildren(e, a);
 466 
 467         Rectangle alloc = ((a != null) && isAllocationValid()) ?
 468             getInsideAllocation(a) : null;
 469         int pos = e.getOffset();
 470         View v = getViewAtPosition(pos, alloc);
 471         if (v != null) {
 472             v.insertUpdate(e, alloc, f);
 473         }
 474     }
 475 
 476     /**
 477      * Gives notification that something was removed from the
 478      * document in a location that this view is responsible for.
 479      * This is implemented to simply update the children.
 480      *
 481      * @param e the change information from the associated document
 482      * @param a the current allocation of the view
 483      * @param f the factory to use to rebuild if the view has children
 484      * @see View#removeUpdate
 485      */
 486     public void removeUpdate(DocumentEvent e, Shape a, ViewFactory f) {
 487         updateChildren(e, a);
 488 
 489         Rectangle alloc = ((a != null) && isAllocationValid()) ?
 490             getInsideAllocation(a) : null;
 491         int pos = e.getOffset();
 492         View v = getViewAtPosition(pos, alloc);
 493         if (v != null) {
 494             v.removeUpdate(e, alloc, f);
 495         }
 496     }
 497 
 498     /**
 499      * Gives notification from the document that attributes were changed
 500      * in a location that this view is responsible for.
 501      *
 502      * @param e the change information from the associated document
 503      * @param a the current allocation of the view
 504      * @param f the factory to use to rebuild if the view has children
 505      * @see View#changedUpdate
 506      */
 507     public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
 508         updateChildren(e, a);
 509     }
 510 
 511     // --- variables -------------------------------------------
 512 
 513     FontMetrics metrics;
 514     Segment lineBuffer;
 515     boolean widthChanging;
 516     int tabBase;
 517     int tabSize;
 518     boolean wordWrap;
 519 
 520     int sel0;
 521     int sel1;
 522     Color unselected;
 523     Color selected;
 524 
 525 
 526     /**
 527      * Simple view of a line that wraps if it doesn't
 528      * fit withing the horizontal space allocated.
 529      * This class tries to be lightweight by carrying little
 530      * state of it's own and sharing the state of the outer class
 531      * with it's sibblings.
 532      */
 533     class WrappedLine extends View {
 534 
 535         WrappedLine(Element elem) {
 536             super(elem);
 537             lineCount = -1;
 538         }
 539 
 540         /**
 541          * Determines the preferred span for this view along an
 542          * axis.
 543          *
 544          * @param axis may be either X_AXIS or Y_AXIS
 545          * @return   the span the view would like to be rendered into.
 546          *           Typically the view is told to render into the span
 547          *           that is returned, although there is no guarantee.
 548          *           The parent may choose to resize or break the view.
 549          * @see View#getPreferredSpan
 550          */
 551         public float getPreferredSpan(int axis) {
 552             switch (axis) {
 553             case View.X_AXIS:
 554                 float width = getWidth();
 555                 if (width == Integer.MAX_VALUE) {
 556                     // We have been initially set to MAX_VALUE, but we don't
 557                     // want this as our preferred.
 558                     return 100f;
 559                 }
 560                 return width;
 561             case View.Y_AXIS:
 562                 if (lineCount < 0 || widthChanging) {
 563                     breakLines(getStartOffset());
 564                 }
 565                 return lineCount * metrics.getHeight();
 566             default:
 567                 throw new IllegalArgumentException("Invalid axis: " + axis);
 568             }
 569         }
 570 
 571         /**
 572          * Renders using the given rendering surface and area on that
 573          * surface.  The view may need to do layout and create child
 574          * views to enable itself to render into the given allocation.
 575          *
 576          * @param g the rendering surface to use
 577          * @param a the allocated region to render into
 578          * @see View#paint
 579          */
 580         public void paint(Graphics g, Shape a) {
 581             Rectangle alloc = (Rectangle) a;
 582             int y = alloc.y + metrics.getAscent();
 583             int x = alloc.x;
 584 
 585             JTextComponent host = (JTextComponent)getContainer();
 586             Highlighter h = host.getHighlighter();
 587             LayeredHighlighter dh = (h instanceof LayeredHighlighter) ?
 588                                      (LayeredHighlighter)h : null;
 589 
 590             int start = getStartOffset();
 591             int end = getEndOffset();
 592             int p0 = start;
 593             int[] lineEnds = getLineEnds();
 594             for (int i = 0; i < lineCount; i++) {
 595                 int p1 = (lineEnds == null) ? end :
 596                                              start + lineEnds[i];
 597                 if (dh != null) {
 598                     int hOffset = (p1 == end)
 599                                   ? (p1 - 1)
 600                                   : p1;
 601                     dh.paintLayeredHighlights(g, p0, hOffset, a, host, this);
 602                 }
 603                 drawLine(p0, p1, g, x, y);
 604 
 605                 p0 = p1;
 606                 y += metrics.getHeight();
 607             }
 608         }
 609 
 610         /**
 611          * Provides a mapping from the document model coordinate space
 612          * to the coordinate space of the view mapped to it.
 613          *
 614          * @param pos the position to convert
 615          * @param a the allocated region to render into
 616          * @return the bounding box of the given position is returned
 617          * @exception BadLocationException  if the given position does not represent a
 618          *   valid location in the associated document
 619          * @see View#modelToView
 620          */
 621         public Shape modelToView(int pos, Shape a, Position.Bias b)
 622                 throws BadLocationException {
 623             Rectangle alloc = a.getBounds();
 624             alloc.height = metrics.getHeight();
 625             alloc.width = 1;
 626 
 627             int p0 = getStartOffset();
 628             if (pos < p0 || pos > getEndOffset()) {
 629                 throw new BadLocationException("Position out of range", pos);
 630             }
 631 
 632             int testP = (b == Position.Bias.Forward) ? pos :
 633                         Math.max(p0, pos - 1);
 634             int line = 0;
 635             int[] lineEnds = getLineEnds();
 636             if (lineEnds != null) {
 637                 line = findLine(testP - p0);
 638                 if (line > 0) {
 639                     p0 += lineEnds[line - 1];
 640                 }
 641                 alloc.y += alloc.height * line;
 642             }
 643 
 644             if (pos > p0) {
 645                 Segment segment = SegmentCache.getSharedSegment();
 646                 loadText(segment, p0, pos);
 647                 alloc.x += Utilities.getTabbedTextWidth(segment, metrics,
 648                         alloc.x, WrappedPlainView.this, p0);
 649                 SegmentCache.releaseSharedSegment(segment);
 650             }
 651             return alloc;
 652         }
 653 
 654         /**
 655          * Provides a mapping from the view coordinate space to the logical
 656          * coordinate space of the model.
 657          *
 658          * @param fx the X coordinate
 659          * @param fy the Y coordinate
 660          * @param a the allocated region to render into
 661          * @return the location within the model that best represents the
 662          *  given point in the view
 663          * @see View#viewToModel
 664          */
 665         public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) {
 666             // PENDING(prinz) implement bias properly
 667             bias[0] = Position.Bias.Forward;
 668 
 669             Rectangle alloc = (Rectangle) a;
 670             int x = (int) fx;
 671             int y = (int) fy;
 672             if (y < alloc.y) {
 673                 // above the area covered by this icon, so the the position
 674                 // is assumed to be the start of the coverage for this view.
 675                 return getStartOffset();
 676             } else if (y > alloc.y + alloc.height) {
 677                 // below the area covered by this icon, so the the position
 678                 // is assumed to be the end of the coverage for this view.
 679                 return getEndOffset() - 1;
 680             } else {
 681                 // positioned within the coverage of this view vertically,
 682                 // so we figure out which line the point corresponds to.
 683                 // if the line is greater than the number of lines contained, then
 684                 // simply use the last line as it represents the last possible place
 685                 // we can position to.
 686                 alloc.height = metrics.getHeight();
 687                 int line = (alloc.height > 0 ?
 688                             (y - alloc.y) / alloc.height : lineCount - 1);
 689                 if (line >= lineCount) {
 690                     return getEndOffset() - 1;
 691                 } else {
 692                     int p0 = getStartOffset();
 693                     int p1;
 694                     if (lineCount == 1) {
 695                         p1 = getEndOffset();
 696                     } else {
 697                         int[] lineEnds = getLineEnds();
 698                         p1 = p0 + lineEnds[line];
 699                         if (line > 0) {
 700                             p0 += lineEnds[line - 1];
 701                         }
 702                     }
 703 
 704                     if (x < alloc.x) {
 705                         // point is to the left of the line
 706                         return p0;
 707                     } else if (x > alloc.x + alloc.width) {
 708                         // point is to the right of the line
 709                         return p1 - 1;
 710                     } else {
 711                         // Determine the offset into the text
 712                         Segment segment = SegmentCache.getSharedSegment();
 713                         loadText(segment, p0, p1);
 714                         int n = Utilities.getTabbedTextOffset(segment, metrics,
 715                                                    alloc.x, x,
 716                                                    WrappedPlainView.this, p0);
 717                         SegmentCache.releaseSharedSegment(segment);
 718                         return Math.min(p0 + n, p1 - 1);
 719                     }
 720                 }
 721             }
 722         }
 723 
 724         public void insertUpdate(DocumentEvent e, Shape a, ViewFactory f) {
 725             update(e, a);
 726         }
 727 
 728         public void removeUpdate(DocumentEvent e, Shape a, ViewFactory f) {
 729             update(e, a);
 730         }
 731 
 732         private void update(DocumentEvent ev, Shape a) {
 733             int oldCount = lineCount;
 734             breakLines(ev.getOffset());
 735             if (oldCount != lineCount) {
 736                 WrappedPlainView.this.preferenceChanged(this, false, true);
 737                 // have to repaint any views after the receiver.
 738                 getContainer().repaint();
 739             } else if (a != null) {
 740                 Component c = getContainer();
 741                 Rectangle alloc = (Rectangle) a;
 742                 c.repaint(alloc.x, alloc.y, alloc.width, alloc.height);
 743             }
 744         }
 745 
 746         /**
 747          * Returns line cache. If the cache was GC'ed, recreates it.
 748          * If there's no cache, returns null
 749          */
 750         final int[] getLineEnds() {
 751             if (lineCache == null) {
 752                 return null;
 753             } else {
 754                 int[] lineEnds = lineCache.get();
 755                 if (lineEnds == null) {
 756                     // Cache was GC'ed, so rebuild it
 757                     return breakLines(getStartOffset());
 758                 } else {
 759                     return lineEnds;
 760                 }
 761             }
 762         }
 763 
 764         /**
 765          * Creates line cache if text breaks into more than one physical line.
 766          * @param startPos position to start breaking from
 767          * @return the cache created, ot null if text breaks into one line
 768          */
 769         final int[] breakLines(int startPos) {
 770             int[] lineEnds = (lineCache == null) ? null : lineCache.get();
 771             int[] oldLineEnds = lineEnds;
 772             int start = getStartOffset();
 773             int lineIndex = 0;
 774             if (lineEnds != null) {
 775                 lineIndex = findLine(startPos - start);
 776                 if (lineIndex > 0) {
 777                     lineIndex--;
 778                 }
 779             }
 780 
 781             int p0 = (lineIndex == 0) ? start : start + lineEnds[lineIndex - 1];
 782             int p1 = getEndOffset();
 783             while (p0 < p1) {
 784                 int p = calculateBreakPosition(p0, p1);
 785                 p0 = (p == p0) ? ++p : p;      // 4410243
 786 
 787                 if (lineIndex == 0 && p0 >= p1) {
 788                     // do not use cache if there's only one line
 789                     lineCache = null;
 790                     lineEnds = null;
 791                     lineIndex = 1;
 792                     break;
 793                 } else if (lineEnds == null || lineIndex >= lineEnds.length) {
 794                     // we have 2+ lines, and the cache is not big enough
 795                     // we try to estimate total number of lines
 796                     double growFactor = ((double)(p1 - start) / (p0 - start));
 797                     int newSize = (int)Math.ceil((lineIndex + 1) * growFactor);
 798                     newSize = Math.max(newSize, lineIndex + 2);
 799                     int[] tmp = new int[newSize];
 800                     if (lineEnds != null) {
 801                         System.arraycopy(lineEnds, 0, tmp, 0, lineIndex);
 802                     }
 803                     lineEnds = tmp;
 804                 }
 805                 lineEnds[lineIndex++] = p0 - start;
 806             }
 807 
 808             lineCount = lineIndex;
 809             if (lineCount > 1) {
 810                 // check if the cache is too big
 811                 int maxCapacity = lineCount + lineCount / 3;
 812                 if (lineEnds.length > maxCapacity) {
 813                     int[] tmp = new int[maxCapacity];
 814                     System.arraycopy(lineEnds, 0, tmp, 0, lineCount);
 815                     lineEnds = tmp;
 816                 }
 817             }
 818 
 819             if (lineEnds != null && lineEnds != oldLineEnds) {
 820                 lineCache = new SoftReference<int[]>(lineEnds);
 821             }
 822             return lineEnds;
 823         }
 824 
 825         /**
 826          * Binary search in the cache for line containing specified offset
 827          * (which is relative to the beginning of the view). This method
 828          * assumes that cache exists.
 829          */
 830         private int findLine(int offset) {
 831             int[] lineEnds = lineCache.get();
 832             if (offset < lineEnds[0]) {
 833                 return 0;
 834             } else if (offset > lineEnds[lineCount - 1]) {
 835                 return lineCount;
 836             } else {
 837                 return findLine(lineEnds, offset, 0, lineCount - 1);
 838             }
 839         }
 840 
 841         private int findLine(int[] array, int offset, int min, int max) {
 842             if (max - min <= 1) {
 843                 return max;
 844             } else {
 845                 int mid = (max + min) / 2;
 846                 return (offset < array[mid]) ?
 847                         findLine(array, offset, min, mid) :
 848                         findLine(array, offset, mid, max);
 849             }
 850         }
 851 
 852         int lineCount;
 853         SoftReference<int[]> lineCache = null;
 854     }
 855 }