0001 /*
0002 * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
0003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0004 *
0005 * This code is free software; you can redistribute it and/or modify it
0006 * under the terms of the GNU General Public License version 2 only, as
0007 * published by the Free Software Foundation. Sun designates this
0008 * particular file as subject to the "Classpath" exception as provided
0009 * by Sun in the LICENSE file that accompanied this code.
0010 *
0011 * This code is distributed in the hope that it will be useful, but WITHOUT
0012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0014 * version 2 for more details (a copy is included in the LICENSE file that
0015 * accompanied this code).
0016 *
0017 * You should have received a copy of the GNU General Public License version
0018 * 2 along with this work; if not, write to the Free Software Foundation,
0019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0020 *
0021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0022 * CA 95054 USA or visit www.sun.com if you need additional information or
0023 * have any questions.
0024 */
0025 package javax.swing.text;
0026
0027 import java.awt.*;
0028 import javax.swing.SwingConstants;
0029 import javax.swing.event.*;
0030
0031 /**
0032 * <p>
0033 * A very important part of the text package is the <code>View</code> class.
0034 * As the name suggests it represents a view of the text model,
0035 * or a piece of the text model.
0036 * It is this class that is responsible for the look of the text component.
0037 * The view is not intended to be some completely new thing that one must
0038 * learn, but rather is much like a lightweight component.
0039 * <p>
0040 By default, a view is very light. It contains a reference to the parent
0041 view from which it can fetch many things without holding state, and it
0042 contains a reference to a portion of the model (<code>Element</code>).
0043 A view does not
0044 have to exactly represent an element in the model, that is simply a typical
0045 and therefore convenient mapping. A view can alternatively maintain a couple
0046 of Position objects to maintain its location in the model (i.e. represent
0047 a fragment of an element). This is typically the result of formatting where
0048 views have been broken down into pieces. The convenience of a substantial
0049 relationship to the element makes it easier to build factories to produce the
0050 views, and makes it easier to keep track of the view pieces as the model is
0051 changed and the view must be changed to reflect the model. Simple views
0052 therefore represent an Element directly and complex views do not.
0053 <p>
0054 A view has the following responsibilities:
0055 <dl>
0056
0057 <dt><b>Participate in layout.</b>
0058 <dd>
0059 <p>The view has a <code>setSize</code> method which is like
0060 <code>doLayout</code> and <code>setSize</code> in <code>Component</code> combined.
0061 The view has a <code>preferenceChanged</code> method which is
0062 like <code>invalidate</code> in <code>Component</code> except that one can
0063 invalidate just one axis
0064 and the child requesting the change is identified.
0065 <p>A View expresses the size that it would like to be in terms of three
0066 values, a minimum, a preferred, and a maximum span. Layout in a view is
0067 can be done independently upon each axis. For a properly functioning View
0068 implementation, the minimum span will be <= the preferred span which in turn
0069 will be <= the maximum span.
0070 </p>
0071 <p align=center><img src="doc-files/View-flexibility.jpg"
0072 alt="The above text describes this graphic.">
0073 <p>The minimum set of methods for layout are:
0074 <ul>
0075 <li><a href="#getMinimumSpan(int)">getMinimumSpan</a>
0076 <li><a href="#getPreferredSpan(int)">getPreferredSpan</a>
0077 <li><a href="#getMaximumSpan(int)">getMaximumSpan</a>
0078 <li><a href="#getAlignment(int)">getAlignment</a>
0079 <li><a href="#preferenceChanged(javax.swing.text.View, boolean, boolean)">preferenceChanged</a>
0080 <li><a href="#setSize(float, float)">setSize</a>
0081 </ul>
0082
0083 <p>The <code>setSize</code> method should be prepared to be called a number of times
0084 (i.e. It may be called even if the size didn't change).
0085 The <code>setSize</code> method
0086 is generally called to make sure the View layout is complete prior to trying
0087 to perform an operation on it that requires an up-to-date layout. A view's
0088 size should <em>always</em> be set to a value within the minimum and maximum
0089 span specified by that view. Additionally, the view must always call the
0090 <code>preferenceChanged</code> method on the parent if it has changed the
0091 values for the
0092 layout it would like, and expects the parent to honor. The parent View is
0093 not required to recognize a change until the <code>preferenceChanged</code>
0094 has been sent.
0095 This allows parent View implementations to cache the child requirements if
0096 desired. The calling sequence looks something like the following:
0097 </p>
0098 <p align=center>
0099 <img src="doc-files/View-layout.jpg"
0100 alt="Sample calling sequence between parent view and child view:
0101 setSize, getMinimum, getPreferred, getMaximum, getAlignment, setSize">
0102 <p>The exact calling sequence is up to the layout functionality of
0103 the parent view (if the view has any children). The view may collect
0104 the preferences of the children prior to determining what it will give
0105 each child, or it might iteratively update the children one at a time.
0106 </p>
0107
0108 <dt><b>Render a portion of the model.</b>
0109 <dd>
0110 <p>This is done in the paint method, which is pretty much like a component
0111 paint method. Views are expected to potentially populate a fairly large
0112 tree. A <code>View</code> has the following semantics for rendering:
0113 </p>
0114 <ul>
0115 <li>The view gets its allocation from the parent at paint time, so it
0116 must be prepared to redo layout if the allocated area is different from
0117 what it is prepared to deal with.
0118 <li>The coordinate system is the same as the hosting <code>Component</code>
0119 (i.e. the <code>Component</code> returned by the
0120 <a href="#getContainer">getContainer</a> method).
0121 This means a child view lives in the same coordinate system as the parent
0122 view unless the parent has explicitly changed the coordinate system.
0123 To schedule itself to be repainted a view can call repaint on the hosting
0124 <code>Component</code>.
0125 <li>The default is to <em>not clip</em> the children. It is more efficient
0126 to allow a view to clip only if it really feels it needs clipping.
0127 <li>The <code>Graphics</code> object given is not initialized in any way.
0128 A view should set any settings needed.
0129 <li>A <code>View</code> is inherently transparent. While a view may render into its
0130 entire allocation, typically a view does not. Rendering is performed by
0131 tranversing down the tree of <code>View</code> implementations.
0132 Each <code>View</code> is responsible
0133 for rendering its children. This behavior is depended upon for thread
0134 safety. While view implementations do not necessarily have to be implemented
0135 with thread safety in mind, other view implementations that do make use of
0136 concurrency can depend upon a tree traversal to guarantee thread safety.
0137 <li>The order of views relative to the model is up to the implementation.
0138 Although child views will typically be arranged in the same order that they
0139 occur in the model, they may be visually arranged in an entirely different
0140 order. View implementations may have Z-Order associated with them if the
0141 children are overlapping.
0142 </ul>
0143 <p>The methods for rendering are:
0144 <ul>
0145 <li><a href="#paint(java.awt.Graphics, java.awt.Shape)">paint</a>
0146 </ul>
0147 <p>
0148
0149 <dt><b>Translate between the model and view coordinate systems.</b>
0150 <dd>
0151 <p>Because the view objects are produced from a factory and therefore cannot
0152 necessarily be counted upon to be in a particular pattern, one must be able
0153 to perform translation to properly locate spatial representation of the model.
0154 The methods for doing this are:
0155 <ul>
0156 <li><a href="#modelToView(int, javax.swing.text.Position.Bias, int, javax.swing.text.Position.Bias, java.awt.Shape)">modelToView</a>
0157 <li><a href="#viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])">viewToModel</a>
0158 <li><a href="#getDocument()">getDocument</a>
0159 <li><a href="#getElement()">getElement</a>
0160 <li><a href="#getStartOffset()">getStartOffset</a>
0161 <li><a href="#getEndOffset()">getEndOffset</a>
0162 </ul>
0163 <p>The layout must be valid prior to attempting to make the translation.
0164 The translation is not valid, and must not be attempted while changes
0165 are being broadcasted from the model via a <code>DocumentEvent</code>.
0166 </p>
0167
0168 <dt><b>Respond to changes from the model.</b>
0169 <dd>
0170 <p>If the overall view is represented by many pieces (which is the best situation
0171 if one want to be able to change the view and write the least amount of new code),
0172 it would be impractical to have a huge number of <code>DocumentListener</code>s.
0173 If each
0174 view listened to the model, only a few would actually be interested in the
0175 changes broadcasted at any given time. Since the model has no knowledge of
0176 views, it has no way to filter the broadcast of change information. The view
0177 hierarchy itself is instead responsible for propagating the change information.
0178 At any level in the view hierarchy, that view knows enough about its children to
0179 best distribute the change information further. Changes are therefore broadcasted
0180 starting from the root of the view hierarchy.
0181 The methods for doing this are:
0182 <ul>
0183 <li><a href="#insertUpdate">insertUpdate</a>
0184 <li><a href="#removeUpdate">removeUpdate</a>
0185 <li><a href="#changedUpdate">changedUpdate</a>
0186 </ul>
0187 <p>
0188 </dl>
0189 *
0190 * @author Timothy Prinzing
0191 * @version 1.81 05/05/07
0192 */
0193 public abstract class View implements SwingConstants {
0194
0195 /**
0196 * Creates a new <code>View</code> object.
0197 *
0198 * @param elem the <code>Element</code> to represent
0199 */
0200 public View(Element elem) {
0201 this .elem = elem;
0202 }
0203
0204 /**
0205 * Returns the parent of the view.
0206 *
0207 * @return the parent, or <code>null</code> if none exists
0208 */
0209 public View getParent() {
0210 return parent;
0211 }
0212
0213 /**
0214 * Returns a boolean that indicates whether
0215 * the view is visible or not. By default
0216 * all views are visible.
0217 *
0218 * @return always returns true
0219 */
0220 public boolean isVisible() {
0221 return true;
0222 }
0223
0224 /**
0225 * Determines the preferred span for this view along an
0226 * axis.
0227 *
0228 * @param axis may be either <code>View.X_AXIS</code> or
0229 * <code>View.Y_AXIS</code>
0230 * @return the span the view would like to be rendered into.
0231 * Typically the view is told to render into the span
0232 * that is returned, although there is no guarantee.
0233 * The parent may choose to resize or break the view
0234 * @see View#getPreferredSpan
0235 */
0236 public abstract float getPreferredSpan(int axis);
0237
0238 /**
0239 * Determines the minimum span for this view along an
0240 * axis.
0241 *
0242 * @param axis may be either <code>View.X_AXIS</code> or
0243 * <code>View.Y_AXIS</code>
0244 * @return the minimum span the view can be rendered into
0245 * @see View#getPreferredSpan
0246 */
0247 public float getMinimumSpan(int axis) {
0248 int w = getResizeWeight(axis);
0249 if (w == 0) {
0250 // can't resize
0251 return getPreferredSpan(axis);
0252 }
0253 return 0;
0254 }
0255
0256 /**
0257 * Determines the maximum span for this view along an
0258 * axis.
0259 *
0260 * @param axis may be either <code>View.X_AXIS</code> or
0261 * <code>View.Y_AXIS</code>
0262 * @return the maximum span the view can be rendered into
0263 * @see View#getPreferredSpan
0264 */
0265 public float getMaximumSpan(int axis) {
0266 int w = getResizeWeight(axis);
0267 if (w == 0) {
0268 // can't resize
0269 return getPreferredSpan(axis);
0270 }
0271 return Integer.MAX_VALUE;
0272 }
0273
0274 /**
0275 * Child views can call this on the parent to indicate that
0276 * the preference has changed and should be reconsidered
0277 * for layout. By default this just propagates upward to
0278 * the next parent. The root view will call
0279 * <code>revalidate</code> on the associated text component.
0280 *
0281 * @param child the child view
0282 * @param width true if the width preference has changed
0283 * @param height true if the height preference has changed
0284 * @see javax.swing.JComponent#revalidate
0285 */
0286 public void preferenceChanged(View child, boolean width,
0287 boolean height) {
0288 View parent = getParent();
0289 if (parent != null) {
0290 parent.preferenceChanged(this , width, height);
0291 }
0292 }
0293
0294 /**
0295 * Determines the desired alignment for this view along an
0296 * axis. The desired alignment is returned. This should be
0297 * a value >= 0.0 and <= 1.0, where 0 indicates alignment at
0298 * the origin and 1.0 indicates alignment to the full span
0299 * away from the origin. An alignment of 0.5 would be the
0300 * center of the view.
0301 *
0302 * @param axis may be either <code>View.X_AXIS</code> or
0303 * <code>View.Y_AXIS</code>
0304 * @return the value 0.5
0305 */
0306 public float getAlignment(int axis) {
0307 return 0.5f;
0308 }
0309
0310 /**
0311 * Renders using the given rendering surface and area on that
0312 * surface. The view may need to do layout and create child
0313 * views to enable itself to render into the given allocation.
0314 *
0315 * @param g the rendering surface to use
0316 * @param allocation the allocated region to render into
0317 */
0318 public abstract void paint(Graphics g, Shape allocation);
0319
0320 /**
0321 * Establishes the parent view for this view. This is
0322 * guaranteed to be called before any other methods if the
0323 * parent view is functioning properly. This is also
0324 * the last method called, since it is called to indicate
0325 * the view has been removed from the hierarchy as
0326 * well. When this method is called to set the parent to
0327 * null, this method does the same for each of its children,
0328 * propogating the notification that they have been
0329 * disconnected from the view tree. If this is
0330 * reimplemented, <code>super.setParent()</code> should
0331 * be called.
0332 *
0333 * @param parent the new parent, or <code>null</code> if the view is
0334 * being removed from a parent
0335 */
0336 public void setParent(View parent) {
0337 // if the parent is null then propogate down the view tree
0338 if (parent == null) {
0339 for (int i = 0; i < getViewCount(); i++) {
0340 if (getView(i).getParent() == this ) {
0341 // in FlowView.java view might be referenced
0342 // from two super-views as a child. see logicalView
0343 getView(i).setParent(null);
0344 }
0345 }
0346 }
0347 this .parent = parent;
0348 }
0349
0350 /**
0351 * Returns the number of views in this view. Since
0352 * the default is to not be a composite view this
0353 * returns 0.
0354 *
0355 * @return the number of views >= 0
0356 * @see View#getViewCount
0357 */
0358 public int getViewCount() {
0359 return 0;
0360 }
0361
0362 /**
0363 * Gets the <i>n</i>th child view. Since there are no
0364 * children by default, this returns <code>null</code>.
0365 *
0366 * @param n the number of the view to get, >= 0 && < getViewCount()
0367 * @return the view
0368 */
0369 public View getView(int n) {
0370 return null;
0371 }
0372
0373 /**
0374 * Removes all of the children. This is a convenience
0375 * call to <code>replace</code>.
0376 *
0377 * @since 1.3
0378 */
0379 public void removeAll() {
0380 replace(0, getViewCount(), null);
0381 }
0382
0383 /**
0384 * Removes one of the children at the given position.
0385 * This is a convenience call to <code>replace</code>.
0386 * @since 1.3
0387 */
0388 public void remove(int i) {
0389 replace(i, 1, null);
0390 }
0391
0392 /**
0393 * Inserts a single child view. This is a convenience
0394 * call to <code>replace</code>.
0395 *
0396 * @param offs the offset of the view to insert before >= 0
0397 * @param v the view
0398 * @see #replace
0399 * @since 1.3
0400 */
0401 public void insert(int offs, View v) {
0402 View[] one = new View[1];
0403 one[0] = v;
0404 replace(offs, 0, one);
0405 }
0406
0407 /**
0408 * Appends a single child view. This is a convenience
0409 * call to <code>replace</code>.
0410 *
0411 * @param v the view
0412 * @see #replace
0413 * @since 1.3
0414 */
0415 public void append(View v) {
0416 View[] one = new View[1];
0417 one[0] = v;
0418 replace(getViewCount(), 0, one);
0419 }
0420
0421 /**
0422 * Replaces child views. If there are no views to remove
0423 * this acts as an insert. If there are no views to
0424 * add this acts as a remove. Views being removed will
0425 * have the parent set to <code>null</code>, and the internal reference
0426 * to them removed so that they can be garbage collected.
0427 * This is implemented to do nothing, because by default
0428 * a view has no children.
0429 *
0430 * @param offset the starting index into the child views to insert
0431 * the new views. This should be a value >= 0 and <= getViewCount
0432 * @param length the number of existing child views to remove
0433 * This should be a value >= 0 and <= (getViewCount() - offset).
0434 * @param views the child views to add. This value can be
0435 * <code>null</code> to indicate no children are being added
0436 * (useful to remove).
0437 * @since 1.3
0438 */
0439 public void replace(int offset, int length, View[] views) {
0440 }
0441
0442 /**
0443 * Returns the child view index representing the given position in
0444 * the model. By default a view has no children so this is implemented
0445 * to return -1 to indicate there is no valid child index for any
0446 * position.
0447 *
0448 * @param pos the position >= 0
0449 * @return index of the view representing the given position, or
0450 * -1 if no view represents that position
0451 * @since 1.3
0452 */
0453 public int getViewIndex(int pos, Position.Bias b) {
0454 return -1;
0455 }
0456
0457 /**
0458 * Fetches the allocation for the given child view.
0459 * This enables finding out where various views
0460 * are located, without assuming how the views store
0461 * their location. This returns <code>null</code> since the
0462 * default is to not have any child views.
0463 *
0464 * @param index the index of the child, >= 0 && <
0465 * <code>getViewCount()</code>
0466 * @param a the allocation to this view
0467 * @return the allocation to the child
0468 */
0469 public Shape getChildAllocation(int index, Shape a) {
0470 return null;
0471 }
0472
0473 /**
0474 * Provides a way to determine the next visually represented model
0475 * location at which one might place a caret.
0476 * Some views may not be visible,
0477 * they might not be in the same order found in the model, or they just
0478 * might not allow access to some of the locations in the model.
0479 *
0480 * @param pos the position to convert >= 0
0481 * @param a the allocated region in which to render
0482 * @param direction the direction from the current position that can
0483 * be thought of as the arrow keys typically found on a keyboard.
0484 * This will be one of the following values:
0485 * <ul>
0486 * <li>SwingConstants.WEST
0487 * <li>SwingConstants.EAST
0488 * <li>SwingConstants.NORTH
0489 * <li>SwingConstants.SOUTH
0490 * </ul>
0491 * @return the location within the model that best represents the next
0492 * location visual position
0493 * @exception BadLocationException
0494 * @exception IllegalArgumentException if <code>direction</code>
0495 * doesn't have one of the legal values above
0496 */
0497 public int getNextVisualPositionFrom(int pos, Position.Bias b,
0498 Shape a, int direction, Position.Bias[] biasRet)
0499 throws BadLocationException {
0500
0501 biasRet[0] = Position.Bias.Forward;
0502 switch (direction) {
0503 case NORTH:
0504 case SOUTH: {
0505 if (pos == -1) {
0506 pos = (direction == NORTH) ? Math.max(0,
0507 getEndOffset() - 1) : getStartOffset();
0508 break;
0509 }
0510 JTextComponent target = (JTextComponent) getContainer();
0511 Caret c = (target != null) ? target.getCaret() : null;
0512 // YECK! Ideally, the x location from the magic caret position
0513 // would be passed in.
0514 Point mcp;
0515 if (c != null) {
0516 mcp = c.getMagicCaretPosition();
0517 } else {
0518 mcp = null;
0519 }
0520 int x;
0521 if (mcp == null) {
0522 Rectangle loc = target.modelToView(pos);
0523 x = (loc == null) ? 0 : loc.x;
0524 } else {
0525 x = mcp.x;
0526 }
0527 if (direction == NORTH) {
0528 pos = Utilities.getPositionAbove(target, pos, x);
0529 } else {
0530 pos = Utilities.getPositionBelow(target, pos, x);
0531 }
0532 }
0533 break;
0534 case WEST:
0535 if (pos == -1) {
0536 pos = Math.max(0, getEndOffset() - 1);
0537 } else {
0538 pos = Math.max(0, pos - 1);
0539 }
0540 break;
0541 case EAST:
0542 if (pos == -1) {
0543 pos = getStartOffset();
0544 } else {
0545 pos = Math.min(pos + 1, getDocument().getLength());
0546 }
0547 break;
0548 default:
0549 throw new IllegalArgumentException("Bad direction: "
0550 + direction);
0551 }
0552 return pos;
0553 }
0554
0555 /**
0556 * Provides a mapping, for a given character,
0557 * from the document model coordinate space
0558 * to the view coordinate space.
0559 *
0560 * @param pos the position of the desired character (>=0)
0561 * @param a the area of the view, which encompasses the requested character
0562 * @param b the bias toward the previous character or the
0563 * next character represented by the offset, in case the
0564 * position is a boundary of two views; <code>b</code> will have one
0565 * of these values:
0566 * <ul>
0567 * <li> <code>Position.Bias.Forward</code>
0568 * <li> <code>Position.Bias.Backward</code>
0569 * </ul>
0570 * @return the bounding box, in view coordinate space,
0571 * of the character at the specified position
0572 * @exception BadLocationException if the specified position does
0573 * not represent a valid location in the associated document
0574 * @exception IllegalArgumentException if <code>b</code> is not one of the
0575 * legal <code>Position.Bias</code> values listed above
0576 * @see View#viewToModel
0577 */
0578 public abstract Shape modelToView(int pos, Shape a, Position.Bias b)
0579 throws BadLocationException;
0580
0581 /**
0582 * Provides a mapping, for a given region,
0583 * from the document model coordinate space
0584 * to the view coordinate space. The specified region is
0585 * created as a union of the first and last character positions.
0586 *
0587 * @param p0 the position of the first character (>=0)
0588 * @param b0 the bias of the first character position,
0589 * toward the previous character or the
0590 * next character represented by the offset, in case the
0591 * position is a boundary of two views; <code>b0</code> will have one
0592 * of these values:
0593 * <ul>
0594 * <li> <code>Position.Bias.Forward</code>
0595 * <li> <code>Position.Bias.Backward</code>
0596 * </ul>
0597 * @param p1 the position of the last character (>=0)
0598 * @param b1 the bias for the second character position, defined
0599 * one of the legal values shown above
0600 * @param a the area of the view, which encompasses the requested region
0601 * @return the bounding box which is a union of the region specified
0602 * by the first and last character positions
0603 * @exception BadLocationException if the given position does
0604 * not represent a valid location in the associated document
0605 * @exception IllegalArgumentException if <code>b0</code> or
0606 * <code>b1</code> are not one of the
0607 * legal <code>Position.Bias</code> values listed above
0608 * @see View#viewToModel
0609 */
0610 public Shape modelToView(int p0, Position.Bias b0, int p1,
0611 Position.Bias b1, Shape a) throws BadLocationException {
0612 Shape s0 = modelToView(p0, a, b0);
0613 Shape s1;
0614 if (p1 == getEndOffset()) {
0615 try {
0616 s1 = modelToView(p1, a, b1);
0617 } catch (BadLocationException ble) {
0618 s1 = null;
0619 }
0620 if (s1 == null) {
0621 // Assume extends left to right.
0622 Rectangle alloc = (a instanceof Rectangle) ? (Rectangle) a
0623 : a.getBounds();
0624 s1 = new Rectangle(alloc.x + alloc.width - 1, alloc.y,
0625 1, alloc.height);
0626 }
0627 } else {
0628 s1 = modelToView(p1, a, b1);
0629 }
0630 Rectangle r0 = s0.getBounds();
0631 Rectangle r1 = (s1 instanceof Rectangle) ? (Rectangle) s1 : s1
0632 .getBounds();
0633 if (r0.y != r1.y) {
0634 // If it spans lines, force it to be the width of the view.
0635 Rectangle alloc = (a instanceof Rectangle) ? (Rectangle) a
0636 : a.getBounds();
0637 r0.x = alloc.x;
0638 r0.width = alloc.width;
0639 }
0640 r0.add(r1);
0641 return r0;
0642 }
0643
0644 /**
0645 * Provides a mapping from the view coordinate space to the logical
0646 * coordinate space of the model. The <code>biasReturn</code>
0647 * argument will be filled in to indicate that the point given is
0648 * closer to the next character in the model or the previous
0649 * character in the model.
0650 *
0651 * @param x the X coordinate >= 0
0652 * @param y the Y coordinate >= 0
0653 * @param a the allocated region in which to render
0654 * @return the location within the model that best represents the
0655 * given point in the view >= 0. The <code>biasReturn</code>
0656 * argument will be
0657 * filled in to indicate that the point given is closer to the next
0658 * character in the model or the previous character in the model.
0659 */
0660 public abstract int viewToModel(float x, float y, Shape a,
0661 Position.Bias[] biasReturn);
0662
0663 /**
0664 * Gives notification that something was inserted into
0665 * the document in a location that this view is responsible for.
0666 * To reduce the burden to subclasses, this functionality is
0667 * spread out into the following calls that subclasses can
0668 * reimplement:
0669 * <ol>
0670 * <li><a href="#updateChildren">updateChildren</a> is called
0671 * if there were any changes to the element this view is
0672 * responsible for. If this view has child views that are
0673 * represent the child elements, then this method should do
0674 * whatever is necessary to make sure the child views correctly
0675 * represent the model.
0676 * <li><a href="#forwardUpdate">forwardUpdate</a> is called
0677 * to forward the DocumentEvent to the appropriate child views.
0678 * <li><a href="#updateLayout">updateLayout</a> is called to
0679 * give the view a chance to either repair its layout, to reschedule
0680 * layout, or do nothing.
0681 * </ol>
0682 *
0683 * @param e the change information from the associated document
0684 * @param a the current allocation of the view
0685 * @param f the factory to use to rebuild if the view has children
0686 * @see View#insertUpdate
0687 */
0688 public void insertUpdate(DocumentEvent e, Shape a, ViewFactory f) {
0689 if (getViewCount() > 0) {
0690 Element elem = getElement();
0691 DocumentEvent.ElementChange ec = e.getChange(elem);
0692 if (ec != null) {
0693 if (!updateChildren(ec, e, f)) {
0694 // don't consider the element changes they
0695 // are for a view further down.
0696 ec = null;
0697 }
0698 }
0699 forwardUpdate(ec, e, a, f);
0700 updateLayout(ec, e, a);
0701 }
0702 }
0703
0704 /**
0705 * Gives notification that something was removed from the document
0706 * in a location that this view is responsible for.
0707 * To reduce the burden to subclasses, this functionality is
0708 * spread out into the following calls that subclasses can
0709 * reimplement:
0710 * <ol>
0711 * <li><a href="#updateChildren">updateChildren</a> is called
0712 * if there were any changes to the element this view is
0713 * responsible for. If this view has child views that are
0714 * represent the child elements, then this method should do
0715 * whatever is necessary to make sure the child views correctly
0716 * represent the model.
0717 * <li><a href="#forwardUpdate">forwardUpdate</a> is called
0718 * to forward the DocumentEvent to the appropriate child views.
0719 * <li><a href="#updateLayout">updateLayout</a> is called to
0720 * give the view a chance to either repair its layout, to reschedule
0721 * layout, or do nothing.
0722 * </ol>
0723 *
0724 * @param e the change information from the associated document
0725 * @param a the current allocation of the view
0726 * @param f the factory to use to rebuild if the view has children
0727 * @see View#removeUpdate
0728 */
0729 public void removeUpdate(DocumentEvent e, Shape a, ViewFactory f) {
0730 if (getViewCount() > 0) {
0731 Element elem = getElement();
0732 DocumentEvent.ElementChange ec = e.getChange(elem);
0733 if (ec != null) {
0734 if (!updateChildren(ec, e, f)) {
0735 // don't consider the element changes they
0736 // are for a view further down.
0737 ec = null;
0738 }
0739 }
0740 forwardUpdate(ec, e, a, f);
0741 updateLayout(ec, e, a);
0742 }
0743 }
0744
0745 /**
0746 * Gives notification from the document that attributes were changed
0747 * in a location that this view is responsible for.
0748 * To reduce the burden to subclasses, this functionality is
0749 * spread out into the following calls that subclasses can
0750 * reimplement:
0751 * <ol>
0752 * <li><a href="#updateChildren">updateChildren</a> is called
0753 * if there were any changes to the element this view is
0754 * responsible for. If this view has child views that are
0755 * represent the child elements, then this method should do
0756 * whatever is necessary to make sure the child views correctly
0757 * represent the model.
0758 * <li><a href="#forwardUpdate">forwardUpdate</a> is called
0759 * to forward the DocumentEvent to the appropriate child views.
0760 * <li><a href="#updateLayout">updateLayout</a> is called to
0761 * give the view a chance to either repair its layout, to reschedule
0762 * layout, or do nothing.
0763 * </ol>
0764 *
0765 * @param e the change information from the associated document
0766 * @param a the current allocation of the view
0767 * @param f the factory to use to rebuild if the view has children
0768 * @see View#changedUpdate
0769 */
0770 public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
0771 if (getViewCount() > 0) {
0772 Element elem = getElement();
0773 DocumentEvent.ElementChange ec = e.getChange(elem);
0774 if (ec != null) {
0775 if (!updateChildren(ec, e, f)) {
0776 // don't consider the element changes they
0777 // are for a view further down.
0778 ec = null;
0779 }
0780 }
0781 forwardUpdate(ec, e, a, f);
0782 updateLayout(ec, e, a);
0783 }
0784 }
0785
0786 /**
0787 * Fetches the model associated with the view.
0788 *
0789 * @return the view model, <code>null</code> if none
0790 * @see View#getDocument
0791 */
0792 public Document getDocument() {
0793 return elem.getDocument();
0794 }
0795
0796 /**
0797 * Fetches the portion of the model for which this view is
0798 * responsible.
0799 *
0800 * @return the starting offset into the model >= 0
0801 * @see View#getStartOffset
0802 */
0803 public int getStartOffset() {
0804 return elem.getStartOffset();
0805 }
0806
0807 /**
0808 * Fetches the portion of the model for which this view is
0809 * responsible.
0810 *
0811 * @return the ending offset into the model >= 0
0812 * @see View#getEndOffset
0813 */
0814 public int getEndOffset() {
0815 return elem.getEndOffset();
0816 }
0817
0818 /**
0819 * Fetches the structural portion of the subject that this
0820 * view is mapped to. The view may not be responsible for the
0821 * entire portion of the element.
0822 *
0823 * @return the subject
0824 * @see View#getElement
0825 */
0826 public Element getElement() {
0827 return elem;
0828 }
0829
0830 /**
0831 * Fetch a <code>Graphics</code> for rendering.
0832 * This can be used to determine
0833 * font characteristics, and will be different for a print view
0834 * than a component view.
0835 *
0836 * @return a <code>Graphics</code> object for rendering
0837 * @since 1.3
0838 */
0839 public Graphics getGraphics() {
0840 // PENDING(prinz) this is a temporary implementation
0841 Component c = getContainer();
0842 return c.getGraphics();
0843 }
0844
0845 /**
0846 * Fetches the attributes to use when rendering. By default
0847 * this simply returns the attributes of the associated element.
0848 * This method should be used rather than using the element
0849 * directly to obtain access to the attributes to allow
0850 * view-specific attributes to be mixed in or to allow the
0851 * view to have view-specific conversion of attributes by
0852 * subclasses.
0853 * Each view should document what attributes it recognizes
0854 * for the purpose of rendering or layout, and should always
0855 * access them through the <code>AttributeSet</code> returned
0856 * by this method.
0857 */
0858 public AttributeSet getAttributes() {
0859 return elem.getAttributes();
0860 }
0861
0862 /**
0863 * Tries to break this view on the given axis. This is
0864 * called by views that try to do formatting of their
0865 * children. For example, a view of a paragraph will
0866 * typically try to place its children into row and
0867 * views representing chunks of text can sometimes be
0868 * broken down into smaller pieces.
0869 * <p>
0870 * This is implemented to return the view itself, which
0871 * represents the default behavior on not being
0872 * breakable. If the view does support breaking, the
0873 * starting offset of the view returned should be the
0874 * given offset, and the end offset should be less than
0875 * or equal to the end offset of the view being broken.
0876 *
0877 * @param axis may be either <code>View.X_AXIS</code> or
0878 * <code>View.Y_AXIS</code>
0879 * @param offset the location in the document model
0880 * that a broken fragment would occupy >= 0. This
0881 * would be the starting offset of the fragment
0882 * returned
0883 * @param pos the position along the axis that the
0884 * broken view would occupy >= 0. This may be useful for
0885 * things like tab calculations
0886 * @param len specifies the distance along the axis
0887 * where a potential break is desired >= 0
0888 * @return the fragment of the view that represents the
0889 * given span, if the view can be broken. If the view
0890 * doesn't support breaking behavior, the view itself is
0891 * returned.
0892 * @see ParagraphView
0893 */
0894 public View breakView(int axis, int offset, float pos, float len) {
0895 return this ;
0896 }
0897
0898 /**
0899 * Creates a view that represents a portion of the element.
0900 * This is potentially useful during formatting operations
0901 * for taking measurements of fragments of the view. If
0902 * the view doesn't support fragmenting (the default), it
0903 * should return itself.
0904 *
0905 * @param p0 the starting offset >= 0. This should be a value
0906 * greater or equal to the element starting offset and
0907 * less than the element ending offset.
0908 * @param p1 the ending offset > p0. This should be a value
0909 * less than or equal to the elements end offset and
0910 * greater than the elements starting offset.
0911 * @return the view fragment, or itself if the view doesn't
0912 * support breaking into fragments
0913 * @see LabelView
0914 */
0915 public View createFragment(int p0, int p1) {
0916 return this ;
0917 }
0918
0919 /**
0920 * Determines how attractive a break opportunity in
0921 * this view is. This can be used for determining which
0922 * view is the most attractive to call <code>breakView</code>
0923 * on in the process of formatting. A view that represents
0924 * text that has whitespace in it might be more attractive
0925 * than a view that has no whitespace, for example. The
0926 * higher the weight, the more attractive the break. A
0927 * value equal to or lower than <code>BadBreakWeight</code>
0928 * should not be considered for a break. A value greater
0929 * than or equal to <code>ForcedBreakWeight</code> should
0930 * be broken.
0931 * <p>
0932 * This is implemented to provide the default behavior
0933 * of returning <code>BadBreakWeight</code> unless the length
0934 * is greater than the length of the view in which case the
0935 * entire view represents the fragment. Unless a view has
0936 * been written to support breaking behavior, it is not
0937 * attractive to try and break the view. An example of
0938 * a view that does support breaking is <code>LabelView</code>.
0939 * An example of a view that uses break weight is
0940 * <code>ParagraphView</code>.
0941 *
0942 * @param axis may be either <code>View.X_AXIS</code> or
0943 * <code>View.Y_AXIS</code>
0944 * @param pos the potential location of the start of the
0945 * broken view >= 0. This may be useful for calculating tab
0946 * positions
0947 * @param len specifies the relative length from <em>pos</em>
0948 * where a potential break is desired >= 0
0949 * @return the weight, which should be a value between
0950 * ForcedBreakWeight and BadBreakWeight
0951 * @see LabelView
0952 * @see ParagraphView
0953 * @see #BadBreakWeight
0954 * @see #GoodBreakWeight
0955 * @see #ExcellentBreakWeight
0956 * @see #ForcedBreakWeight
0957 */
0958 public int getBreakWeight(int axis, float pos, float len) {
0959 if (len > getPreferredSpan(axis)) {
0960 return GoodBreakWeight;
0961 }
0962 return BadBreakWeight;
0963 }
0964
0965 /**
0966 * Determines the resizability of the view along the
0967 * given axis. A value of 0 or less is not resizable.
0968 *
0969 * @param axis may be either <code>View.X_AXIS</code> or
0970 * <code>View.Y_AXIS</code>
0971 * @return the weight
0972 */
0973 public int getResizeWeight(int axis) {
0974 return 0;
0975 }
0976
0977 /**
0978 * Sets the size of the view. This should cause
0979 * layout of the view along the given axis, if it
0980 * has any layout duties.
0981 *
0982 * @param width the width >= 0
0983 * @param height the height >= 0
0984 */
0985 public void setSize(float width, float height) {
0986 }
0987
0988 /**
0989 * Fetches the container hosting the view. This is useful for
0990 * things like scheduling a repaint, finding out the host
0991 * components font, etc. The default implementation
0992 * of this is to forward the query to the parent view.
0993 *
0994 * @return the container, <code>null</code> if none
0995 */
0996 public Container getContainer() {
0997 View v = getParent();
0998 return (v != null) ? v.getContainer() : null;
0999 }
1000
1001 /**
1002 * Fetches the <code>ViewFactory</code> implementation that is feeding
1003 * the view hierarchy. Normally the views are given this
1004 * as an argument to updates from the model when they
1005 * are most likely to need the factory, but this
1006 * method serves to provide it at other times.
1007 *
1008 * @return the factory, <code>null</code> if none
1009 */
1010 public ViewFactory getViewFactory() {
1011 View v = getParent();
1012 return (v != null) ? v.getViewFactory() : null;
1013 }
1014
1015 /**
1016 * Returns the tooltip text at the specified location. The default
1017 * implementation returns the value from the child View identified by
1018 * the passed in location.
1019 *
1020 * @since 1.4
1021 * @see JTextComponent#getToolTipText
1022 */
1023 public String getToolTipText(float x, float y, Shape allocation) {
1024 int viewIndex = getViewIndex(x, y, allocation);
1025 if (viewIndex >= 0) {
1026 allocation = getChildAllocation(viewIndex, allocation);
1027 Rectangle rect = (allocation instanceof Rectangle) ? (Rectangle) allocation
1028 : allocation.getBounds();
1029 if (rect.contains(x, y)) {
1030 return getView(viewIndex).getToolTipText(x, y,
1031 allocation);
1032 }
1033 }
1034 return null;
1035 }
1036
1037 /**
1038 * Returns the child view index representing the given position in
1039 * the view. This iterates over all the children returning the
1040 * first with a bounds that contains <code>x</code>, <code>y</code>.
1041 *
1042 * @param x the x coordinate
1043 * @param y the y coordinate
1044 * @param allocation current allocation of the View.
1045 * @return index of the view representing the given location, or
1046 * -1 if no view represents that position
1047 * @since 1.4
1048 */
1049 public int getViewIndex(float x, float y, Shape allocation) {
1050 for (int counter = getViewCount() - 1; counter >= 0; counter--) {
1051 Shape childAllocation = getChildAllocation(counter,
1052 allocation);
1053
1054 if (childAllocation != null) {
1055 Rectangle rect = (childAllocation instanceof Rectangle) ? (Rectangle) childAllocation
1056 : childAllocation.getBounds();
1057
1058 if (rect.contains(x, y)) {
1059 return counter;
1060 }
1061 }
1062 }
1063 return -1;
1064 }
1065
1066 /**
1067 * Updates the child views in response to receiving notification
1068 * that the model changed, and there is change record for the
1069 * element this view is responsible for. This is implemented
1070 * to assume the child views are directly responsible for the
1071 * child elements of the element this view represents. The
1072 * <code>ViewFactory</code> is used to create child views for each element
1073 * specified as added in the <code>ElementChange</code>, starting at the
1074 * index specified in the given <code>ElementChange</code>. The number of
1075 * child views representing the removed elements specified are
1076 * removed.
1077 *
1078 * @param ec the change information for the element this view
1079 * is responsible for. This should not be <code>null</code> if
1080 * this method gets called
1081 * @param e the change information from the associated document
1082 * @param f the factory to use to build child views
1083 * @return whether or not the child views represent the
1084 * child elements of the element this view is responsible
1085 * for. Some views create children that represent a portion
1086 * of the element they are responsible for, and should return
1087 * false. This information is used to determine if views
1088 * in the range of the added elements should be forwarded to
1089 * or not
1090 * @see #insertUpdate
1091 * @see #removeUpdate
1092 * @see #changedUpdate
1093 * @since 1.3
1094 */
1095 protected boolean updateChildren(DocumentEvent.ElementChange ec,
1096 DocumentEvent e, ViewFactory f) {
1097 Element[] removedElems = ec.getChildrenRemoved();
1098 Element[] addedElems = ec.getChildrenAdded();
1099 View[] added = null;
1100 if (addedElems != null) {
1101 added = new View[addedElems.length];
1102 for (int i = 0; i < addedElems.length; i++) {
1103 added[i] = f.create(addedElems[i]);
1104 }
1105 }
1106 int nremoved = 0;
1107 int index = ec.getIndex();
1108 if (removedElems != null) {
1109 nremoved = removedElems.length;
1110 }
1111 replace(index, nremoved, added);
1112 return true;
1113 }
1114
1115 /**
1116 * Forwards the given <code>DocumentEvent</code> to the child views
1117 * that need to be notified of the change to the model.
1118 * If there were changes to the element this view is
1119 * responsible for, that should be considered when
1120 * forwarding (i.e. new child views should not get
1121 * notified).
1122 *
1123 * @param ec changes to the element this view is responsible
1124 * for (may be <code>null</code> if there were no changes).
1125 * @param e the change information from the associated document
1126 * @param a the current allocation of the view
1127 * @param f the factory to use to rebuild if the view has children
1128 * @see #insertUpdate
1129 * @see #removeUpdate
1130 * @see #changedUpdate
1131 * @since 1.3
1132 */
1133 protected void forwardUpdate(DocumentEvent.ElementChange ec,
1134 DocumentEvent e, Shape a, ViewFactory f) {
1135 Element elem = getElement();
1136 int pos = e.getOffset();
1137 int index0 = getViewIndex(pos, Position.Bias.Forward);
1138 if (index0 == -1
1139 && e.getType() == DocumentEvent.EventType.REMOVE
1140 && pos >= getEndOffset()) {
1141 // Event beyond our offsets. We may have represented this, that is
1142 // the remove may have removed one of our child Elements that
1143 // represented this, so, we should foward to last element.
1144 index0 = getViewCount() - 1;
1145 }
1146 int index1 = index0;
1147 View v = (index0 >= 0) ? getView(index0) : null;
1148 if (v != null) {
1149 if ((v.getStartOffset() == pos) && (pos > 0)) {
1150 // If v is at a boundary, forward the event to the previous
1151 // view too.
1152 index0 = Math.max(index0 - 1, 0);
1153 }
1154 }
1155 if (e.getType() != DocumentEvent.EventType.REMOVE) {
1156 index1 = getViewIndex(pos + e.getLength(),
1157 Position.Bias.Forward);
1158 if (index1 < 0) {
1159 index1 = getViewCount() - 1;
1160 }
1161 }
1162 int hole0 = index1 + 1;
1163 int hole1 = hole0;
1164 Element[] addedElems = (ec != null) ? ec.getChildrenAdded()
1165 : null;
1166 if ((addedElems != null) && (addedElems.length > 0)) {
1167 hole0 = ec.getIndex();
1168 hole1 = hole0 + addedElems.length - 1;
1169 }
1170
1171 // forward to any view not in the forwarding hole
1172 // formed by added elements (i.e. they will be updated
1173 // by initialization.
1174 index0 = Math.max(index0, 0);
1175 for (int i = index0; i <= index1; i++) {
1176 if (!((i >= hole0) && (i <= hole1))) {
1177 v = getView(i);
1178 if (v != null) {
1179 Shape childAlloc = getChildAllocation(i, a);
1180 forwardUpdateToView(v, e, childAlloc, f);
1181 }
1182 }
1183 }
1184 }
1185
1186 /**
1187 * Forwards the <code>DocumentEvent</code> to the give child view. This
1188 * simply messages the view with a call to <code>insertUpdate</code>,
1189 * <code>removeUpdate</code>, or <code>changedUpdate</code> depending
1190 * upon the type of the event. This is called by
1191 * <a href="#forwardUpdate">forwardUpdate</a> to forward
1192 * the event to children that need it.
1193 *
1194 * @param v the child view to forward the event to
1195 * @param e the change information from the associated document
1196 * @param a the current allocation of the view
1197 * @param f the factory to use to rebuild if the view has children
1198 * @see #forwardUpdate
1199 * @since 1.3
1200 */
1201 protected void forwardUpdateToView(View v, DocumentEvent e,
1202 Shape a, ViewFactory f) {
1203 DocumentEvent.EventType type = e.getType();
1204 if (type == DocumentEvent.EventType.INSERT) {
1205 v.insertUpdate(e, a, f);
1206 } else if (type == DocumentEvent.EventType.REMOVE) {
1207 v.removeUpdate(e, a, f);
1208 } else {
1209 v.changedUpdate(e, a, f);
1210 }
1211 }
1212
1213 /**
1214 * Updates the layout in response to receiving notification of
1215 * change from the model. This is implemented to call
1216 * <code>preferenceChanged</code> to reschedule a new layout
1217 * if the <code>ElementChange</code> record is not <code>null</code>.
1218 *
1219 * @param ec changes to the element this view is responsible
1220 * for (may be <code>null</code> if there were no changes)
1221 * @param e the change information from the associated document
1222 * @param a the current allocation of the view
1223 * @see #insertUpdate
1224 * @see #removeUpdate
1225 * @see #changedUpdate
1226 * @since 1.3
1227 */
1228 protected void updateLayout(DocumentEvent.ElementChange ec,
1229 DocumentEvent e, Shape a) {
1230 if ((ec != null) && (a != null)) {
1231 // should damage more intelligently
1232 preferenceChanged(null, true, true);
1233 Container host = getContainer();
1234 if (host != null) {
1235 host.repaint();
1236 }
1237 }
1238 }
1239
1240 /**
1241 * The weight to indicate a view is a bad break
1242 * opportunity for the purpose of formatting. This
1243 * value indicates that no attempt should be made to
1244 * break the view into fragments as the view has
1245 * not been written to support fragmenting.
1246 *
1247 * @see #getBreakWeight
1248 * @see #GoodBreakWeight
1249 * @see #ExcellentBreakWeight
1250 * @see #ForcedBreakWeight
1251 */
1252 public static final int BadBreakWeight = 0;
1253
1254 /**
1255 * The weight to indicate a view supports breaking,
1256 * but better opportunities probably exist.
1257 *
1258 * @see #getBreakWeight
1259 * @see #BadBreakWeight
1260 * @see #ExcellentBreakWeight
1261 * @see #ForcedBreakWeight
1262 */
1263 public static final int GoodBreakWeight = 1000;
1264
1265 /**
1266 * The weight to indicate a view supports breaking,
1267 * and this represents a very attractive place to
1268 * break.
1269 *
1270 * @see #getBreakWeight
1271 * @see #BadBreakWeight
1272 * @see #GoodBreakWeight
1273 * @see #ForcedBreakWeight
1274 */
1275 public static final int ExcellentBreakWeight = 2000;
1276
1277 /**
1278 * The weight to indicate a view supports breaking,
1279 * and must be broken to be represented properly
1280 * when placed in a view that formats its children
1281 * by breaking them.
1282 *
1283 * @see #getBreakWeight
1284 * @see #BadBreakWeight
1285 * @see #GoodBreakWeight
1286 * @see #ExcellentBreakWeight
1287 */
1288 public static final int ForcedBreakWeight = 3000;
1289
1290 /**
1291 * Axis for format/break operations.
1292 */
1293 public static final int X_AXIS = HORIZONTAL;
1294
1295 /**
1296 * Axis for format/break operations.
1297 */
1298 public static final int Y_AXIS = VERTICAL;
1299
1300 /**
1301 * Provides a mapping from the document model coordinate space
1302 * to the coordinate space of the view mapped to it. This is
1303 * implemented to default the bias to <code>Position.Bias.Forward</code>
1304 * which was previously implied.
1305 *
1306 * @param pos the position to convert >= 0
1307 * @param a the allocated region in which to render
1308 * @return the bounding box of the given position is returned
1309 * @exception BadLocationException if the given position does
1310 * not represent a valid location in the associated document
1311 * @see View#modelToView
1312 * @deprecated
1313 */
1314 @Deprecated
1315 public Shape modelToView(int pos, Shape a)
1316 throws BadLocationException {
1317 return modelToView(pos, a, Position.Bias.Forward);
1318 }
1319
1320 /**
1321 * Provides a mapping from the view coordinate space to the logical
1322 * coordinate space of the model.
1323 *
1324 * @param x the X coordinate >= 0
1325 * @param y the Y coordinate >= 0
1326 * @param a the allocated region in which to render
1327 * @return the location within the model that best represents the
1328 * given point in the view >= 0
1329 * @see View#viewToModel
1330 * @deprecated
1331 */
1332 @Deprecated
1333 public int viewToModel(float x, float y, Shape a) {
1334 sharedBiasReturn[0] = Position.Bias.Forward;
1335 return viewToModel(x, y, a, sharedBiasReturn);
1336 }
1337
1338 // static argument available for viewToModel calls since only
1339 // one thread at a time may call this method.
1340 static final Position.Bias[] sharedBiasReturn = new Position.Bias[1];
1341
1342 private View parent;
1343 private Element elem;
1344
1345 };
|