1 /* 2 * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package javax.swing.text; 26 27 import java.awt.*; 28 import java.awt.event.*; 29 import java.awt.datatransfer.*; 30 import java.beans.*; 31 import java.awt.event.ActionEvent; 32 import java.awt.event.ActionListener; 33 import java.io.*; 34 import javax.swing.*; 35 import javax.swing.event.*; 36 import javax.swing.plaf.*; 37 import java.util.EventListener; 38 import sun.swing.SwingUtilities2; 39 40 /** 41 * A default implementation of Caret. The caret is rendered as 42 * a vertical line in the color specified by the CaretColor property 43 * of the associated JTextComponent. It can blink at the rate specified 44 * by the BlinkRate property. 45 * <p> 46 * This implementation expects two sources of asynchronous notification. 47 * The timer thread fires asynchronously, and causes the caret to simply 48 * repaint the most recent bounding box. The caret also tracks change 49 * as the document is modified. Typically this will happen on the 50 * event dispatch thread as a result of some mouse or keyboard event. 51 * The caret behavior on both synchronous and asynchronous documents updates 52 * is controlled by <code>UpdatePolicy</code> property. The repaint of the 53 * new caret location will occur on the event thread in any case, as calls to 54 * <code>modelToView</code> are only safe on the event thread. 55 * <p> 56 * The caret acts as a mouse and focus listener on the text component 57 * it has been installed in, and defines the caret semantics based upon 58 * those events. The listener methods can be reimplemented to change the 59 * semantics. 60 * By default, the first mouse button will be used to set focus and caret 61 * position. Dragging the mouse pointer with the first mouse button will 62 * sweep out a selection that is contiguous in the model. If the associated 63 * text component is editable, the caret will become visible when focus 64 * is gained, and invisible when focus is lost. 65 * <p> 66 * The Highlighter bound to the associated text component is used to 67 * render the selection by default. 68 * Selection appearance can be customized by supplying a 69 * painter to use for the highlights. By default a painter is used that 70 * will render a solid color as specified in the associated text component 71 * in the <code>SelectionColor</code> property. This can easily be changed 72 * by reimplementing the 73 * {@link #getSelectionPainter getSelectionPainter} 74 * method. 75 * <p> 76 * A customized caret appearance can be achieved by reimplementing 77 * the paint method. If the paint method is changed, the damage method 78 * should also be reimplemented to cause a repaint for the area needed 79 * to render the caret. The caret extends the Rectangle class which 80 * is used to hold the bounding box for where the caret was last rendered. 81 * This enables the caret to repaint in a thread-safe manner when the 82 * caret moves without making a call to modelToView which is unstable 83 * between model updates and view repair (i.e. the order of delivery 84 * to DocumentListeners is not guaranteed). 85 * <p> 86 * The magic caret position is set to null when the caret position changes. 87 * A timer is used to determine the new location (after the caret change). 88 * When the timer fires, if the magic caret position is still null it is 89 * reset to the current caret position. Any actions that change 90 * the caret position and want the magic caret position to remain the 91 * same, must remember the magic caret position, change the cursor, and 92 * then set the magic caret position to its original value. This has the 93 * benefit that only actions that want the magic caret position to persist 94 * (such as open/down) need to know about it. 95 * <p> 96 * <strong>Warning:</strong> 97 * Serialized objects of this class will not be compatible with 98 * future Swing releases. The current serialization support is 99 * appropriate for short term storage or RMI between applications running 100 * the same version of Swing. As of 1.4, support for long term storage 101 * of all JavaBeans™ 102 * has been added to the <code>java.beans</code> package. 103 * Please see {@link java.beans.XMLEncoder}. 104 * 105 * @author Timothy Prinzing 106 * @see Caret 107 */ 108 @SuppressWarnings("serial") // Same-version serialization only 109 public class DefaultCaret extends Rectangle implements Caret, FocusListener, MouseListener, MouseMotionListener { 110 111 /** 112 * Indicates that the caret position is to be updated only when 113 * document changes are performed on the Event Dispatching Thread. 114 * @see #setUpdatePolicy 115 * @see #getUpdatePolicy 116 * @since 1.5 117 */ 118 public static final int UPDATE_WHEN_ON_EDT = 0; 119 120 /** 121 * Indicates that the caret should remain at the same 122 * absolute position in the document regardless of any document 123 * updates, except when the document length becomes less than 124 * the current caret position due to removal. In that case the caret 125 * position is adjusted to the end of the document. 126 * 127 * @see #setUpdatePolicy 128 * @see #getUpdatePolicy 129 * @since 1.5 130 */ 131 public static final int NEVER_UPDATE = 1; 132 133 /** 134 * Indicates that the caret position is to be <b>always</b> 135 * updated accordingly to the document changes regardless whether 136 * the document updates are performed on the Event Dispatching Thread 137 * or not. 138 * 139 * @see #setUpdatePolicy 140 * @see #getUpdatePolicy 141 * @since 1.5 142 */ 143 public static final int ALWAYS_UPDATE = 2; 144 145 /** 146 * Constructs a default caret. 147 */ 148 public DefaultCaret() { 149 } 150 151 /** 152 * Sets the caret movement policy on the document updates. Normally 153 * the caret updates its absolute position within the document on 154 * insertions occurred before or at the caret position and 155 * on removals before the caret position. 'Absolute position' 156 * means here the position relative to the start of the document. 157 * For example if 158 * a character is typed within editable text component it is inserted 159 * at the caret position and the caret moves to the next absolute 160 * position within the document due to insertion and if 161 * <code>BACKSPACE</code> is typed then caret decreases its absolute 162 * position due to removal of a character before it. Sometimes 163 * it may be useful to turn off the caret position updates so that 164 * the caret stays at the same absolute position within the 165 * document position regardless of any document updates. 166 * <p> 167 * The following update policies are allowed: 168 * <ul> 169 * <li><code>NEVER_UPDATE</code>: the caret stays at the same 170 * absolute position in the document regardless of any document 171 * updates, except when document length becomes less than 172 * the current caret position due to removal. In that case caret 173 * position is adjusted to the end of the document. 174 * The caret doesn't try to keep itself visible by scrolling 175 * the associated view when using this policy. </li> 176 * <li><code>ALWAYS_UPDATE</code>: the caret always tracks document 177 * changes. For regular changes it increases its position 178 * if an insertion occurs before or at its current position, 179 * and decreases position if a removal occurs before 180 * its current position. For undo/redo updates it is always 181 * moved to the position where update occurred. The caret 182 * also tries to keep itself visible by calling 183 * <code>adjustVisibility</code> method.</li> 184 * <li><code>UPDATE_WHEN_ON_EDT</code>: acts like <code>ALWAYS_UPDATE</code> 185 * if the document updates are performed on the Event Dispatching Thread 186 * and like <code>NEVER_UPDATE</code> if updates are performed on 187 * other thread. </li> 188 * </ul> <p> 189 * The default property value is <code>UPDATE_WHEN_ON_EDT</code>. 190 * 191 * @param policy one of the following values : <code>UPDATE_WHEN_ON_EDT</code>, 192 * <code>NEVER_UPDATE</code>, <code>ALWAYS_UPDATE</code> 193 * @throws IllegalArgumentException if invalid value is passed 194 * 195 * @see #getUpdatePolicy 196 * @see #adjustVisibility 197 * @see #UPDATE_WHEN_ON_EDT 198 * @see #NEVER_UPDATE 199 * @see #ALWAYS_UPDATE 200 * 201 * @since 1.5 202 */ 203 public void setUpdatePolicy(int policy) { 204 updatePolicy = policy; 205 } 206 207 /** 208 * Gets the caret movement policy on document updates. 209 * 210 * @return one of the following values : <code>UPDATE_WHEN_ON_EDT</code>, 211 * <code>NEVER_UPDATE</code>, <code>ALWAYS_UPDATE</code> 212 * 213 * @see #setUpdatePolicy 214 * @see #UPDATE_WHEN_ON_EDT 215 * @see #NEVER_UPDATE 216 * @see #ALWAYS_UPDATE 217 * 218 * @since 1.5 219 */ 220 public int getUpdatePolicy() { 221 return updatePolicy; 222 } 223 224 /** 225 * Gets the text editor component that this caret is 226 * is bound to. 227 * 228 * @return the component 229 */ 230 protected final JTextComponent getComponent() { 231 return component; 232 } 233 234 /** 235 * Cause the caret to be painted. The repaint 236 * area is the bounding box of the caret (i.e. 237 * the caret rectangle or <em>this</em>). 238 * <p> 239 * This method is thread safe, although most Swing methods 240 * are not. Please see 241 * <A HREF="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency 242 * in Swing</A> for more information. 243 */ 244 protected final synchronized void repaint() { 245 if (component != null) { 246 component.repaint(x, y, width, height); 247 } 248 } 249 250 /** 251 * Damages the area surrounding the caret to cause 252 * it to be repainted in a new location. If paint() 253 * is reimplemented, this method should also be 254 * reimplemented. This method should update the 255 * caret bounds (x, y, width, and height). 256 * 257 * @param r the current location of the caret 258 * @see #paint 259 */ 260 protected synchronized void damage(Rectangle r) { 261 if (r != null) { 262 int damageWidth = getCaretWidth(r.height); 263 x = r.x - 4 - (damageWidth >> 1); 264 y = r.y; 265 width = 9 + damageWidth; 266 height = r.height; 267 repaint(); 268 } 269 } 270 271 /** 272 * Scrolls the associated view (if necessary) to make 273 * the caret visible. Since how this should be done 274 * is somewhat of a policy, this method can be 275 * reimplemented to change the behavior. By default 276 * the scrollRectToVisible method is called on the 277 * associated component. 278 * 279 * @param nloc the new position to scroll to 280 */ 281 protected void adjustVisibility(Rectangle nloc) { 282 if(component == null) { 283 return; 284 } 285 if (SwingUtilities.isEventDispatchThread()) { 286 component.scrollRectToVisible(nloc); 287 } else { 288 SwingUtilities.invokeLater(new SafeScroller(nloc)); 289 } 290 } 291 292 /** 293 * Gets the painter for the Highlighter. 294 * 295 * @return the painter 296 */ 297 protected Highlighter.HighlightPainter getSelectionPainter() { 298 return DefaultHighlighter.DefaultPainter; 299 } 300 301 /** 302 * Tries to set the position of the caret from 303 * the coordinates of a mouse event, using viewToModel(). 304 * 305 * @param e the mouse event 306 */ 307 protected void positionCaret(MouseEvent e) { 308 Point pt = new Point(e.getX(), e.getY()); 309 Position.Bias[] biasRet = new Position.Bias[1]; 310 int pos = component.getUI().viewToModel(component, pt, biasRet); 311 if(biasRet[0] == null) 312 biasRet[0] = Position.Bias.Forward; 313 if (pos >= 0) { 314 setDot(pos, biasRet[0]); 315 } 316 } 317 318 /** 319 * Tries to move the position of the caret from 320 * the coordinates of a mouse event, using viewToModel(). 321 * This will cause a selection if the dot and mark 322 * are different. 323 * 324 * @param e the mouse event 325 */ 326 protected void moveCaret(MouseEvent e) { 327 Point pt = new Point(e.getX(), e.getY()); 328 Position.Bias[] biasRet = new Position.Bias[1]; 329 int pos = component.getUI().viewToModel(component, pt, biasRet); 330 if(biasRet[0] == null) 331 biasRet[0] = Position.Bias.Forward; 332 if (pos >= 0) { 333 moveDot(pos, biasRet[0]); 334 } 335 } 336 337 // --- FocusListener methods -------------------------- 338 339 /** 340 * Called when the component containing the caret gains 341 * focus. This is implemented to set the caret to visible 342 * if the component is editable. 343 * 344 * @param e the focus event 345 * @see FocusListener#focusGained 346 */ 347 public void focusGained(FocusEvent e) { 348 if (component.isEnabled()) { 349 if (component.isEditable()) { 350 setVisible(true); 351 } 352 setSelectionVisible(true); 353 } 354 } 355 356 /** 357 * Called when the component containing the caret loses 358 * focus. This is implemented to set the caret to visibility 359 * to false. 360 * 361 * @param e the focus event 362 * @see FocusListener#focusLost 363 */ 364 public void focusLost(FocusEvent e) { 365 setVisible(false); 366 setSelectionVisible(ownsSelection || e.isTemporary()); 367 } 368 369 370 /** 371 * Selects word based on the MouseEvent 372 */ 373 private void selectWord(MouseEvent e) { 374 if (selectedWordEvent != null 375 && selectedWordEvent.getX() == e.getX() 376 && selectedWordEvent.getY() == e.getY()) { 377 //we already done selection for this 378 return; 379 } 380 Action a = null; 381 ActionMap map = getComponent().getActionMap(); 382 if (map != null) { 383 a = map.get(DefaultEditorKit.selectWordAction); 384 } 385 if (a == null) { 386 if (selectWord == null) { 387 selectWord = new DefaultEditorKit.SelectWordAction(); 388 } 389 a = selectWord; 390 } 391 a.actionPerformed(new ActionEvent(getComponent(), 392 ActionEvent.ACTION_PERFORMED, null, e.getWhen(), e.getModifiers())); 393 selectedWordEvent = e; 394 } 395 396 // --- MouseListener methods ----------------------------------- 397 398 /** 399 * Called when the mouse is clicked. If the click was generated 400 * from button1, a double click selects a word, 401 * and a triple click the current line. 402 * 403 * @param e the mouse event 404 * @see MouseListener#mouseClicked 405 */ 406 public void mouseClicked(MouseEvent e) { 407 if (getComponent() == null) { 408 return; 409 } 410 411 int nclicks = SwingUtilities2.getAdjustedClickCount(getComponent(), e); 412 413 if (! e.isConsumed()) { 414 if (SwingUtilities.isLeftMouseButton(e)) { 415 // mouse 1 behavior 416 if(nclicks == 1) { 417 selectedWordEvent = null; 418 } else if(nclicks == 2 419 && SwingUtilities2.canEventAccessSystemClipboard(e)) { 420 selectWord(e); 421 selectedWordEvent = null; 422 } else if(nclicks == 3 423 && SwingUtilities2.canEventAccessSystemClipboard(e)) { 424 Action a = null; 425 ActionMap map = getComponent().getActionMap(); 426 if (map != null) { 427 a = map.get(DefaultEditorKit.selectLineAction); 428 } 429 if (a == null) { 430 if (selectLine == null) { 431 selectLine = new DefaultEditorKit.SelectLineAction(); 432 } 433 a = selectLine; 434 } 435 a.actionPerformed(new ActionEvent(getComponent(), 436 ActionEvent.ACTION_PERFORMED, null, e.getWhen(), e.getModifiers())); 437 } 438 } else if (SwingUtilities.isMiddleMouseButton(e)) { 439 // mouse 2 behavior 440 if (nclicks == 1 && component.isEditable() && component.isEnabled() 441 && SwingUtilities2.canEventAccessSystemClipboard(e)) { 442 // paste system selection, if it exists 443 JTextComponent c = (JTextComponent) e.getSource(); 444 if (c != null) { 445 try { 446 Toolkit tk = c.getToolkit(); 447 Clipboard buffer = tk.getSystemSelection(); 448 if (buffer != null) { 449 // platform supports system selections, update it. 450 adjustCaret(e); 451 TransferHandler th = c.getTransferHandler(); 452 if (th != null) { 453 Transferable trans = null; 454 455 try { 456 trans = buffer.getContents(null); 457 } catch (IllegalStateException ise) { 458 // clipboard was unavailable 459 UIManager.getLookAndFeel().provideErrorFeedback(c); 460 } 461 462 if (trans != null) { 463 th.importData(c, trans); 464 } 465 } 466 adjustFocus(true); 467 } 468 } catch (HeadlessException he) { 469 // do nothing... there is no system clipboard 470 } 471 } 472 } 473 } 474 } 475 } 476 477 /** 478 * If button 1 is pressed, this is implemented to 479 * request focus on the associated text component, 480 * and to set the caret position. If the shift key is held down, 481 * the caret will be moved, potentially resulting in a selection, 482 * otherwise the 483 * caret position will be set to the new location. If the component 484 * is not enabled, there will be no request for focus. 485 * 486 * @param e the mouse event 487 * @see MouseListener#mousePressed 488 */ 489 public void mousePressed(MouseEvent e) { 490 int nclicks = SwingUtilities2.getAdjustedClickCount(getComponent(), e); 491 492 if (SwingUtilities.isLeftMouseButton(e)) { 493 if (e.isConsumed()) { 494 shouldHandleRelease = true; 495 } else { 496 shouldHandleRelease = false; 497 adjustCaretAndFocus(e); 498 if (nclicks == 2 499 && SwingUtilities2.canEventAccessSystemClipboard(e)) { 500 selectWord(e); 501 } 502 } 503 } 504 } 505 506 void adjustCaretAndFocus(MouseEvent e) { 507 adjustCaret(e); 508 adjustFocus(false); 509 } 510 511 /** 512 * Adjusts the caret location based on the MouseEvent. 513 */ 514 private void adjustCaret(MouseEvent e) { 515 if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && 516 getDot() != -1) { 517 moveCaret(e); 518 } else if (!e.isPopupTrigger()) { 519 positionCaret(e); 520 } 521 } 522 523 /** 524 * Adjusts the focus, if necessary. 525 * 526 * @param inWindow if true indicates requestFocusInWindow should be used 527 */ 528 private void adjustFocus(boolean inWindow) { 529 if ((component != null) && component.isEnabled() && 530 component.isRequestFocusEnabled()) { 531 if (inWindow) { 532 component.requestFocusInWindow(); 533 } 534 else { 535 component.requestFocus(); 536 } 537 } 538 } 539 540 /** 541 * Called when the mouse is released. 542 * 543 * @param e the mouse event 544 * @see MouseListener#mouseReleased 545 */ 546 public void mouseReleased(MouseEvent e) { 547 if (!e.isConsumed() 548 && shouldHandleRelease 549 && SwingUtilities.isLeftMouseButton(e)) { 550 551 adjustCaretAndFocus(e); 552 } 553 } 554 555 /** 556 * Called when the mouse enters a region. 557 * 558 * @param e the mouse event 559 * @see MouseListener#mouseEntered 560 */ 561 public void mouseEntered(MouseEvent e) { 562 } 563 564 /** 565 * Called when the mouse exits a region. 566 * 567 * @param e the mouse event 568 * @see MouseListener#mouseExited 569 */ 570 public void mouseExited(MouseEvent e) { 571 } 572 573 // --- MouseMotionListener methods ------------------------- 574 575 /** 576 * Moves the caret position 577 * according to the mouse pointer's current 578 * location. This effectively extends the 579 * selection. By default, this is only done 580 * for mouse button 1. 581 * 582 * @param e the mouse event 583 * @see MouseMotionListener#mouseDragged 584 */ 585 public void mouseDragged(MouseEvent e) { 586 if ((! e.isConsumed()) && SwingUtilities.isLeftMouseButton(e)) { 587 moveCaret(e); 588 } 589 } 590 591 /** 592 * Called when the mouse is moved. 593 * 594 * @param e the mouse event 595 * @see MouseMotionListener#mouseMoved 596 */ 597 public void mouseMoved(MouseEvent e) { 598 } 599 600 // ---- Caret methods --------------------------------- 601 602 /** 603 * Renders the caret as a vertical line. If this is reimplemented 604 * the damage method should also be reimplemented as it assumes the 605 * shape of the caret is a vertical line. Sets the caret color to 606 * the value returned by getCaretColor(). 607 * <p> 608 * If there are multiple text directions present in the associated 609 * document, a flag indicating the caret bias will be rendered. 610 * This will occur only if the associated document is a subclass 611 * of AbstractDocument and there are multiple bidi levels present 612 * in the bidi element structure (i.e. the text has multiple 613 * directions associated with it). 614 * 615 * @param g the graphics context 616 * @see #damage 617 */ 618 public void paint(Graphics g) { 619 if(isVisible()) { 620 try { 621 TextUI mapper = component.getUI(); 622 Rectangle r = mapper.modelToView(component, dot, dotBias); 623 624 if ((r == null) || ((r.width == 0) && (r.height == 0))) { 625 return; 626 } 627 if (width > 0 && height > 0 && 628 !this._contains(r.x, r.y, r.width, r.height)) { 629 // We seem to have gotten out of sync and no longer 630 // contain the right location, adjust accordingly. 631 Rectangle clip = g.getClipBounds(); 632 633 if (clip != null && !clip.contains(this)) { 634 // Clip doesn't contain the old location, force it 635 // to be repainted lest we leave a caret around. 636 repaint(); 637 } 638 // This will potentially cause a repaint of something 639 // we're already repainting, but without changing the 640 // semantics of damage we can't really get around this. 641 damage(r); 642 } 643 g.setColor(component.getCaretColor()); 644 int paintWidth = getCaretWidth(r.height); 645 r.x -= paintWidth >> 1; 646 g.fillRect(r.x, r.y, paintWidth, r.height); 647 648 // see if we should paint a flag to indicate the bias 649 // of the caret. 650 // PENDING(prinz) this should be done through 651 // protected methods so that alternative LAF 652 // will show bidi information. 653 Document doc = component.getDocument(); 654 if (doc instanceof AbstractDocument) { 655 Element bidi = ((AbstractDocument)doc).getBidiRootElement(); 656 if ((bidi != null) && (bidi.getElementCount() > 1)) { 657 // there are multiple directions present. 658 flagXPoints[0] = r.x + ((dotLTR) ? paintWidth : 0); 659 flagYPoints[0] = r.y; 660 flagXPoints[1] = flagXPoints[0]; 661 flagYPoints[1] = flagYPoints[0] + 4; 662 flagXPoints[2] = flagXPoints[0] + ((dotLTR) ? 4 : -4); 663 flagYPoints[2] = flagYPoints[0]; 664 g.fillPolygon(flagXPoints, flagYPoints, 3); 665 } 666 } 667 } catch (BadLocationException e) { 668 // can't render I guess 669 //System.err.println("Can't render cursor"); 670 } 671 } 672 } 673 674 /** 675 * Called when the UI is being installed into the 676 * interface of a JTextComponent. This can be used 677 * to gain access to the model that is being navigated 678 * by the implementation of this interface. Sets the dot 679 * and mark to 0, and establishes document, property change, 680 * focus, mouse, and mouse motion listeners. 681 * 682 * @param c the component 683 * @see Caret#install 684 */ 685 public void install(JTextComponent c) { 686 component = c; 687 Document doc = c.getDocument(); 688 dot = mark = 0; 689 dotLTR = markLTR = true; 690 dotBias = markBias = Position.Bias.Forward; 691 if (doc != null) { 692 doc.addDocumentListener(handler); 693 } 694 c.addPropertyChangeListener(handler); 695 c.addFocusListener(this); 696 c.addMouseListener(this); 697 c.addMouseMotionListener(this); 698 699 // if the component already has focus, it won't 700 // be notified. 701 if (component.hasFocus()) { 702 focusGained(null); 703 } 704 705 Number ratio = (Number) c.getClientProperty("caretAspectRatio"); 706 if (ratio != null) { 707 aspectRatio = ratio.floatValue(); 708 } else { 709 aspectRatio = -1; 710 } 711 712 Integer width = (Integer) c.getClientProperty("caretWidth"); 713 if (width != null) { 714 caretWidth = width.intValue(); 715 } else { 716 caretWidth = -1; 717 } 718 } 719 720 /** 721 * Called when the UI is being removed from the 722 * interface of a JTextComponent. This is used to 723 * unregister any listeners that were attached. 724 * 725 * @param c the component 726 * @see Caret#deinstall 727 */ 728 public void deinstall(JTextComponent c) { 729 c.removeMouseListener(this); 730 c.removeMouseMotionListener(this); 731 c.removeFocusListener(this); 732 c.removePropertyChangeListener(handler); 733 Document doc = c.getDocument(); 734 if (doc != null) { 735 doc.removeDocumentListener(handler); 736 } 737 synchronized(this) { 738 component = null; 739 } 740 if (flasher != null) { 741 flasher.stop(); 742 } 743 744 745 } 746 747 /** 748 * Adds a listener to track whenever the caret position has 749 * been changed. 750 * 751 * @param l the listener 752 * @see Caret#addChangeListener 753 */ 754 public void addChangeListener(ChangeListener l) { 755 listenerList.add(ChangeListener.class, l); 756 } 757 758 /** 759 * Removes a listener that was tracking caret position changes. 760 * 761 * @param l the listener 762 * @see Caret#removeChangeListener 763 */ 764 public void removeChangeListener(ChangeListener l) { 765 listenerList.remove(ChangeListener.class, l); 766 } 767 768 /** 769 * Returns an array of all the change listeners 770 * registered on this caret. 771 * 772 * @return all of this caret's <code>ChangeListener</code>s 773 * or an empty 774 * array if no change listeners are currently registered 775 * 776 * @see #addChangeListener 777 * @see #removeChangeListener 778 * 779 * @since 1.4 780 */ 781 public ChangeListener[] getChangeListeners() { 782 return listenerList.getListeners(ChangeListener.class); 783 } 784 785 /** 786 * Notifies all listeners that have registered interest for 787 * notification on this event type. The event instance 788 * is lazily created using the parameters passed into 789 * the fire method. The listener list is processed last to first. 790 * 791 * @see EventListenerList 792 */ 793 protected void fireStateChanged() { 794 // Guaranteed to return a non-null array 795 Object[] listeners = listenerList.getListenerList(); 796 // Process the listeners last to first, notifying 797 // those that are interested in this event 798 for (int i = listeners.length-2; i>=0; i-=2) { 799 if (listeners[i]==ChangeListener.class) { 800 // Lazily create the event: 801 if (changeEvent == null) 802 changeEvent = new ChangeEvent(this); 803 ((ChangeListener)listeners[i+1]).stateChanged(changeEvent); 804 } 805 } 806 } 807 808 /** 809 * Returns an array of all the objects currently registered 810 * as <code><em>Foo</em>Listener</code>s 811 * upon this caret. 812 * <code><em>Foo</em>Listener</code>s are registered using the 813 * <code>add<em>Foo</em>Listener</code> method. 814 * 815 * <p> 816 * 817 * You can specify the <code>listenerType</code> argument 818 * with a class literal, 819 * such as 820 * <code><em>Foo</em>Listener.class</code>. 821 * For example, you can query a 822 * <code>DefaultCaret</code> <code>c</code> 823 * for its change listeners with the following code: 824 * 825 * <pre>ChangeListener[] cls = (ChangeListener[])(c.getListeners(ChangeListener.class));</pre> 826 * 827 * If no such listeners exist, this method returns an empty array. 828 * @param <T> the listener type 829 * @param listenerType the type of listeners requested 830 * @return an array of all objects registered as 831 * <code><em>Foo</em>Listener</code>s on this component, 832 * or an empty array if no such 833 * listeners have been added 834 * @exception ClassCastException if <code>listenerType</code> 835 * doesn't specify a class or interface that implements 836 * <code>java.util.EventListener</code> 837 * 838 * @see #getChangeListeners 839 * 840 * @since 1.3 841 */ 842 public <T extends EventListener> T[] getListeners(Class<T> listenerType) { 843 return listenerList.getListeners(listenerType); 844 } 845 846 /** 847 * Changes the selection visibility. 848 * 849 * @param vis the new visibility 850 */ 851 public void setSelectionVisible(boolean vis) { 852 if (vis != selectionVisible) { 853 selectionVisible = vis; 854 if (selectionVisible) { 855 // show 856 Highlighter h = component.getHighlighter(); 857 if ((dot != mark) && (h != null) && (selectionTag == null)) { 858 int p0 = Math.min(dot, mark); 859 int p1 = Math.max(dot, mark); 860 Highlighter.HighlightPainter p = getSelectionPainter(); 861 try { 862 selectionTag = h.addHighlight(p0, p1, p); 863 } catch (BadLocationException bl) { 864 selectionTag = null; 865 } 866 } 867 } else { 868 // hide 869 if (selectionTag != null) { 870 Highlighter h = component.getHighlighter(); 871 h.removeHighlight(selectionTag); 872 selectionTag = null; 873 } 874 } 875 } 876 } 877 878 /** 879 * Checks whether the current selection is visible. 880 * 881 * @return true if the selection is visible 882 */ 883 public boolean isSelectionVisible() { 884 return selectionVisible; 885 } 886 887 /** 888 * Determines if the caret is currently active. 889 * <p> 890 * This method returns whether or not the <code>Caret</code> 891 * is currently in a blinking state. It does not provide 892 * information as to whether it is currently blinked on or off. 893 * To determine if the caret is currently painted use the 894 * <code>isVisible</code> method. 895 * 896 * @return <code>true</code> if active else <code>false</code> 897 * @see #isVisible 898 * 899 * @since 1.5 900 */ 901 public boolean isActive() { 902 return active; 903 } 904 905 /** 906 * Indicates whether or not the caret is currently visible. As the 907 * caret flashes on and off the return value of this will change 908 * between true, when the caret is painted, and false, when the 909 * caret is not painted. <code>isActive</code> indicates whether 910 * or not the caret is in a blinking state, such that it <b>can</b> 911 * be visible, and <code>isVisible</code> indicates whether or not 912 * the caret <b>is</b> actually visible. 913 * <p> 914 * Subclasses that wish to render a different flashing caret 915 * should override paint and only paint the caret if this method 916 * returns true. 917 * 918 * @return true if visible else false 919 * @see Caret#isVisible 920 * @see #isActive 921 */ 922 public boolean isVisible() { 923 return visible; 924 } 925 926 /** 927 * Sets the caret visibility, and repaints the caret. 928 * It is important to understand the relationship between this method, 929 * <code>isVisible</code> and <code>isActive</code>. 930 * Calling this method with a value of <code>true</code> activates the 931 * caret blinking. Setting it to <code>false</code> turns it completely off. 932 * To determine whether the blinking is active, you should call 933 * <code>isActive</code>. In effect, <code>isActive</code> is an 934 * appropriate corresponding "getter" method for this one. 935 * <code>isVisible</code> can be used to fetch the current 936 * visibility status of the caret, meaning whether or not it is currently 937 * painted. This status will change as the caret blinks on and off. 938 * <p> 939 * Here's a list showing the potential return values of both 940 * <code>isActive</code> and <code>isVisible</code> 941 * after calling this method: 942 * <p> 943 * <b><code>setVisible(true)</code></b>: 944 * <ul> 945 * <li>isActive(): true</li> 946 * <li>isVisible(): true or false depending on whether 947 * or not the caret is blinked on or off</li> 948 * </ul> 949 * <p> 950 * <b><code>setVisible(false)</code></b>: 951 * <ul> 952 * <li>isActive(): false</li> 953 * <li>isVisible(): false</li> 954 * </ul> 955 * 956 * @param e the visibility specifier 957 * @see #isActive 958 * @see Caret#setVisible 959 */ 960 public void setVisible(boolean e) { 961 // focus lost notification can come in later after the 962 // caret has been deinstalled, in which case the component 963 // will be null. 964 active = e; 965 if (component != null) { 966 TextUI mapper = component.getUI(); 967 if (visible != e) { 968 visible = e; 969 // repaint the caret 970 try { 971 Rectangle loc = mapper.modelToView(component, dot,dotBias); 972 damage(loc); 973 } catch (BadLocationException badloc) { 974 // hmm... not legally positioned 975 } 976 } 977 } 978 if (flasher != null) { 979 if (visible) { 980 flasher.start(); 981 } else { 982 flasher.stop(); 983 } 984 } 985 } 986 987 /** 988 * Sets the caret blink rate. 989 * 990 * @param rate the rate in milliseconds, 0 to stop blinking 991 * @see Caret#setBlinkRate 992 */ 993 public void setBlinkRate(int rate) { 994 if (rate != 0) { 995 if (flasher == null) { 996 flasher = new Timer(rate, handler); 997 } 998 flasher.setDelay(rate); 999 } else { 1000 if (flasher != null) { 1001 flasher.stop(); 1002 flasher.removeActionListener(handler); 1003 flasher = null; 1004 } 1005 } 1006 } 1007 1008 /** 1009 * Gets the caret blink rate. 1010 * 1011 * @return the delay in milliseconds. If this is 1012 * zero the caret will not blink. 1013 * @see Caret#getBlinkRate 1014 */ 1015 public int getBlinkRate() { 1016 return (flasher == null) ? 0 : flasher.getDelay(); 1017 } 1018 1019 /** 1020 * Fetches the current position of the caret. 1021 * 1022 * @return the position >= 0 1023 * @see Caret#getDot 1024 */ 1025 public int getDot() { 1026 return dot; 1027 } 1028 1029 /** 1030 * Fetches the current position of the mark. If there is a selection, 1031 * the dot and mark will not be the same. 1032 * 1033 * @return the position >= 0 1034 * @see Caret#getMark 1035 */ 1036 public int getMark() { 1037 return mark; 1038 } 1039 1040 /** 1041 * Sets the caret position and mark to the specified position, 1042 * with a forward bias. This implicitly sets the 1043 * selection range to zero. 1044 * 1045 * @param dot the position >= 0 1046 * @see #setDot(int, Position.Bias) 1047 * @see Caret#setDot 1048 */ 1049 public void setDot(int dot) { 1050 setDot(dot, Position.Bias.Forward); 1051 } 1052 1053 /** 1054 * Moves the caret position to the specified position, 1055 * with a forward bias. 1056 * 1057 * @param dot the position >= 0 1058 * @see #moveDot(int, javax.swing.text.Position.Bias) 1059 * @see Caret#moveDot 1060 */ 1061 public void moveDot(int dot) { 1062 moveDot(dot, Position.Bias.Forward); 1063 } 1064 1065 // ---- Bidi methods (we could put these in a subclass) 1066 1067 /** 1068 * Moves the caret position to the specified position, with the 1069 * specified bias. 1070 * 1071 * @param dot the position >= 0 1072 * @param dotBias the bias for this position, not <code>null</code> 1073 * @throws IllegalArgumentException if the bias is <code>null</code> 1074 * @see Caret#moveDot 1075 * @since 1.6 1076 */ 1077 public void moveDot(int dot, Position.Bias dotBias) { 1078 if (dotBias == null) { 1079 throw new IllegalArgumentException("null bias"); 1080 } 1081 1082 if (! component.isEnabled()) { 1083 // don't allow selection on disabled components. 1084 setDot(dot, dotBias); 1085 return; 1086 } 1087 if (dot != this.dot) { 1088 NavigationFilter filter = component.getNavigationFilter(); 1089 1090 if (filter != null) { 1091 filter.moveDot(getFilterBypass(), dot, dotBias); 1092 } 1093 else { 1094 handleMoveDot(dot, dotBias); 1095 } 1096 } 1097 } 1098 1099 void handleMoveDot(int dot, Position.Bias dotBias) { 1100 changeCaretPosition(dot, dotBias); 1101 1102 if (selectionVisible) { 1103 Highlighter h = component.getHighlighter(); 1104 if (h != null) { 1105 int p0 = Math.min(dot, mark); 1106 int p1 = Math.max(dot, mark); 1107 1108 // if p0 == p1 then there should be no highlight, remove it if necessary 1109 if (p0 == p1) { 1110 if (selectionTag != null) { 1111 h.removeHighlight(selectionTag); 1112 selectionTag = null; 1113 } 1114 // otherwise, change or add the highlight 1115 } else { 1116 try { 1117 if (selectionTag != null) { 1118 h.changeHighlight(selectionTag, p0, p1); 1119 } else { 1120 Highlighter.HighlightPainter p = getSelectionPainter(); 1121 selectionTag = h.addHighlight(p0, p1, p); 1122 } 1123 } catch (BadLocationException e) { 1124 throw new StateInvariantError("Bad caret position"); 1125 } 1126 } 1127 } 1128 } 1129 } 1130 1131 /** 1132 * Sets the caret position and mark to the specified position, with the 1133 * specified bias. This implicitly sets the selection range 1134 * to zero. 1135 * 1136 * @param dot the position >= 0 1137 * @param dotBias the bias for this position, not <code>null</code> 1138 * @throws IllegalArgumentException if the bias is <code>null</code> 1139 * @see Caret#setDot 1140 * @since 1.6 1141 */ 1142 public void setDot(int dot, Position.Bias dotBias) { 1143 if (dotBias == null) { 1144 throw new IllegalArgumentException("null bias"); 1145 } 1146 1147 NavigationFilter filter = component.getNavigationFilter(); 1148 1149 if (filter != null) { 1150 filter.setDot(getFilterBypass(), dot, dotBias); 1151 } 1152 else { 1153 handleSetDot(dot, dotBias); 1154 } 1155 } 1156 1157 void handleSetDot(int dot, Position.Bias dotBias) { 1158 // move dot, if it changed 1159 Document doc = component.getDocument(); 1160 if (doc != null) { 1161 dot = Math.min(dot, doc.getLength()); 1162 } 1163 dot = Math.max(dot, 0); 1164 1165 // The position (0,Backward) is out of range so disallow it. 1166 if( dot == 0 ) 1167 dotBias = Position.Bias.Forward; 1168 1169 mark = dot; 1170 if (this.dot != dot || this.dotBias != dotBias || 1171 selectionTag != null || forceCaretPositionChange) { 1172 changeCaretPosition(dot, dotBias); 1173 } 1174 this.markBias = this.dotBias; 1175 this.markLTR = dotLTR; 1176 Highlighter h = component.getHighlighter(); 1177 if ((h != null) && (selectionTag != null)) { 1178 h.removeHighlight(selectionTag); 1179 selectionTag = null; 1180 } 1181 } 1182 1183 /** 1184 * Returns the bias of the caret position. 1185 * 1186 * @return the bias of the caret position 1187 * @since 1.6 1188 */ 1189 public Position.Bias getDotBias() { 1190 return dotBias; 1191 } 1192 1193 /** 1194 * Returns the bias of the mark. 1195 * 1196 * @return the bias of the mark 1197 * @since 1.6 1198 */ 1199 public Position.Bias getMarkBias() { 1200 return markBias; 1201 } 1202 1203 boolean isDotLeftToRight() { 1204 return dotLTR; 1205 } 1206 1207 boolean isMarkLeftToRight() { 1208 return markLTR; 1209 } 1210 1211 boolean isPositionLTR(int position, Position.Bias bias) { 1212 Document doc = component.getDocument(); 1213 if(bias == Position.Bias.Backward && --position < 0) 1214 position = 0; 1215 return AbstractDocument.isLeftToRight(doc, position, position); 1216 } 1217 1218 Position.Bias guessBiasForOffset(int offset, Position.Bias lastBias, 1219 boolean lastLTR) { 1220 // There is an abiguous case here. That if your model looks like: 1221 // abAB with the cursor at abB]A (visual representation of 1222 // 3 forward) deleting could either become abB] or 1223 // ab[B. I'ld actually prefer abB]. But, if I implement that 1224 // a delete at abBA] would result in aBA] vs a[BA which I 1225 // think is totally wrong. To get this right we need to know what 1226 // was deleted. And we could get this from the bidi structure 1227 // in the change event. So: 1228 // PENDING: base this off what was deleted. 1229 if(lastLTR != isPositionLTR(offset, lastBias)) { 1230 lastBias = Position.Bias.Backward; 1231 } 1232 else if(lastBias != Position.Bias.Backward && 1233 lastLTR != isPositionLTR(offset, Position.Bias.Backward)) { 1234 lastBias = Position.Bias.Backward; 1235 } 1236 if (lastBias == Position.Bias.Backward && offset > 0) { 1237 try { 1238 Segment s = new Segment(); 1239 component.getDocument().getText(offset - 1, 1, s); 1240 if (s.count > 0 && s.array[s.offset] == '\n') { 1241 lastBias = Position.Bias.Forward; 1242 } 1243 } 1244 catch (BadLocationException ble) {} 1245 } 1246 return lastBias; 1247 } 1248 1249 // ---- local methods -------------------------------------------- 1250 1251 /** 1252 * Sets the caret position (dot) to a new location. This 1253 * causes the old and new location to be repainted. It 1254 * also makes sure that the caret is within the visible 1255 * region of the view, if the view is scrollable. 1256 */ 1257 void changeCaretPosition(int dot, Position.Bias dotBias) { 1258 // repaint the old position and set the new value of 1259 // the dot. 1260 repaint(); 1261 1262 1263 // Make sure the caret is visible if this window has the focus. 1264 if (flasher != null && flasher.isRunning()) { 1265 visible = true; 1266 flasher.restart(); 1267 } 1268 1269 // notify listeners at the caret moved 1270 this.dot = dot; 1271 this.dotBias = dotBias; 1272 dotLTR = isPositionLTR(dot, dotBias); 1273 fireStateChanged(); 1274 1275 updateSystemSelection(); 1276 1277 setMagicCaretPosition(null); 1278 1279 // We try to repaint the caret later, since things 1280 // may be unstable at the time this is called 1281 // (i.e. we don't want to depend upon notification 1282 // order or the fact that this might happen on 1283 // an unsafe thread). 1284 Runnable callRepaintNewCaret = new Runnable() { 1285 public void run() { 1286 repaintNewCaret(); 1287 } 1288 }; 1289 SwingUtilities.invokeLater(callRepaintNewCaret); 1290 } 1291 1292 /** 1293 * Repaints the new caret position, with the 1294 * assumption that this is happening on the 1295 * event thread so that calling <code>modelToView</code> 1296 * is safe. 1297 */ 1298 void repaintNewCaret() { 1299 if (component != null) { 1300 TextUI mapper = component.getUI(); 1301 Document doc = component.getDocument(); 1302 if ((mapper != null) && (doc != null)) { 1303 // determine the new location and scroll if 1304 // not visible. 1305 Rectangle newLoc; 1306 try { 1307 newLoc = mapper.modelToView(component, this.dot, this.dotBias); 1308 } catch (BadLocationException e) { 1309 newLoc = null; 1310 } 1311 if (newLoc != null) { 1312 adjustVisibility(newLoc); 1313 // If there is no magic caret position, make one 1314 if (getMagicCaretPosition() == null) { 1315 setMagicCaretPosition(new Point(newLoc.x, newLoc.y)); 1316 } 1317 } 1318 1319 // repaint the new position 1320 damage(newLoc); 1321 } 1322 } 1323 } 1324 1325 private void updateSystemSelection() { 1326 if ( ! SwingUtilities2.canCurrentEventAccessSystemClipboard() ) { 1327 return; 1328 } 1329 if (this.dot != this.mark && component != null && component.hasFocus()) { 1330 Clipboard clip = getSystemSelection(); 1331 if (clip != null) { 1332 String selectedText; 1333 if (component instanceof JPasswordField 1334 && component.getClientProperty("JPasswordField.cutCopyAllowed") != 1335 Boolean.TRUE) { 1336 //fix for 4793761 1337 StringBuilder txt = null; 1338 char echoChar = ((JPasswordField)component).getEchoChar(); 1339 int p0 = Math.min(getDot(), getMark()); 1340 int p1 = Math.max(getDot(), getMark()); 1341 for (int i = p0; i < p1; i++) { 1342 if (txt == null) { 1343 txt = new StringBuilder(); 1344 } 1345 txt.append(echoChar); 1346 } 1347 selectedText = (txt != null) ? txt.toString() : null; 1348 } else { 1349 selectedText = component.getSelectedText(); 1350 } 1351 try { 1352 clip.setContents( 1353 new StringSelection(selectedText), getClipboardOwner()); 1354 1355 ownsSelection = true; 1356 } catch (IllegalStateException ise) { 1357 // clipboard was unavailable 1358 // no need to provide error feedback to user since updating 1359 // the system selection is not a user invoked action 1360 } 1361 } 1362 } 1363 } 1364 1365 private Clipboard getSystemSelection() { 1366 try { 1367 return component.getToolkit().getSystemSelection(); 1368 } catch (HeadlessException he) { 1369 // do nothing... there is no system clipboard 1370 } catch (SecurityException se) { 1371 // do nothing... there is no allowed system clipboard 1372 } 1373 return null; 1374 } 1375 1376 private ClipboardOwner getClipboardOwner() { 1377 return handler; 1378 } 1379 1380 /** 1381 * This is invoked after the document changes to verify the current 1382 * dot/mark is valid. We do this in case the <code>NavigationFilter</code> 1383 * changed where to position the dot, that resulted in the current location 1384 * being bogus. 1385 */ 1386 private void ensureValidPosition() { 1387 int length = component.getDocument().getLength(); 1388 if (dot > length || mark > length) { 1389 // Current location is bogus and filter likely vetoed the 1390 // change, force the reset without giving the filter a 1391 // chance at changing it. 1392 handleSetDot(length, Position.Bias.Forward); 1393 } 1394 } 1395 1396 1397 /** 1398 * Saves the current caret position. This is used when 1399 * caret up/down actions occur, moving between lines 1400 * that have uneven end positions. 1401 * 1402 * @param p the position 1403 * @see #getMagicCaretPosition 1404 */ 1405 public void setMagicCaretPosition(Point p) { 1406 magicCaretPosition = p; 1407 } 1408 1409 /** 1410 * Gets the saved caret position. 1411 * 1412 * @return the position 1413 * see #setMagicCaretPosition 1414 */ 1415 public Point getMagicCaretPosition() { 1416 return magicCaretPosition; 1417 } 1418 1419 /** 1420 * Compares this object to the specified object. 1421 * The superclass behavior of comparing rectangles 1422 * is not desired, so this is changed to the Object 1423 * behavior. 1424 * 1425 * @param obj the object to compare this font with 1426 * @return <code>true</code> if the objects are equal; 1427 * <code>false</code> otherwise 1428 */ 1429 public boolean equals(Object obj) { 1430 return (this == obj); 1431 } 1432 1433 public String toString() { 1434 String s = "Dot=(" + dot + ", " + dotBias + ")"; 1435 s += " Mark=(" + mark + ", " + markBias + ")"; 1436 return s; 1437 } 1438 1439 private NavigationFilter.FilterBypass getFilterBypass() { 1440 if (filterBypass == null) { 1441 filterBypass = new DefaultFilterBypass(); 1442 } 1443 return filterBypass; 1444 } 1445 1446 // Rectangle.contains returns false if passed a rect with a w or h == 0, 1447 // this won't (assuming X,Y are contained with this rectangle). 1448 private boolean _contains(int X, int Y, int W, int H) { 1449 int w = this.width; 1450 int h = this.height; 1451 if ((w | h | W | H) < 0) { 1452 // At least one of the dimensions is negative... 1453 return false; 1454 } 1455 // Note: if any dimension is zero, tests below must return false... 1456 int x = this.x; 1457 int y = this.y; 1458 if (X < x || Y < y) { 1459 return false; 1460 } 1461 if (W > 0) { 1462 w += x; 1463 W += X; 1464 if (W <= X) { 1465 // X+W overflowed or W was zero, return false if... 1466 // either original w or W was zero or 1467 // x+w did not overflow or 1468 // the overflowed x+w is smaller than the overflowed X+W 1469 if (w >= x || W > w) return false; 1470 } else { 1471 // X+W did not overflow and W was not zero, return false if... 1472 // original w was zero or 1473 // x+w did not overflow and x+w is smaller than X+W 1474 if (w >= x && W > w) return false; 1475 } 1476 } 1477 else if ((x + w) < X) { 1478 return false; 1479 } 1480 if (H > 0) { 1481 h += y; 1482 H += Y; 1483 if (H <= Y) { 1484 if (h >= y || H > h) return false; 1485 } else { 1486 if (h >= y && H > h) return false; 1487 } 1488 } 1489 else if ((y + h) < Y) { 1490 return false; 1491 } 1492 return true; 1493 } 1494 1495 int getCaretWidth(int height) { 1496 if (aspectRatio > -1) { 1497 return (int) (aspectRatio * height) + 1; 1498 } 1499 1500 if (caretWidth > -1) { 1501 return caretWidth; 1502 } else { 1503 Object property = UIManager.get("Caret.width"); 1504 if (property instanceof Integer) { 1505 return ((Integer) property).intValue(); 1506 } else { 1507 return 1; 1508 } 1509 } 1510 } 1511 1512 // --- serialization --------------------------------------------- 1513 1514 private void readObject(ObjectInputStream s) 1515 throws ClassNotFoundException, IOException 1516 { 1517 ObjectInputStream.GetField f = s.readFields(); 1518 1519 EventListenerList newListenerList = (EventListenerList) f.get("listenerList", null); 1520 if (newListenerList == null) { 1521 throw new InvalidObjectException("Null listenerList"); 1522 } 1523 listenerList = newListenerList; 1524 component = (JTextComponent) f.get("component", null); 1525 updatePolicy = f.get("updatePolicy", 0); 1526 visible = f.get("visible", false); 1527 active = f.get("active", false); 1528 dot = f.get("dot", 0); 1529 mark = f.get("mark", 0); 1530 selectionTag = f.get("selectionTag", null); 1531 selectionVisible = f.get("selectionVisible", false); 1532 flasher = (Timer) f.get("flasher", null); 1533 magicCaretPosition = (Point) f.get("magicCaretPosition", null); 1534 dotLTR = f.get("dotLTR", false); 1535 markLTR = f.get("markLTR", false); 1536 ownsSelection = f.get("ownsSelection", false); 1537 forceCaretPositionChange = f.get("forceCaretPositionChange", false); 1538 caretWidth = f.get("caretWidth", 0); 1539 aspectRatio = f.get("aspectRatio", 0.0f); 1540 1541 handler = new Handler(); 1542 if (!s.readBoolean()) { 1543 dotBias = Position.Bias.Forward; 1544 } 1545 else { 1546 dotBias = Position.Bias.Backward; 1547 } 1548 if (!s.readBoolean()) { 1549 markBias = Position.Bias.Forward; 1550 } 1551 else { 1552 markBias = Position.Bias.Backward; 1553 } 1554 } 1555 1556 private void writeObject(ObjectOutputStream s) throws IOException { 1557 s.defaultWriteObject(); 1558 s.writeBoolean((dotBias == Position.Bias.Backward)); 1559 s.writeBoolean((markBias == Position.Bias.Backward)); 1560 } 1561 1562 // ---- member variables ------------------------------------------ 1563 1564 /** 1565 * The event listener list. 1566 */ 1567 protected EventListenerList listenerList = new EventListenerList(); 1568 1569 /** 1570 * The change event for the model. 1571 * Only one ChangeEvent is needed per model instance since the 1572 * event's only (read-only) state is the source property. The source 1573 * of events generated here is always "this". 1574 */ 1575 protected transient ChangeEvent changeEvent = null; 1576 1577 // package-private to avoid inner classes private member 1578 // access bug 1579 JTextComponent component; 1580 1581 int updatePolicy = UPDATE_WHEN_ON_EDT; 1582 boolean visible; 1583 boolean active; 1584 int dot; 1585 int mark; 1586 Object selectionTag; 1587 boolean selectionVisible; 1588 Timer flasher; 1589 Point magicCaretPosition; 1590 transient Position.Bias dotBias; 1591 transient Position.Bias markBias; 1592 boolean dotLTR; 1593 boolean markLTR; 1594 transient Handler handler = new Handler(); 1595 transient private int[] flagXPoints = new int[3]; 1596 transient private int[] flagYPoints = new int[3]; 1597 private transient NavigationFilter.FilterBypass filterBypass; 1598 static private transient Action selectWord = null; 1599 static private transient Action selectLine = null; 1600 /** 1601 * This is used to indicate if the caret currently owns the selection. 1602 * This is always false if the system does not support the system 1603 * clipboard. 1604 */ 1605 private boolean ownsSelection; 1606 1607 /** 1608 * If this is true, the location of the dot is updated regardless of 1609 * the current location. This is set in the DocumentListener 1610 * such that even if the model location of dot hasn't changed (perhaps do 1611 * to a forward delete) the visual location is updated. 1612 */ 1613 private boolean forceCaretPositionChange; 1614 1615 /** 1616 * Whether or not mouseReleased should adjust the caret and focus. 1617 * This flag is set by mousePressed if it wanted to adjust the caret 1618 * and focus but couldn't because of a possible DnD operation. 1619 */ 1620 private transient boolean shouldHandleRelease; 1621 1622 1623 /** 1624 * holds last MouseEvent which caused the word selection 1625 */ 1626 private transient MouseEvent selectedWordEvent = null; 1627 1628 /** 1629 * The width of the caret in pixels. 1630 */ 1631 private int caretWidth = -1; 1632 private float aspectRatio = -1; 1633 1634 class SafeScroller implements Runnable { 1635 1636 SafeScroller(Rectangle r) { 1637 this.r = r; 1638 } 1639 1640 public void run() { 1641 if (component != null) { 1642 component.scrollRectToVisible(r); 1643 } 1644 } 1645 1646 Rectangle r; 1647 } 1648 1649 1650 class Handler implements PropertyChangeListener, DocumentListener, ActionListener, ClipboardOwner { 1651 1652 // --- ActionListener methods ---------------------------------- 1653 1654 /** 1655 * Invoked when the blink timer fires. This is called 1656 * asynchronously. The simply changes the visibility 1657 * and repaints the rectangle that last bounded the caret. 1658 * 1659 * @param e the action event 1660 */ 1661 public void actionPerformed(ActionEvent e) { 1662 if (width == 0 || height == 0) { 1663 // setVisible(true) will cause a scroll, only do this if the 1664 // new location is really valid. 1665 if (component != null) { 1666 TextUI mapper = component.getUI(); 1667 try { 1668 Rectangle r = mapper.modelToView(component, dot, 1669 dotBias); 1670 if (r != null && r.width != 0 && r.height != 0) { 1671 damage(r); 1672 } 1673 } catch (BadLocationException ble) { 1674 } 1675 } 1676 } 1677 visible = !visible; 1678 repaint(); 1679 } 1680 1681 // --- DocumentListener methods -------------------------------- 1682 1683 /** 1684 * Updates the dot and mark if they were changed by 1685 * the insertion. 1686 * 1687 * @param e the document event 1688 * @see DocumentListener#insertUpdate 1689 */ 1690 public void insertUpdate(DocumentEvent e) { 1691 if (getUpdatePolicy() == NEVER_UPDATE || 1692 (getUpdatePolicy() == UPDATE_WHEN_ON_EDT && 1693 !SwingUtilities.isEventDispatchThread())) { 1694 1695 if ((e.getOffset() <= dot || e.getOffset() <= mark) 1696 && selectionTag != null) { 1697 try { 1698 component.getHighlighter().changeHighlight(selectionTag, 1699 Math.min(dot, mark), Math.max(dot, mark)); 1700 } catch (BadLocationException e1) { 1701 e1.printStackTrace(); 1702 } 1703 } 1704 return; 1705 } 1706 int offset = e.getOffset(); 1707 int length = e.getLength(); 1708 int newDot = dot; 1709 short changed = 0; 1710 1711 if (e instanceof AbstractDocument.UndoRedoDocumentEvent) { 1712 setDot(offset + length); 1713 return; 1714 } 1715 if (newDot >= offset) { 1716 newDot += length; 1717 changed |= 1; 1718 } 1719 int newMark = mark; 1720 if (newMark >= offset) { 1721 newMark += length; 1722 changed |= 2; 1723 } 1724 1725 if (changed != 0) { 1726 Position.Bias dotBias = DefaultCaret.this.dotBias; 1727 if (dot == offset) { 1728 Document doc = component.getDocument(); 1729 boolean isNewline; 1730 try { 1731 Segment s = new Segment(); 1732 doc.getText(newDot - 1, 1, s); 1733 isNewline = (s.count > 0 && 1734 s.array[s.offset] == '\n'); 1735 } catch (BadLocationException ble) { 1736 isNewline = false; 1737 } 1738 if (isNewline) { 1739 dotBias = Position.Bias.Forward; 1740 } else { 1741 dotBias = Position.Bias.Backward; 1742 } 1743 } 1744 if (newMark == newDot) { 1745 setDot(newDot, dotBias); 1746 ensureValidPosition(); 1747 } 1748 else { 1749 setDot(newMark, markBias); 1750 if (getDot() == newMark) { 1751 // Due this test in case the filter vetoed the 1752 // change in which case this probably won't be 1753 // valid either. 1754 moveDot(newDot, dotBias); 1755 } 1756 ensureValidPosition(); 1757 } 1758 } 1759 } 1760 1761 /** 1762 * Updates the dot and mark if they were changed 1763 * by the removal. 1764 * 1765 * @param e the document event 1766 * @see DocumentListener#removeUpdate 1767 */ 1768 public void removeUpdate(DocumentEvent e) { 1769 if (getUpdatePolicy() == NEVER_UPDATE || 1770 (getUpdatePolicy() == UPDATE_WHEN_ON_EDT && 1771 !SwingUtilities.isEventDispatchThread())) { 1772 1773 int length = component.getDocument().getLength(); 1774 dot = Math.min(dot, length); 1775 mark = Math.min(mark, length); 1776 if ((e.getOffset() < dot || e.getOffset() < mark) 1777 && selectionTag != null) { 1778 try { 1779 component.getHighlighter().changeHighlight(selectionTag, 1780 Math.min(dot, mark), Math.max(dot, mark)); 1781 } catch (BadLocationException e1) { 1782 e1.printStackTrace(); 1783 } 1784 } 1785 return; 1786 } 1787 int offs0 = e.getOffset(); 1788 int offs1 = offs0 + e.getLength(); 1789 int newDot = dot; 1790 boolean adjustDotBias = false; 1791 int newMark = mark; 1792 boolean adjustMarkBias = false; 1793 1794 if(e instanceof AbstractDocument.UndoRedoDocumentEvent) { 1795 setDot(offs0); 1796 return; 1797 } 1798 if (newDot >= offs1) { 1799 newDot -= (offs1 - offs0); 1800 if(newDot == offs1) { 1801 adjustDotBias = true; 1802 } 1803 } else if (newDot >= offs0) { 1804 newDot = offs0; 1805 adjustDotBias = true; 1806 } 1807 if (newMark >= offs1) { 1808 newMark -= (offs1 - offs0); 1809 if(newMark == offs1) { 1810 adjustMarkBias = true; 1811 } 1812 } else if (newMark >= offs0) { 1813 newMark = offs0; 1814 adjustMarkBias = true; 1815 } 1816 if (newMark == newDot) { 1817 forceCaretPositionChange = true; 1818 try { 1819 setDot(newDot, guessBiasForOffset(newDot, dotBias, 1820 dotLTR)); 1821 } finally { 1822 forceCaretPositionChange = false; 1823 } 1824 ensureValidPosition(); 1825 } else { 1826 Position.Bias dotBias = DefaultCaret.this.dotBias; 1827 Position.Bias markBias = DefaultCaret.this.markBias; 1828 if(adjustDotBias) { 1829 dotBias = guessBiasForOffset(newDot, dotBias, dotLTR); 1830 } 1831 if(adjustMarkBias) { 1832 markBias = guessBiasForOffset(mark, markBias, markLTR); 1833 } 1834 setDot(newMark, markBias); 1835 if (getDot() == newMark) { 1836 // Due this test in case the filter vetoed the change 1837 // in which case this probably won't be valid either. 1838 moveDot(newDot, dotBias); 1839 } 1840 ensureValidPosition(); 1841 } 1842 } 1843 1844 /** 1845 * Gives notification that an attribute or set of attributes changed. 1846 * 1847 * @param e the document event 1848 * @see DocumentListener#changedUpdate 1849 */ 1850 public void changedUpdate(DocumentEvent e) { 1851 if (getUpdatePolicy() == NEVER_UPDATE || 1852 (getUpdatePolicy() == UPDATE_WHEN_ON_EDT && 1853 !SwingUtilities.isEventDispatchThread())) { 1854 return; 1855 } 1856 if(e instanceof AbstractDocument.UndoRedoDocumentEvent) { 1857 setDot(e.getOffset() + e.getLength()); 1858 } 1859 } 1860 1861 // --- PropertyChangeListener methods ----------------------- 1862 1863 /** 1864 * This method gets called when a bound property is changed. 1865 * We are looking for document changes on the editor. 1866 */ 1867 public void propertyChange(PropertyChangeEvent evt) { 1868 Object oldValue = evt.getOldValue(); 1869 Object newValue = evt.getNewValue(); 1870 if ((oldValue instanceof Document) || (newValue instanceof Document)) { 1871 setDot(0); 1872 if (oldValue != null) { 1873 ((Document)oldValue).removeDocumentListener(this); 1874 } 1875 if (newValue != null) { 1876 ((Document)newValue).addDocumentListener(this); 1877 } 1878 } else if("enabled".equals(evt.getPropertyName())) { 1879 Boolean enabled = (Boolean) evt.getNewValue(); 1880 if(component.isFocusOwner()) { 1881 if(enabled == Boolean.TRUE) { 1882 if(component.isEditable()) { 1883 setVisible(true); 1884 } 1885 setSelectionVisible(true); 1886 } else { 1887 setVisible(false); 1888 setSelectionVisible(false); 1889 } 1890 } 1891 } else if("caretWidth".equals(evt.getPropertyName())) { 1892 Integer newWidth = (Integer) evt.getNewValue(); 1893 if (newWidth != null) { 1894 caretWidth = newWidth.intValue(); 1895 } else { 1896 caretWidth = -1; 1897 } 1898 repaint(); 1899 } else if("caretAspectRatio".equals(evt.getPropertyName())) { 1900 Number newRatio = (Number) evt.getNewValue(); 1901 if (newRatio != null) { 1902 aspectRatio = newRatio.floatValue(); 1903 } else { 1904 aspectRatio = -1; 1905 } 1906 repaint(); 1907 } 1908 } 1909 1910 1911 // 1912 // ClipboardOwner 1913 // 1914 /** 1915 * Toggles the visibility of the selection when ownership is lost. 1916 */ 1917 public void lostOwnership(Clipboard clipboard, 1918 Transferable contents) { 1919 if (ownsSelection) { 1920 ownsSelection = false; 1921 if (component != null && !component.hasFocus()) { 1922 setSelectionVisible(false); 1923 } 1924 } 1925 } 1926 } 1927 1928 1929 private class DefaultFilterBypass extends NavigationFilter.FilterBypass { 1930 public Caret getCaret() { 1931 return DefaultCaret.this; 1932 } 1933 1934 public void setDot(int dot, Position.Bias bias) { 1935 handleSetDot(dot, bias); 1936 } 1937 1938 public void moveDot(int dot, Position.Bias bias) { 1939 handleMoveDot(dot, bias); 1940 } 1941 } 1942 }