1 /* 2 * Copyright (c) 1997, 2013, 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 javax.swing.SwingConstants; 29 import javax.swing.event.*; 30 31 /** 32 * <p> 33 * A very important part of the text package is the <code>View</code> class. 34 * As the name suggests it represents a view of the text model, 35 * or a piece of the text model. 36 * It is this class that is responsible for the look of the text component. 37 * The view is not intended to be some completely new thing that one must 38 * learn, but rather is much like a lightweight component. 39 * <p> 40 By default, a view is very light. It contains a reference to the parent 41 view from which it can fetch many things without holding state, and it 42 contains a reference to a portion of the model (<code>Element</code>). 43 A view does not 44 have to exactly represent an element in the model, that is simply a typical 45 and therefore convenient mapping. A view can alternatively maintain a couple 46 of Position objects to maintain its location in the model (i.e. represent 47 a fragment of an element). This is typically the result of formatting where 48 views have been broken down into pieces. The convenience of a substantial 49 relationship to the element makes it easier to build factories to produce the 50 views, and makes it easier to keep track of the view pieces as the model is 51 changed and the view must be changed to reflect the model. Simple views 52 therefore represent an Element directly and complex views do not. 53 <p> 54 A view has the following responsibilities: 55 <dl> 56 57 <dt><b>Participate in layout.</b> 58 <dd> 59 <p>The view has a <code>setSize</code> method which is like 60 <code>doLayout</code> and <code>setSize</code> in <code>Component</code> combined. 61 The view has a <code>preferenceChanged</code> method which is 62 like <code>invalidate</code> in <code>Component</code> except that one can 63 invalidate just one axis 64 and the child requesting the change is identified. 65 <p>A View expresses the size that it would like to be in terms of three 66 values, a minimum, a preferred, and a maximum span. Layout in a view is 67 can be done independently upon each axis. For a properly functioning View 68 implementation, the minimum span will be <= the preferred span which in turn 69 will be <= the maximum span. 70 </p> 71 <p style="text-align:center"><img src="doc-files/View-flexibility.jpg" 72 alt="The above text describes this graphic."> 73 <p>The minimum set of methods for layout are: 74 <ul> 75 <li>{@link #getMinimumSpan(int) getMinimumSpan} 76 <li>{@link #getPreferredSpan(int) getPreferredSpan} 77 <li>{@link #getMaximumSpan(int) getMaximumSpan} 78 <li>{@link #getAlignment(int) getAlignment} 79 <li>{@link #preferenceChanged(javax.swing.text.View, boolean, boolean) preferenceChanged} 80 <li>{@link #setSize(float, float) setSize} 81 </ul> 82 83 <p>The <code>setSize</code> method should be prepared to be called a number of times 84 (i.e. It may be called even if the size didn't change). 85 The <code>setSize</code> method 86 is generally called to make sure the View layout is complete prior to trying 87 to perform an operation on it that requires an up-to-date layout. A view's 88 size should <em>always</em> be set to a value within the minimum and maximum 89 span specified by that view. Additionally, the view must always call the 90 <code>preferenceChanged</code> method on the parent if it has changed the 91 values for the 92 layout it would like, and expects the parent to honor. The parent View is 93 not required to recognize a change until the <code>preferenceChanged</code> 94 has been sent. 95 This allows parent View implementations to cache the child requirements if 96 desired. The calling sequence looks something like the following: 97 </p> 98 <p style="text-align:center"> 99 <img src="doc-files/View-layout.jpg" 100 alt="Sample calling sequence between parent view and child view: 101 setSize, getMinimum, getPreferred, getMaximum, getAlignment, setSize"> 102 <p>The exact calling sequence is up to the layout functionality of 103 the parent view (if the view has any children). The view may collect 104 the preferences of the children prior to determining what it will give 105 each child, or it might iteratively update the children one at a time. 106 </p> 107 108 <dt><b>Render a portion of the model.</b> 109 <dd> 110 <p>This is done in the paint method, which is pretty much like a component 111 paint method. Views are expected to potentially populate a fairly large 112 tree. A <code>View</code> has the following semantics for rendering: 113 </p> 114 <ul> 115 <li>The view gets its allocation from the parent at paint time, so it 116 must be prepared to redo layout if the allocated area is different from 117 what it is prepared to deal with. 118 <li>The coordinate system is the same as the hosting <code>Component</code> 119 (i.e. the <code>Component</code> returned by the 120 {@link #getContainer getContainer} method). 121 This means a child view lives in the same coordinate system as the parent 122 view unless the parent has explicitly changed the coordinate system. 123 To schedule itself to be repainted a view can call repaint on the hosting 124 <code>Component</code>. 125 <li>The default is to <em>not clip</em> the children. It is more efficient 126 to allow a view to clip only if it really feels it needs clipping. 127 <li>The <code>Graphics</code> object given is not initialized in any way. 128 A view should set any settings needed. 129 <li>A <code>View</code> is inherently transparent. While a view may render into its 130 entire allocation, typically a view does not. Rendering is performed by 131 traversing down the tree of <code>View</code> implementations. 132 Each <code>View</code> is responsible 133 for rendering its children. This behavior is depended upon for thread 134 safety. While view implementations do not necessarily have to be implemented 135 with thread safety in mind, other view implementations that do make use of 136 concurrency can depend upon a tree traversal to guarantee thread safety. 137 <li>The order of views relative to the model is up to the implementation. 138 Although child views will typically be arranged in the same order that they 139 occur in the model, they may be visually arranged in an entirely different 140 order. View implementations may have Z-Order associated with them if the 141 children are overlapping. 142 </ul> 143 <p>The methods for rendering are: 144 <ul> 145 <li>{@link #paint(java.awt.Graphics, java.awt.Shape) paint} 146 </ul> 147 148 <dt><b>Translate between the model and view coordinate systems.</b> 149 <dd> 150 <p>Because the view objects are produced from a factory and therefore cannot 151 necessarily be counted upon to be in a particular pattern, one must be able 152 to perform translation to properly locate spatial representation of the model. 153 The methods for doing this are: 154 <ul> 155 <li>{@link #modelToView(int, javax.swing.text.Position.Bias, int, javax.swing.text.Position.Bias, java.awt.Shape) modelToView} 156 <li>{@link #viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[]) viewToModel} 157 <li>{@link #getDocument() getDocument} 158 <li>{@link #getElement() getElement} 159 <li>{@link #getStartOffset() getStartOffset} 160 <li>{@link #getEndOffset() getEndOffset} 161 </ul> 162 <p>The layout must be valid prior to attempting to make the translation. 163 The translation is not valid, and must not be attempted while changes 164 are being broadcasted from the model via a <code>DocumentEvent</code>. 165 </p> 166 167 <dt><b>Respond to changes from the model.</b> 168 <dd> 169 <p>If the overall view is represented by many pieces (which is the best situation 170 if one want to be able to change the view and write the least amount of new code), 171 it would be impractical to have a huge number of <code>DocumentListener</code>s. 172 If each 173 view listened to the model, only a few would actually be interested in the 174 changes broadcasted at any given time. Since the model has no knowledge of 175 views, it has no way to filter the broadcast of change information. The view 176 hierarchy itself is instead responsible for propagating the change information. 177 At any level in the view hierarchy, that view knows enough about its children to 178 best distribute the change information further. Changes are therefore broadcasted 179 starting from the root of the view hierarchy. 180 The methods for doing this are: 181 <ul> 182 <li>{@link #insertUpdate insertUpdate} 183 <li>{@link #removeUpdate removeUpdate} 184 <li>{@link #changedUpdate changedUpdate} 185 </ul> 186 </dl> 187 * 188 * @author Timothy Prinzing 189 */ 190 public abstract class View implements SwingConstants { 191 192 /** 193 * Creates a new <code>View</code> object. 194 * 195 * @param elem the <code>Element</code> to represent 196 */ 197 public View(Element elem) { 198 this.elem = elem; 199 } 200 201 /** 202 * Returns the parent of the view. 203 * 204 * @return the parent, or <code>null</code> if none exists 205 */ 206 public View getParent() { 207 return parent; 208 } 209 210 /** 211 * Returns a boolean that indicates whether 212 * the view is visible or not. By default 213 * all views are visible. 214 * 215 * @return always returns true 216 */ 217 public boolean isVisible() { 218 return true; 219 } 220 221 222 /** 223 * Determines the preferred span for this view along an 224 * axis. 225 * 226 * @param axis may be either <code>View.X_AXIS</code> or 227 * <code>View.Y_AXIS</code> 228 * @return the span the view would like to be rendered into. 229 * Typically the view is told to render into the span 230 * that is returned, although there is no guarantee. 231 * The parent may choose to resize or break the view 232 * @see View#getPreferredSpan 233 */ 234 public abstract float getPreferredSpan(int axis); 235 236 /** 237 * Determines the minimum span for this view along an 238 * axis. 239 * 240 * @param axis may be either <code>View.X_AXIS</code> or 241 * <code>View.Y_AXIS</code> 242 * @return the minimum span the view can be rendered into 243 * @see View#getPreferredSpan 244 */ 245 public float getMinimumSpan(int axis) { 246 int w = getResizeWeight(axis); 247 if (w == 0) { 248 // can't resize 249 return getPreferredSpan(axis); 250 } 251 return 0; 252 } 253 254 /** 255 * Determines the maximum span for this view along an 256 * axis. 257 * 258 * @param axis may be either <code>View.X_AXIS</code> or 259 * <code>View.Y_AXIS</code> 260 * @return the maximum span the view can be rendered into 261 * @see View#getPreferredSpan 262 */ 263 public float getMaximumSpan(int axis) { 264 int w = getResizeWeight(axis); 265 if (w == 0) { 266 // can't resize 267 return getPreferredSpan(axis); 268 } 269 return Integer.MAX_VALUE; 270 } 271 272 /** 273 * Child views can call this on the parent to indicate that 274 * the preference has changed and should be reconsidered 275 * for layout. By default this just propagates upward to 276 * the next parent. The root view will call 277 * <code>revalidate</code> on the associated text component. 278 * 279 * @param child the child view 280 * @param width true if the width preference has changed 281 * @param height true if the height preference has changed 282 * @see javax.swing.JComponent#revalidate 283 */ 284 public void preferenceChanged(View child, boolean width, boolean height) { 285 View parent = getParent(); 286 if (parent != null) { 287 parent.preferenceChanged(this, width, height); 288 } 289 } 290 291 /** 292 * Determines the desired alignment for this view along an 293 * axis. The desired alignment is returned. This should be 294 * a value >= 0.0 and <= 1.0, where 0 indicates alignment at 295 * the origin and 1.0 indicates alignment to the full span 296 * away from the origin. An alignment of 0.5 would be the 297 * center of the view. 298 * 299 * @param axis may be either <code>View.X_AXIS</code> or 300 * <code>View.Y_AXIS</code> 301 * @return the value 0.5 302 */ 303 public float getAlignment(int axis) { 304 return 0.5f; 305 } 306 307 /** 308 * Renders using the given rendering surface and area on that 309 * surface. The view may need to do layout and create child 310 * views to enable itself to render into the given allocation. 311 * 312 * @param g the rendering surface to use 313 * @param allocation the allocated region to render into 314 */ 315 public abstract void paint(Graphics g, Shape allocation); 316 317 /** 318 * Establishes the parent view for this view. This is 319 * guaranteed to be called before any other methods if the 320 * parent view is functioning properly. This is also 321 * the last method called, since it is called to indicate 322 * the view has been removed from the hierarchy as 323 * well. When this method is called to set the parent to 324 * null, this method does the same for each of its children, 325 * propagating the notification that they have been 326 * disconnected from the view tree. If this is 327 * reimplemented, <code>super.setParent()</code> should 328 * be called. 329 * 330 * @param parent the new parent, or <code>null</code> if the view is 331 * being removed from a parent 332 */ 333 public void setParent(View parent) { 334 // if the parent is null then propogate down the view tree 335 if (parent == null) { 336 for (int i = 0; i < getViewCount(); i++) { 337 if (getView(i).getParent() == this) { 338 // in FlowView.java view might be referenced 339 // from two super-views as a child. see logicalView 340 getView(i).setParent(null); 341 } 342 } 343 } 344 this.parent = parent; 345 } 346 347 /** 348 * Returns the number of views in this view. Since 349 * the default is to not be a composite view this 350 * returns 0. 351 * 352 * @return the number of views >= 0 353 * @see View#getViewCount 354 */ 355 public int getViewCount() { 356 return 0; 357 } 358 359 /** 360 * Gets the <i>n</i>th child view. Since there are no 361 * children by default, this returns <code>null</code>. 362 * 363 * @param n the number of the view to get, >= 0 && < getViewCount() 364 * @return the view 365 */ 366 public View getView(int n) { 367 return null; 368 } 369 370 371 /** 372 * Removes all of the children. This is a convenience 373 * call to <code>replace</code>. 374 * 375 * @since 1.3 376 */ 377 public void removeAll() { 378 replace(0, getViewCount(), null); 379 } 380 381 /** 382 * Removes one of the children at the given position. 383 * This is a convenience call to <code>replace</code>. 384 * @since 1.3 385 */ 386 public void remove(int i) { 387 replace(i, 1, null); 388 } 389 390 /** 391 * Inserts a single child view. This is a convenience 392 * call to <code>replace</code>. 393 * 394 * @param offs the offset of the view to insert before >= 0 395 * @param v the view 396 * @see #replace 397 * @since 1.3 398 */ 399 public void insert(int offs, View v) { 400 View[] one = new View[1]; 401 one[0] = v; 402 replace(offs, 0, one); 403 } 404 405 /** 406 * Appends a single child view. This is a convenience 407 * call to <code>replace</code>. 408 * 409 * @param v the view 410 * @see #replace 411 * @since 1.3 412 */ 413 public void append(View v) { 414 View[] one = new View[1]; 415 one[0] = v; 416 replace(getViewCount(), 0, one); 417 } 418 419 /** 420 * Replaces child views. If there are no views to remove 421 * this acts as an insert. If there are no views to 422 * add this acts as a remove. Views being removed will 423 * have the parent set to <code>null</code>, and the internal reference 424 * to them removed so that they can be garbage collected. 425 * This is implemented to do nothing, because by default 426 * a view has no children. 427 * 428 * @param offset the starting index into the child views to insert 429 * the new views. This should be a value >= 0 and <= getViewCount 430 * @param length the number of existing child views to remove 431 * This should be a value >= 0 and <= (getViewCount() - offset). 432 * @param views the child views to add. This value can be 433 * <code>null</code> to indicate no children are being added 434 * (useful to remove). 435 * @since 1.3 436 */ 437 public void replace(int offset, int length, View[] views) { 438 } 439 440 /** 441 * Returns the child view index representing the given position in 442 * the model. By default a view has no children so this is implemented 443 * to return -1 to indicate there is no valid child index for any 444 * position. 445 * 446 * @param pos the position >= 0 447 * @return index of the view representing the given position, or 448 * -1 if no view represents that position 449 * @since 1.3 450 */ 451 public int getViewIndex(int pos, Position.Bias b) { 452 return -1; 453 } 454 455 /** 456 * Fetches the allocation for the given child view. 457 * This enables finding out where various views 458 * are located, without assuming how the views store 459 * their location. This returns <code>null</code> since the 460 * default is to not have any child views. 461 * 462 * @param index the index of the child, >= 0 && < 463 * <code>getViewCount()</code> 464 * @param a the allocation to this view 465 * @return the allocation to the child 466 */ 467 public Shape getChildAllocation(int index, Shape a) { 468 return null; 469 } 470 471 /** 472 * Provides a way to determine the next visually represented model 473 * location at which one might place a caret. 474 * Some views may not be visible, 475 * they might not be in the same order found in the model, or they just 476 * might not allow access to some of the locations in the model. 477 * This method enables specifying a position to convert 478 * within the range of >=0. If the value is -1, a position 479 * will be calculated automatically. If the value < -1, 480 * the {@code BadLocationException} will be thrown. 481 * 482 * @param pos the position to convert 483 * @param a the allocated region in which to render 484 * @param direction the direction from the current position that can 485 * be thought of as the arrow keys typically found on a keyboard. 486 * This will be one of the following values: 487 * <ul> 488 * <li>SwingConstants.WEST 489 * <li>SwingConstants.EAST 490 * <li>SwingConstants.NORTH 491 * <li>SwingConstants.SOUTH 492 * </ul> 493 * @return the location within the model that best represents the next 494 * location visual position 495 * @exception BadLocationException the given position is not a valid 496 * position within the document 497 * @exception IllegalArgumentException if <code>direction</code> 498 * doesn't have one of the legal values above 499 */ 500 public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, 501 int direction, Position.Bias[] biasRet) 502 throws BadLocationException { 503 if (pos < -1 || pos > getDocument().getLength()) { 504 // -1 is a reserved value, see the code below 505 throw new BadLocationException("Invalid position", pos); 506 } 507 508 biasRet[0] = Position.Bias.Forward; 509 switch (direction) { 510 case NORTH: 511 case SOUTH: 512 { 513 if (pos == -1) { 514 pos = (direction == NORTH) ? Math.max(0, getEndOffset() - 1) : 515 getStartOffset(); 516 break; 517 } 518 JTextComponent target = (JTextComponent) getContainer(); 519 Caret c = (target != null) ? target.getCaret() : null; 520 // YECK! Ideally, the x location from the magic caret position 521 // would be passed in. 522 Point mcp; 523 if (c != null) { 524 mcp = c.getMagicCaretPosition(); 525 } 526 else { 527 mcp = null; 528 } 529 int x; 530 if (mcp == null) { 531 Rectangle loc = target.modelToView(pos); 532 x = (loc == null) ? 0 : loc.x; 533 } 534 else { 535 x = mcp.x; 536 } 537 if (direction == NORTH) { 538 pos = Utilities.getPositionAbove(target, pos, x); 539 } 540 else { 541 pos = Utilities.getPositionBelow(target, pos, x); 542 } 543 } 544 break; 545 case WEST: 546 if(pos == -1) { 547 pos = Math.max(0, getEndOffset() - 1); 548 } 549 else { 550 pos = Math.max(0, pos - 1); 551 } 552 break; 553 case EAST: 554 if(pos == -1) { 555 pos = getStartOffset(); 556 } 557 else { 558 pos = Math.min(pos + 1, getDocument().getLength()); 559 } 560 break; 561 default: 562 throw new IllegalArgumentException("Bad direction: " + direction); 563 } 564 return pos; 565 } 566 567 /** 568 * Provides a mapping, for a given character, 569 * from the document model coordinate space 570 * to the view coordinate space. 571 * 572 * @param pos the position of the desired character (>=0) 573 * @param a the area of the view, which encompasses the requested character 574 * @param b the bias toward the previous character or the 575 * next character represented by the offset, in case the 576 * position is a boundary of two views; <code>b</code> will have one 577 * of these values: 578 * <ul> 579 * <li> <code>Position.Bias.Forward</code> 580 * <li> <code>Position.Bias.Backward</code> 581 * </ul> 582 * @return the bounding box, in view coordinate space, 583 * of the character at the specified position 584 * @exception BadLocationException if the specified position does 585 * not represent a valid location in the associated document 586 * @exception IllegalArgumentException if <code>b</code> is not one of the 587 * legal <code>Position.Bias</code> values listed above 588 * @see View#viewToModel 589 */ 590 public abstract Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException; 591 592 /** 593 * Provides a mapping, for a given region, 594 * from the document model coordinate space 595 * to the view coordinate space. The specified region is 596 * created as a union of the first and last character positions. 597 * 598 * @param p0 the position of the first character (>=0) 599 * @param b0 the bias of the first character position, 600 * toward the previous character or the 601 * next character represented by the offset, in case the 602 * position is a boundary of two views; <code>b0</code> will have one 603 * of these values: 604 * <ul style="list-style-type:none"> 605 * <li> <code>Position.Bias.Forward</code> 606 * <li> <code>Position.Bias.Backward</code> 607 * </ul> 608 * @param p1 the position of the last character (>=0) 609 * @param b1 the bias for the second character position, defined 610 * one of the legal values shown above 611 * @param a the area of the view, which encompasses the requested region 612 * @return the bounding box which is a union of the region specified 613 * by the first and last character positions 614 * @exception BadLocationException if the given position does 615 * not represent a valid location in the associated document 616 * @exception IllegalArgumentException if <code>b0</code> or 617 * <code>b1</code> are not one of the 618 * legal <code>Position.Bias</code> values listed above 619 * @see View#viewToModel 620 */ 621 public Shape modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) throws BadLocationException { 622 Shape s0 = modelToView(p0, a, b0); 623 Shape s1; 624 if (p1 == getEndOffset()) { 625 try { 626 s1 = modelToView(p1, a, b1); 627 } catch (BadLocationException ble) { 628 s1 = null; 629 } 630 if (s1 == null) { 631 // Assume extends left to right. 632 Rectangle alloc = (a instanceof Rectangle) ? (Rectangle)a : 633 a.getBounds(); 634 s1 = new Rectangle(alloc.x + alloc.width - 1, alloc.y, 635 1, alloc.height); 636 } 637 } 638 else { 639 s1 = modelToView(p1, a, b1); 640 } 641 Rectangle r0 = s0.getBounds(); 642 Rectangle r1 = (s1 instanceof Rectangle) ? (Rectangle) s1 : 643 s1.getBounds(); 644 if (r0.y != r1.y) { 645 // If it spans lines, force it to be the width of the view. 646 Rectangle alloc = (a instanceof Rectangle) ? (Rectangle)a : 647 a.getBounds(); 648 r0.x = alloc.x; 649 r0.width = alloc.width; 650 } 651 r0.add(r1); 652 return r0; 653 } 654 655 /** 656 * Provides a mapping from the view coordinate space to the logical 657 * coordinate space of the model. The <code>biasReturn</code> 658 * argument will be filled in to indicate that the point given is 659 * closer to the next character in the model or the previous 660 * character in the model. 661 * 662 * @param x the X coordinate >= 0 663 * @param y the Y coordinate >= 0 664 * @param a the allocated region in which to render 665 * @return the location within the model that best represents the 666 * given point in the view >= 0. The <code>biasReturn</code> 667 * argument will be 668 * filled in to indicate that the point given is closer to the next 669 * character in the model or the previous character in the model. 670 */ 671 public abstract int viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn); 672 673 /** 674 * Gives notification that something was inserted into 675 * the document in a location that this view is responsible for. 676 * To reduce the burden to subclasses, this functionality is 677 * spread out into the following calls that subclasses can 678 * reimplement: 679 * <ol> 680 * <li>{@link #updateChildren updateChildren} is called 681 * if there were any changes to the element this view is 682 * responsible for. If this view has child views that are 683 * represent the child elements, then this method should do 684 * whatever is necessary to make sure the child views correctly 685 * represent the model. 686 * <li>{@link #forwardUpdate forwardUpdate} is called 687 * to forward the DocumentEvent to the appropriate child views. 688 * <li>{@link #updateLayout updateLayout} is called to 689 * give the view a chance to either repair its layout, to reschedule 690 * layout, or do nothing. 691 * </ol> 692 * 693 * @param e the change information from the associated document 694 * @param a the current allocation of the view 695 * @param f the factory to use to rebuild if the view has children 696 * @see View#insertUpdate 697 */ 698 public void insertUpdate(DocumentEvent e, Shape a, ViewFactory f) { 699 if (getViewCount() > 0) { 700 Element elem = getElement(); 701 DocumentEvent.ElementChange ec = e.getChange(elem); 702 if (ec != null) { 703 if (! updateChildren(ec, e, f)) { 704 // don't consider the element changes they 705 // are for a view further down. 706 ec = null; 707 } 708 } 709 forwardUpdate(ec, e, a, f); 710 updateLayout(ec, e, a); 711 } 712 } 713 714 /** 715 * Gives notification that something was removed from the document 716 * in a location that this view is responsible for. 717 * To reduce the burden to subclasses, this functionality is 718 * spread out into the following calls that subclasses can 719 * reimplement: 720 * <ol> 721 * <li>{@link #updateChildren updateChildren} is called 722 * if there were any changes to the element this view is 723 * responsible for. If this view has child views that are 724 * represent the child elements, then this method should do 725 * whatever is necessary to make sure the child views correctly 726 * represent the model. 727 * <li>{@link #forwardUpdate forwardUpdate} is called 728 * to forward the DocumentEvent to the appropriate child views. 729 * <li>{@link #updateLayout updateLayout} is called to 730 * give the view a chance to either repair its layout, to reschedule 731 * layout, or do nothing. 732 * </ol> 733 * 734 * @param e the change information from the associated document 735 * @param a the current allocation of the view 736 * @param f the factory to use to rebuild if the view has children 737 * @see View#removeUpdate 738 */ 739 public void removeUpdate(DocumentEvent e, Shape a, ViewFactory f) { 740 if (getViewCount() > 0) { 741 Element elem = getElement(); 742 DocumentEvent.ElementChange ec = e.getChange(elem); 743 if (ec != null) { 744 if (! updateChildren(ec, e, f)) { 745 // don't consider the element changes they 746 // are for a view further down. 747 ec = null; 748 } 749 } 750 forwardUpdate(ec, e, a, f); 751 updateLayout(ec, e, a); 752 } 753 } 754 755 /** 756 * Gives notification from the document that attributes were changed 757 * in a location that this view is responsible for. 758 * To reduce the burden to subclasses, this functionality is 759 * spread out into the following calls that subclasses can 760 * reimplement: 761 * <ol> 762 * <li>{@link #updateChildren updateChildren} is called 763 * if there were any changes to the element this view is 764 * responsible for. If this view has child views that are 765 * represent the child elements, then this method should do 766 * whatever is necessary to make sure the child views correctly 767 * represent the model. 768 * <li>{@link #forwardUpdate forwardUpdate} is called 769 * to forward the DocumentEvent to the appropriate child views. 770 * <li>{@link #updateLayout updateLayout} is called to 771 * give the view a chance to either repair its layout, to reschedule 772 * layout, or do nothing. 773 * </ol> 774 * 775 * @param e the change information from the associated document 776 * @param a the current allocation of the view 777 * @param f the factory to use to rebuild if the view has children 778 * @see View#changedUpdate 779 */ 780 public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) { 781 if (getViewCount() > 0) { 782 Element elem = getElement(); 783 DocumentEvent.ElementChange ec = e.getChange(elem); 784 if (ec != null) { 785 if (! updateChildren(ec, e, f)) { 786 // don't consider the element changes they 787 // are for a view further down. 788 ec = null; 789 } 790 } 791 forwardUpdate(ec, e, a, f); 792 updateLayout(ec, e, a); 793 } 794 } 795 796 /** 797 * Fetches the model associated with the view. 798 * 799 * @return the view model, <code>null</code> if none 800 * @see View#getDocument 801 */ 802 public Document getDocument() { 803 return elem.getDocument(); 804 } 805 806 /** 807 * Fetches the portion of the model for which this view is 808 * responsible. 809 * 810 * @return the starting offset into the model >= 0 811 * @see View#getStartOffset 812 */ 813 public int getStartOffset() { 814 return elem.getStartOffset(); 815 } 816 817 /** 818 * Fetches the portion of the model for which this view is 819 * responsible. 820 * 821 * @return the ending offset into the model >= 0 822 * @see View#getEndOffset 823 */ 824 public int getEndOffset() { 825 return elem.getEndOffset(); 826 } 827 828 /** 829 * Fetches the structural portion of the subject that this 830 * view is mapped to. The view may not be responsible for the 831 * entire portion of the element. 832 * 833 * @return the subject 834 * @see View#getElement 835 */ 836 public Element getElement() { 837 return elem; 838 } 839 840 /** 841 * Fetch a <code>Graphics</code> for rendering. 842 * This can be used to determine 843 * font characteristics, and will be different for a print view 844 * than a component view. 845 * 846 * @return a <code>Graphics</code> object for rendering 847 * @since 1.3 848 */ 849 public Graphics getGraphics() { 850 // PENDING(prinz) this is a temporary implementation 851 Component c = getContainer(); 852 return c.getGraphics(); 853 } 854 855 /** 856 * Fetches the attributes to use when rendering. By default 857 * this simply returns the attributes of the associated element. 858 * This method should be used rather than using the element 859 * directly to obtain access to the attributes to allow 860 * view-specific attributes to be mixed in or to allow the 861 * view to have view-specific conversion of attributes by 862 * subclasses. 863 * Each view should document what attributes it recognizes 864 * for the purpose of rendering or layout, and should always 865 * access them through the <code>AttributeSet</code> returned 866 * by this method. 867 */ 868 public AttributeSet getAttributes() { 869 return elem.getAttributes(); 870 } 871 872 /** 873 * Tries to break this view on the given axis. This is 874 * called by views that try to do formatting of their 875 * children. For example, a view of a paragraph will 876 * typically try to place its children into row and 877 * views representing chunks of text can sometimes be 878 * broken down into smaller pieces. 879 * <p> 880 * This is implemented to return the view itself, which 881 * represents the default behavior on not being 882 * breakable. If the view does support breaking, the 883 * starting offset of the view returned should be the 884 * given offset, and the end offset should be less than 885 * or equal to the end offset of the view being broken. 886 * 887 * @param axis may be either <code>View.X_AXIS</code> or 888 * <code>View.Y_AXIS</code> 889 * @param offset the location in the document model 890 * that a broken fragment would occupy >= 0. This 891 * would be the starting offset of the fragment 892 * returned 893 * @param pos the position along the axis that the 894 * broken view would occupy >= 0. This may be useful for 895 * things like tab calculations 896 * @param len specifies the distance along the axis 897 * where a potential break is desired >= 0 898 * @return the fragment of the view that represents the 899 * given span, if the view can be broken. If the view 900 * doesn't support breaking behavior, the view itself is 901 * returned. 902 * @see ParagraphView 903 */ 904 public View breakView(int axis, int offset, float pos, float len) { 905 return this; 906 } 907 908 /** 909 * Creates a view that represents a portion of the element. 910 * This is potentially useful during formatting operations 911 * for taking measurements of fragments of the view. If 912 * the view doesn't support fragmenting (the default), it 913 * should return itself. 914 * 915 * @param p0 the starting offset >= 0. This should be a value 916 * greater or equal to the element starting offset and 917 * less than the element ending offset. 918 * @param p1 the ending offset > p0. This should be a value 919 * less than or equal to the elements end offset and 920 * greater than the elements starting offset. 921 * @return the view fragment, or itself if the view doesn't 922 * support breaking into fragments 923 * @see LabelView 924 */ 925 public View createFragment(int p0, int p1) { 926 return this; 927 } 928 929 /** 930 * Determines how attractive a break opportunity in 931 * this view is. This can be used for determining which 932 * view is the most attractive to call <code>breakView</code> 933 * on in the process of formatting. A view that represents 934 * text that has whitespace in it might be more attractive 935 * than a view that has no whitespace, for example. The 936 * higher the weight, the more attractive the break. A 937 * value equal to or lower than <code>BadBreakWeight</code> 938 * should not be considered for a break. A value greater 939 * than or equal to <code>ForcedBreakWeight</code> should 940 * be broken. 941 * <p> 942 * This is implemented to provide the default behavior 943 * of returning <code>BadBreakWeight</code> unless the length 944 * is greater than the length of the view in which case the 945 * entire view represents the fragment. Unless a view has 946 * been written to support breaking behavior, it is not 947 * attractive to try and break the view. An example of 948 * a view that does support breaking is <code>LabelView</code>. 949 * An example of a view that uses break weight is 950 * <code>ParagraphView</code>. 951 * 952 * @param axis may be either <code>View.X_AXIS</code> or 953 * <code>View.Y_AXIS</code> 954 * @param pos the potential location of the start of the 955 * broken view >= 0. This may be useful for calculating tab 956 * positions 957 * @param len specifies the relative length from <em>pos</em> 958 * where a potential break is desired >= 0 959 * @return the weight, which should be a value between 960 * ForcedBreakWeight and BadBreakWeight 961 * @see LabelView 962 * @see ParagraphView 963 * @see #BadBreakWeight 964 * @see #GoodBreakWeight 965 * @see #ExcellentBreakWeight 966 * @see #ForcedBreakWeight 967 */ 968 public int getBreakWeight(int axis, float pos, float len) { 969 if (len > getPreferredSpan(axis)) { 970 return GoodBreakWeight; 971 } 972 return BadBreakWeight; 973 } 974 975 /** 976 * Determines the resizability of the view along the 977 * given axis. A value of 0 or less is not resizable. 978 * 979 * @param axis may be either <code>View.X_AXIS</code> or 980 * <code>View.Y_AXIS</code> 981 * @return the weight 982 */ 983 public int getResizeWeight(int axis) { 984 return 0; 985 } 986 987 /** 988 * Sets the size of the view. This should cause 989 * layout of the view along the given axis, if it 990 * has any layout duties. 991 * 992 * @param width the width >= 0 993 * @param height the height >= 0 994 */ 995 public void setSize(float width, float height) { 996 } 997 998 /** 999 * Fetches the container hosting the view. This is useful for 1000 * things like scheduling a repaint, finding out the host 1001 * components font, etc. The default implementation 1002 * of this is to forward the query to the parent view. 1003 * 1004 * @return the container, <code>null</code> if none 1005 */ 1006 public Container getContainer() { 1007 View v = getParent(); 1008 return (v != null) ? v.getContainer() : null; 1009 } 1010 1011 /** 1012 * Fetches the <code>ViewFactory</code> implementation that is feeding 1013 * the view hierarchy. Normally the views are given this 1014 * as an argument to updates from the model when they 1015 * are most likely to need the factory, but this 1016 * method serves to provide it at other times. 1017 * 1018 * @return the factory, <code>null</code> if none 1019 */ 1020 public ViewFactory getViewFactory() { 1021 View v = getParent(); 1022 return (v != null) ? v.getViewFactory() : null; 1023 } 1024 1025 /** 1026 * Returns the tooltip text at the specified location. The default 1027 * implementation returns the value from the child View identified by 1028 * the passed in location. 1029 * 1030 * @since 1.4 1031 * @see JTextComponent#getToolTipText 1032 */ 1033 public String getToolTipText(float x, float y, Shape allocation) { 1034 int viewIndex = getViewIndex(x, y, allocation); 1035 if (viewIndex >= 0) { 1036 allocation = getChildAllocation(viewIndex, allocation); 1037 Rectangle rect = (allocation instanceof Rectangle) ? 1038 (Rectangle)allocation : allocation.getBounds(); 1039 if (rect.contains(x, y)) { 1040 return getView(viewIndex).getToolTipText(x, y, allocation); 1041 } 1042 } 1043 return null; 1044 } 1045 1046 /** 1047 * Returns the child view index representing the given position in 1048 * the view. This iterates over all the children returning the 1049 * first with a bounds that contains <code>x</code>, <code>y</code>. 1050 * 1051 * @param x the x coordinate 1052 * @param y the y coordinate 1053 * @param allocation current allocation of the View. 1054 * @return index of the view representing the given location, or 1055 * -1 if no view represents that position 1056 * @since 1.4 1057 */ 1058 public int getViewIndex(float x, float y, Shape allocation) { 1059 for (int counter = getViewCount() - 1; counter >= 0; counter--) { 1060 Shape childAllocation = getChildAllocation(counter, allocation); 1061 1062 if (childAllocation != null) { 1063 Rectangle rect = (childAllocation instanceof Rectangle) ? 1064 (Rectangle)childAllocation : childAllocation.getBounds(); 1065 1066 if (rect.contains(x, y)) { 1067 return counter; 1068 } 1069 } 1070 } 1071 return -1; 1072 } 1073 1074 /** 1075 * Updates the child views in response to receiving notification 1076 * that the model changed, and there is change record for the 1077 * element this view is responsible for. This is implemented 1078 * to assume the child views are directly responsible for the 1079 * child elements of the element this view represents. The 1080 * <code>ViewFactory</code> is used to create child views for each element 1081 * specified as added in the <code>ElementChange</code>, starting at the 1082 * index specified in the given <code>ElementChange</code>. The number of 1083 * child views representing the removed elements specified are 1084 * removed. 1085 * 1086 * @param ec the change information for the element this view 1087 * is responsible for. This should not be <code>null</code> if 1088 * this method gets called 1089 * @param e the change information from the associated document 1090 * @param f the factory to use to build child views 1091 * @return whether or not the child views represent the 1092 * child elements of the element this view is responsible 1093 * for. Some views create children that represent a portion 1094 * of the element they are responsible for, and should return 1095 * false. This information is used to determine if views 1096 * in the range of the added elements should be forwarded to 1097 * or not 1098 * @see #insertUpdate 1099 * @see #removeUpdate 1100 * @see #changedUpdate 1101 * @since 1.3 1102 */ 1103 protected boolean updateChildren(DocumentEvent.ElementChange ec, 1104 DocumentEvent e, ViewFactory f) { 1105 Element[] removedElems = ec.getChildrenRemoved(); 1106 Element[] addedElems = ec.getChildrenAdded(); 1107 View[] added = null; 1108 if (addedElems != null) { 1109 added = new View[addedElems.length]; 1110 for (int i = 0; i < addedElems.length; i++) { 1111 added[i] = f.create(addedElems[i]); 1112 } 1113 } 1114 int nremoved = 0; 1115 int index = ec.getIndex(); 1116 if (removedElems != null) { 1117 nremoved = removedElems.length; 1118 } 1119 replace(index, nremoved, added); 1120 return true; 1121 } 1122 1123 /** 1124 * Forwards the given <code>DocumentEvent</code> to the child views 1125 * that need to be notified of the change to the model. 1126 * If there were changes to the element this view is 1127 * responsible for, that should be considered when 1128 * forwarding (i.e. new child views should not get 1129 * notified). 1130 * 1131 * @param ec changes to the element this view is responsible 1132 * for (may be <code>null</code> if there were no changes). 1133 * @param e the change information from the associated document 1134 * @param a the current allocation of the view 1135 * @param f the factory to use to rebuild if the view has children 1136 * @see #insertUpdate 1137 * @see #removeUpdate 1138 * @see #changedUpdate 1139 * @since 1.3 1140 */ 1141 protected void forwardUpdate(DocumentEvent.ElementChange ec, 1142 DocumentEvent e, Shape a, ViewFactory f) { 1143 calculateUpdateIndexes(e); 1144 1145 int hole0 = lastUpdateIndex + 1; 1146 int hole1 = hole0; 1147 Element[] addedElems = (ec != null) ? ec.getChildrenAdded() : null; 1148 if ((addedElems != null) && (addedElems.length > 0)) { 1149 hole0 = ec.getIndex(); 1150 hole1 = hole0 + addedElems.length - 1; 1151 } 1152 1153 // forward to any view not in the forwarding hole 1154 // formed by added elements (i.e. they will be updated 1155 // by initialization. 1156 for (int i = firstUpdateIndex; i <= lastUpdateIndex; i++) { 1157 if (! ((i >= hole0) && (i <= hole1))) { 1158 View v = getView(i); 1159 if (v != null) { 1160 Shape childAlloc = getChildAllocation(i, a); 1161 forwardUpdateToView(v, e, childAlloc, f); 1162 } 1163 } 1164 } 1165 } 1166 1167 /** 1168 * Calculates the first and the last indexes of the child views 1169 * that need to be notified of the change to the model. 1170 * @param e the change information from the associated document 1171 */ 1172 void calculateUpdateIndexes(DocumentEvent e) { 1173 int pos = e.getOffset(); 1174 firstUpdateIndex = getViewIndex(pos, Position.Bias.Forward); 1175 if (firstUpdateIndex == -1 && e.getType() == DocumentEvent.EventType.REMOVE && 1176 pos >= getEndOffset()) { 1177 // Event beyond our offsets. We may have represented this, that is 1178 // the remove may have removed one of our child Elements that 1179 // represented this, so, we should forward to last element. 1180 firstUpdateIndex = getViewCount() - 1; 1181 } 1182 lastUpdateIndex = firstUpdateIndex; 1183 View v = (firstUpdateIndex >= 0) ? getView(firstUpdateIndex) : null; 1184 if (v != null) { 1185 if ((v.getStartOffset() == pos) && (pos > 0)) { 1186 // If v is at a boundary, forward the event to the previous 1187 // view too. 1188 firstUpdateIndex = Math.max(firstUpdateIndex - 1, 0); 1189 } 1190 } 1191 if (e.getType() != DocumentEvent.EventType.REMOVE) { 1192 lastUpdateIndex = getViewIndex(pos + e.getLength(), Position.Bias.Forward); 1193 if (lastUpdateIndex < 0) { 1194 lastUpdateIndex = getViewCount() - 1; 1195 } 1196 } 1197 firstUpdateIndex = Math.max(firstUpdateIndex, 0); 1198 } 1199 1200 /** 1201 * Updates the view to reflect the changes. 1202 */ 1203 void updateAfterChange() { 1204 // Do nothing by default. Should be overridden in subclasses, if any. 1205 } 1206 1207 /** 1208 * Forwards the <code>DocumentEvent</code> to the give child view. This 1209 * simply messages the view with a call to <code>insertUpdate</code>, 1210 * <code>removeUpdate</code>, or <code>changedUpdate</code> depending 1211 * upon the type of the event. This is called by 1212 * {@link #forwardUpdate forwardUpdate} to forward 1213 * the event to children that need it. 1214 * 1215 * @param v the child view to forward the event to 1216 * @param e the change information from the associated document 1217 * @param a the current allocation of the view 1218 * @param f the factory to use to rebuild if the view has children 1219 * @see #forwardUpdate 1220 * @since 1.3 1221 */ 1222 protected void forwardUpdateToView(View v, DocumentEvent e, 1223 Shape a, ViewFactory f) { 1224 DocumentEvent.EventType type = e.getType(); 1225 if (type == DocumentEvent.EventType.INSERT) { 1226 v.insertUpdate(e, a, f); 1227 } else if (type == DocumentEvent.EventType.REMOVE) { 1228 v.removeUpdate(e, a, f); 1229 } else { 1230 v.changedUpdate(e, a, f); 1231 } 1232 } 1233 1234 /** 1235 * Updates the layout in response to receiving notification of 1236 * change from the model. This is implemented to call 1237 * <code>preferenceChanged</code> to reschedule a new layout 1238 * if the <code>ElementChange</code> record is not <code>null</code>. 1239 * 1240 * @param ec changes to the element this view is responsible 1241 * for (may be <code>null</code> if there were no changes) 1242 * @param e the change information from the associated document 1243 * @param a the current allocation of the view 1244 * @see #insertUpdate 1245 * @see #removeUpdate 1246 * @see #changedUpdate 1247 * @since 1.3 1248 */ 1249 protected void updateLayout(DocumentEvent.ElementChange ec, 1250 DocumentEvent e, Shape a) { 1251 if ((ec != null) && (a != null)) { 1252 // should damage more intelligently 1253 preferenceChanged(null, true, true); 1254 Container host = getContainer(); 1255 if (host != null) { 1256 host.repaint(); 1257 } 1258 } 1259 } 1260 1261 /** 1262 * The weight to indicate a view is a bad break 1263 * opportunity for the purpose of formatting. This 1264 * value indicates that no attempt should be made to 1265 * break the view into fragments as the view has 1266 * not been written to support fragmenting. 1267 * 1268 * @see #getBreakWeight 1269 * @see #GoodBreakWeight 1270 * @see #ExcellentBreakWeight 1271 * @see #ForcedBreakWeight 1272 */ 1273 public static final int BadBreakWeight = 0; 1274 1275 /** 1276 * The weight to indicate a view supports breaking, 1277 * but better opportunities probably exist. 1278 * 1279 * @see #getBreakWeight 1280 * @see #BadBreakWeight 1281 * @see #ExcellentBreakWeight 1282 * @see #ForcedBreakWeight 1283 */ 1284 public static final int GoodBreakWeight = 1000; 1285 1286 /** 1287 * The weight to indicate a view supports breaking, 1288 * and this represents a very attractive place to 1289 * break. 1290 * 1291 * @see #getBreakWeight 1292 * @see #BadBreakWeight 1293 * @see #GoodBreakWeight 1294 * @see #ForcedBreakWeight 1295 */ 1296 public static final int ExcellentBreakWeight = 2000; 1297 1298 /** 1299 * The weight to indicate a view supports breaking, 1300 * and must be broken to be represented properly 1301 * when placed in a view that formats its children 1302 * by breaking them. 1303 * 1304 * @see #getBreakWeight 1305 * @see #BadBreakWeight 1306 * @see #GoodBreakWeight 1307 * @see #ExcellentBreakWeight 1308 */ 1309 public static final int ForcedBreakWeight = 3000; 1310 1311 /** 1312 * Axis for format/break operations. 1313 */ 1314 public static final int X_AXIS = HORIZONTAL; 1315 1316 /** 1317 * Axis for format/break operations. 1318 */ 1319 public static final int Y_AXIS = VERTICAL; 1320 1321 /** 1322 * Provides a mapping from the document model coordinate space 1323 * to the coordinate space of the view mapped to it. This is 1324 * implemented to default the bias to <code>Position.Bias.Forward</code> 1325 * which was previously implied. 1326 * 1327 * @param pos the position to convert >= 0 1328 * @param a the allocated region in which to render 1329 * @return the bounding box of the given position is returned 1330 * @exception BadLocationException if the given position does 1331 * not represent a valid location in the associated document 1332 * @see View#modelToView 1333 * @deprecated 1334 */ 1335 @Deprecated 1336 public Shape modelToView(int pos, Shape a) throws BadLocationException { 1337 return modelToView(pos, a, Position.Bias.Forward); 1338 } 1339 1340 1341 /** 1342 * Provides a mapping from the view coordinate space to the logical 1343 * coordinate space of the model. 1344 * 1345 * @param x the X coordinate >= 0 1346 * @param y the Y coordinate >= 0 1347 * @param a the allocated region in which to render 1348 * @return the location within the model that best represents the 1349 * given point in the view >= 0 1350 * @see View#viewToModel 1351 * @deprecated 1352 */ 1353 @Deprecated 1354 public int viewToModel(float x, float y, Shape a) { 1355 sharedBiasReturn[0] = Position.Bias.Forward; 1356 return viewToModel(x, y, a, sharedBiasReturn); 1357 } 1358 1359 // static argument available for viewToModel calls since only 1360 // one thread at a time may call this method. 1361 static final Position.Bias[] sharedBiasReturn = new Position.Bias[1]; 1362 1363 private View parent; 1364 private Element elem; 1365 1366 /** 1367 * The index of the first child view to be notified. 1368 */ 1369 int firstUpdateIndex; 1370 1371 /** 1372 * The index of the last child view to be notified. 1373 */ 1374 int lastUpdateIndex; 1375 1376 };