1 /* 2 * Copyright (c) 1997, 2014, 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 com.sun.beans.util.Cache; 28 29 import java.security.AccessController; 30 import java.security.PrivilegedAction; 31 32 import java.beans.Transient; 33 import java.util.HashMap; 34 import java.util.Hashtable; 35 import java.util.Enumeration; 36 import java.util.Vector; 37 38 import java.util.concurrent.*; 39 40 import java.io.*; 41 42 import java.awt.*; 43 import java.awt.event.*; 44 import java.awt.print.*; 45 import java.awt.datatransfer.*; 46 import java.awt.im.InputContext; 47 import java.awt.im.InputMethodRequests; 48 import java.awt.font.TextHitInfo; 49 import java.awt.font.TextAttribute; 50 51 import java.awt.print.Printable; 52 import java.awt.print.PrinterException; 53 54 import javax.print.PrintService; 55 import javax.print.attribute.PrintRequestAttributeSet; 56 57 import java.text.*; 58 import java.text.AttributedCharacterIterator.Attribute; 59 60 import javax.swing.*; 61 import javax.swing.event.*; 62 import javax.swing.plaf.*; 63 64 import javax.accessibility.*; 65 66 import javax.print.attribute.*; 67 68 import sun.awt.AppContext; 69 70 71 import sun.swing.PrintingStatus; 72 import sun.swing.SwingUtilities2; 73 import sun.swing.text.TextComponentPrintable; 74 import sun.swing.SwingAccessor; 75 76 /** 77 * <code>JTextComponent</code> is the base class for swing text 78 * components. It tries to be compatible with the 79 * <code>java.awt.TextComponent</code> class 80 * where it can reasonably do so. Also provided are other services 81 * for additional flexibility (beyond the pluggable UI and bean 82 * support). 83 * You can find information on how to use the functionality 84 * this class provides in 85 * <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html">General Rules for Using Text Components</a>, 86 * a section in <em>The Java Tutorial.</em> 87 * 88 * <dl> 89 * <dt><b>Caret Changes</b> 90 * <dd> 91 * The caret is a pluggable object in swing text components. 92 * Notification of changes to the caret position and the selection 93 * are sent to implementations of the <code>CaretListener</code> 94 * interface that have been registered with the text component. 95 * The UI will install a default caret unless a customized caret 96 * has been set. <br> 97 * By default the caret tracks all the document changes 98 * performed on the Event Dispatching Thread and updates it's position 99 * accordingly if an insertion occurs before or at the caret position 100 * or a removal occurs before the caret position. <code>DefaultCaret</code> 101 * tries to make itself visible which may lead to scrolling 102 * of a text component within <code>JScrollPane</code>. The default caret 103 * behavior can be changed by the {@link DefaultCaret#setUpdatePolicy} method. 104 * <br> 105 * <b>Note</b>: Non-editable text components also have a caret though 106 * it may not be painted. 107 * 108 * <dt><b>Commands</b> 109 * <dd> 110 * Text components provide a number of commands that can be used 111 * to manipulate the component. This is essentially the way that 112 * the component expresses its capabilities. These are expressed 113 * in terms of the swing <code>Action</code> interface, 114 * using the <code>TextAction</code> implementation. 115 * The set of commands supported by the text component can be 116 * found with the {@link #getActions} method. These actions 117 * can be bound to key events, fired from buttons, etc. 118 * 119 * <dt><b>Text Input</b> 120 * <dd> 121 * The text components support flexible and internationalized text input, using 122 * keymaps and the input method framework, while maintaining compatibility with 123 * the AWT listener model. 124 * <p> 125 * A {@link javax.swing.text.Keymap} lets an application bind key 126 * strokes to actions. 127 * In order to allow keymaps to be shared across multiple text components, they 128 * can use actions that extend <code>TextAction</code>. 129 * <code>TextAction</code> can determine which <code>JTextComponent</code> 130 * most recently has or had focus and therefore is the subject of 131 * the action (In the case that the <code>ActionEvent</code> 132 * sent to the action doesn't contain the target text component as its source). 133 * <p> 134 * The <a href="../../../../technotes/guides/imf/spec.html">input method framework</a> 135 * lets text components interact with input methods, separate software 136 * components that preprocess events to let users enter thousands of 137 * different characters using keyboards with far fewer keys. 138 * <code>JTextComponent</code> is an <em>active client</em> of 139 * the framework, so it implements the preferred user interface for interacting 140 * with input methods. As a consequence, some key events do not reach the text 141 * component because they are handled by an input method, and some text input 142 * reaches the text component as committed text within an {@link 143 * java.awt.event.InputMethodEvent} instead of as a key event. 144 * The complete text input is the combination of the characters in 145 * <code>keyTyped</code> key events and committed text in input method events. 146 * <p> 147 * The AWT listener model lets applications attach event listeners to 148 * components in order to bind events to actions. Swing encourages the 149 * use of keymaps instead of listeners, but maintains compatibility 150 * with listeners by giving the listeners a chance to steal an event 151 * by consuming it. 152 * <p> 153 * Keyboard event and input method events are handled in the following stages, 154 * with each stage capable of consuming the event: 155 * 156 * <table border=1 summary="Stages of keyboard and input method event handling"> 157 * <tr> 158 * <th id="stage"><p style="text-align:left">Stage</p></th> 159 * <th id="ke"><p style="text-align:left">KeyEvent</p></th> 160 * <th id="ime"><p style="text-align:left">InputMethodEvent</p></th></tr> 161 * <tr><td headers="stage">1. </td> 162 * <td headers="ke">input methods </td> 163 * <td headers="ime">(generated here)</td></tr> 164 * <tr><td headers="stage">2. </td> 165 * <td headers="ke">focus manager </td> 166 * <td headers="ime"></td> 167 * </tr> 168 * <tr> 169 * <td headers="stage">3. </td> 170 * <td headers="ke">registered key listeners</td> 171 * <td headers="ime">registered input method listeners</tr> 172 * <tr> 173 * <td headers="stage">4. </td> 174 * <td headers="ke"></td> 175 * <td headers="ime">input method handling in JTextComponent</tr> 176 * <tr> 177 * <td headers="stage">5. </td><td headers="ke ime" colspan=2>keymap handling using the current keymap</td></tr> 178 * <tr><td headers="stage">6. </td><td headers="ke">keyboard handling in JComponent (e.g. accelerators, component navigation, etc.)</td> 179 * <td headers="ime"></td></tr> 180 * </table> 181 * 182 * <p> 183 * To maintain compatibility with applications that listen to key 184 * events but are not aware of input method events, the input 185 * method handling in stage 4 provides a compatibility mode for 186 * components that do not process input method events. For these 187 * components, the committed text is converted to keyTyped key events 188 * and processed in the key event pipeline starting at stage 3 189 * instead of in the input method event pipeline. 190 * <p> 191 * By default the component will create a keymap (named <b>DEFAULT_KEYMAP</b>) 192 * that is shared by all JTextComponent instances as the default keymap. 193 * Typically a look-and-feel implementation will install a different keymap 194 * that resolves to the default keymap for those bindings not found in the 195 * different keymap. The minimal bindings include: 196 * <ul> 197 * <li>inserting content into the editor for the 198 * printable keys. 199 * <li>removing content with the backspace and del 200 * keys. 201 * <li>caret movement forward and backward 202 * </ul> 203 * 204 * <dt><b>Model/View Split</b> 205 * <dd> 206 * The text components have a model-view split. A text component pulls 207 * together the objects used to represent the model, view, and controller. 208 * The text document model may be shared by other views which act as observers 209 * of the model (e.g. a document may be shared by multiple components). 210 * 211 * <p style="text-align:center"><img src="doc-files/editor.gif" alt="Diagram showing interaction between Controller, Document, events, and ViewFactory" 212 * HEIGHT=358 WIDTH=587></p> 213 * 214 * <p> 215 * The model is defined by the {@link Document} interface. 216 * This is intended to provide a flexible text storage mechanism 217 * that tracks change during edits and can be extended to more sophisticated 218 * models. The model interfaces are meant to capture the capabilities of 219 * expression given by SGML, a system used to express a wide variety of 220 * content. 221 * Each modification to the document causes notification of the 222 * details of the change to be sent to all observers in the form of a 223 * {@link DocumentEvent} which allows the views to stay up to date with the model. 224 * This event is sent to observers that have implemented the 225 * {@link DocumentListener} 226 * interface and registered interest with the model being observed. 227 * 228 * <dt><b>Location Information</b> 229 * <dd> 230 * The capability of determining the location of text in 231 * the view is provided. There are two methods, {@link #modelToView} 232 * and {@link #viewToModel} for determining this information. 233 * 234 * <dt><b>Undo/Redo support</b> 235 * <dd> 236 * Support for an edit history mechanism is provided to allow 237 * undo/redo operations. The text component does not itself 238 * provide the history buffer by default, but does provide 239 * the <code>UndoableEdit</code> records that can be used in conjunction 240 * with a history buffer to provide the undo/redo support. 241 * The support is provided by the Document model, which allows 242 * one to attach UndoableEditListener implementations. 243 * 244 * <dt><b>Thread Safety</b> 245 * <dd> 246 * The swing text components provide some support of thread 247 * safe operations. Because of the high level of configurability 248 * of the text components, it is possible to circumvent the 249 * protection provided. The protection primarily comes from 250 * the model, so the documentation of <code>AbstractDocument</code> 251 * describes the assumptions of the protection provided. 252 * The methods that are safe to call asynchronously are marked 253 * with comments. 254 * 255 * <dt><b>Newlines</b> 256 * <dd> 257 * For a discussion on how newlines are handled, see 258 * <a href="DefaultEditorKit.html">DefaultEditorKit</a>. 259 * 260 * 261 * <dt><b>Printing support</b> 262 * <dd> 263 * Several {@link #print print} methods are provided for basic 264 * document printing. If more advanced printing is needed, use the 265 * {@link #getPrintable} method. 266 * </dl> 267 * 268 * <p> 269 * <strong>Warning:</strong> 270 * Serialized objects of this class will not be compatible with 271 * future Swing releases. The current serialization support is 272 * appropriate for short term storage or RMI between applications running 273 * the same version of Swing. As of 1.4, support for long term storage 274 * of all JavaBeans™ 275 * has been added to the <code>java.beans</code> package. 276 * Please see {@link java.beans.XMLEncoder}. 277 * 278 * @beaninfo 279 * attribute: isContainer false 280 * 281 * @author Timothy Prinzing 282 * @author Igor Kushnirskiy (printing support) 283 * @see Document 284 * @see DocumentEvent 285 * @see DocumentListener 286 * @see Caret 287 * @see CaretEvent 288 * @see CaretListener 289 * @see TextUI 290 * @see View 291 * @see ViewFactory 292 */ 293 @SuppressWarnings("serial") // Same-version serialization only 294 public abstract class JTextComponent extends JComponent implements Scrollable, Accessible 295 { 296 /** 297 * Creates a new <code>JTextComponent</code>. 298 * Listeners for caret events are established, and the pluggable 299 * UI installed. The component is marked as editable. No layout manager 300 * is used, because layout is managed by the view subsystem of text. 301 * The document model is set to <code>null</code>. 302 */ 303 public JTextComponent() { 304 super(); 305 // enable InputMethodEvent for on-the-spot pre-editing 306 enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK); 307 caretEvent = new MutableCaretEvent(this); 308 addMouseListener(caretEvent); 309 addFocusListener(caretEvent); 310 setEditable(true); 311 setDragEnabled(false); 312 setLayout(null); // layout is managed by View hierarchy 313 updateUI(); 314 } 315 316 /** 317 * Fetches the user-interface factory for this text-oriented editor. 318 * 319 * @return the factory 320 */ 321 public TextUI getUI() { return (TextUI)ui; } 322 323 /** 324 * Sets the user-interface factory for this text-oriented editor. 325 * 326 * @param ui the factory 327 */ 328 public void setUI(TextUI ui) { 329 super.setUI(ui); 330 } 331 332 /** 333 * Reloads the pluggable UI. The key used to fetch the 334 * new interface is <code>getUIClassID()</code>. The type of 335 * the UI is <code>TextUI</code>. <code>invalidate</code> 336 * is called after setting the UI. 337 */ 338 public void updateUI() { 339 setUI((TextUI)UIManager.getUI(this)); 340 invalidate(); 341 } 342 343 /** 344 * Adds a caret listener for notification of any changes 345 * to the caret. 346 * 347 * @param listener the listener to be added 348 * @see javax.swing.event.CaretEvent 349 */ 350 public void addCaretListener(CaretListener listener) { 351 listenerList.add(CaretListener.class, listener); 352 } 353 354 /** 355 * Removes a caret listener. 356 * 357 * @param listener the listener to be removed 358 * @see javax.swing.event.CaretEvent 359 */ 360 public void removeCaretListener(CaretListener listener) { 361 listenerList.remove(CaretListener.class, listener); 362 } 363 364 /** 365 * Returns an array of all the caret listeners 366 * registered on this text component. 367 * 368 * @return all of this component's <code>CaretListener</code>s 369 * or an empty 370 * array if no caret listeners are currently registered 371 * 372 * @see #addCaretListener 373 * @see #removeCaretListener 374 * 375 * @since 1.4 376 */ 377 public CaretListener[] getCaretListeners() { 378 return listenerList.getListeners(CaretListener.class); 379 } 380 381 /** 382 * Notifies all listeners that have registered interest for 383 * notification on this event type. The event instance 384 * is lazily created using the parameters passed into 385 * the fire method. The listener list is processed in a 386 * last-to-first manner. 387 * 388 * @param e the event 389 * @see EventListenerList 390 */ 391 protected void fireCaretUpdate(CaretEvent e) { 392 // Guaranteed to return a non-null array 393 Object[] listeners = listenerList.getListenerList(); 394 // Process the listeners last to first, notifying 395 // those that are interested in this event 396 for (int i = listeners.length-2; i>=0; i-=2) { 397 if (listeners[i]==CaretListener.class) { 398 ((CaretListener)listeners[i+1]).caretUpdate(e); 399 } 400 } 401 } 402 403 /** 404 * Associates the editor with a text document. 405 * The currently registered factory is used to build a view for 406 * the document, which gets displayed by the editor after revalidation. 407 * A PropertyChange event ("document") is propagated to each listener. 408 * 409 * @param doc the document to display/edit 410 * @see #getDocument 411 * @beaninfo 412 * description: the text document model 413 * bound: true 414 * expert: true 415 */ 416 public void setDocument(Document doc) { 417 Document old = model; 418 419 /* 420 * acquire a read lock on the old model to prevent notification of 421 * mutations while we disconnecting the old model. 422 */ 423 try { 424 if (old instanceof AbstractDocument) { 425 ((AbstractDocument)old).readLock(); 426 } 427 if (accessibleContext != null) { 428 model.removeDocumentListener( 429 ((AccessibleJTextComponent)accessibleContext)); 430 } 431 if (inputMethodRequestsHandler != null) { 432 model.removeDocumentListener((DocumentListener)inputMethodRequestsHandler); 433 } 434 model = doc; 435 436 // Set the document's run direction property to match the 437 // component's ComponentOrientation property. 438 Boolean runDir = getComponentOrientation().isLeftToRight() 439 ? TextAttribute.RUN_DIRECTION_LTR 440 : TextAttribute.RUN_DIRECTION_RTL; 441 if (runDir != doc.getProperty(TextAttribute.RUN_DIRECTION)) { 442 doc.putProperty(TextAttribute.RUN_DIRECTION, runDir ); 443 } 444 firePropertyChange("document", old, doc); 445 } finally { 446 if (old instanceof AbstractDocument) { 447 ((AbstractDocument)old).readUnlock(); 448 } 449 } 450 451 revalidate(); 452 repaint(); 453 if (accessibleContext != null) { 454 model.addDocumentListener( 455 ((AccessibleJTextComponent)accessibleContext)); 456 } 457 if (inputMethodRequestsHandler != null) { 458 model.addDocumentListener((DocumentListener)inputMethodRequestsHandler); 459 } 460 } 461 462 /** 463 * Fetches the model associated with the editor. This is 464 * primarily for the UI to get at the minimal amount of 465 * state required to be a text editor. Subclasses will 466 * return the actual type of the model which will typically 467 * be something that extends Document. 468 * 469 * @return the model 470 */ 471 public Document getDocument() { 472 return model; 473 } 474 475 // Override of Component.setComponentOrientation 476 public void setComponentOrientation( ComponentOrientation o ) { 477 // Set the document's run direction property to match the 478 // ComponentOrientation property. 479 Document doc = getDocument(); 480 if( doc != null ) { 481 Boolean runDir = o.isLeftToRight() 482 ? TextAttribute.RUN_DIRECTION_LTR 483 : TextAttribute.RUN_DIRECTION_RTL; 484 doc.putProperty( TextAttribute.RUN_DIRECTION, runDir ); 485 } 486 super.setComponentOrientation( o ); 487 } 488 489 /** 490 * Fetches the command list for the editor. This is 491 * the list of commands supported by the plugged-in UI 492 * augmented by the collection of commands that the 493 * editor itself supports. These are useful for binding 494 * to events, such as in a keymap. 495 * 496 * @return the command list 497 */ 498 public Action[] getActions() { 499 return getUI().getEditorKit(this).getActions(); 500 } 501 502 /** 503 * Sets margin space between the text component's border 504 * and its text. The text component's default <code>Border</code> 505 * object will use this value to create the proper margin. 506 * However, if a non-default border is set on the text component, 507 * it is that <code>Border</code> object's responsibility to create the 508 * appropriate margin space (else this property will effectively 509 * be ignored). This causes a redraw of the component. 510 * A PropertyChange event ("margin") is sent to all listeners. 511 * 512 * @param m the space between the border and the text 513 * @beaninfo 514 * description: desired space between the border and text area 515 * bound: true 516 */ 517 public void setMargin(Insets m) { 518 Insets old = margin; 519 margin = m; 520 firePropertyChange("margin", old, m); 521 invalidate(); 522 } 523 524 /** 525 * Returns the margin between the text component's border and 526 * its text. 527 * 528 * @return the margin 529 */ 530 public Insets getMargin() { 531 return margin; 532 } 533 534 /** 535 * Sets the <code>NavigationFilter</code>. <code>NavigationFilter</code> 536 * is used by <code>DefaultCaret</code> and the default cursor movement 537 * actions as a way to restrict the cursor movement. 538 * 539 * @since 1.4 540 */ 541 public void setNavigationFilter(NavigationFilter filter) { 542 navigationFilter = filter; 543 } 544 545 /** 546 * Returns the <code>NavigationFilter</code>. <code>NavigationFilter</code> 547 * is used by <code>DefaultCaret</code> and the default cursor movement 548 * actions as a way to restrict the cursor movement. A null return value 549 * implies the cursor movement and selection should not be restricted. 550 * 551 * @since 1.4 552 * @return the NavigationFilter 553 */ 554 public NavigationFilter getNavigationFilter() { 555 return navigationFilter; 556 } 557 558 /** 559 * Fetches the caret that allows text-oriented navigation over 560 * the view. 561 * 562 * @return the caret 563 */ 564 @Transient 565 public Caret getCaret() { 566 return caret; 567 } 568 569 /** 570 * Sets the caret to be used. By default this will be set 571 * by the UI that gets installed. This can be changed to 572 * a custom caret if desired. Setting the caret results in a 573 * PropertyChange event ("caret") being fired. 574 * 575 * @param c the caret 576 * @see #getCaret 577 * @beaninfo 578 * description: the caret used to select/navigate 579 * bound: true 580 * expert: true 581 */ 582 public void setCaret(Caret c) { 583 if (caret != null) { 584 caret.removeChangeListener(caretEvent); 585 caret.deinstall(this); 586 } 587 Caret old = caret; 588 caret = c; 589 if (caret != null) { 590 caret.install(this); 591 caret.addChangeListener(caretEvent); 592 } 593 firePropertyChange("caret", old, caret); 594 } 595 596 /** 597 * Fetches the object responsible for making highlights. 598 * 599 * @return the highlighter 600 */ 601 public Highlighter getHighlighter() { 602 return highlighter; 603 } 604 605 /** 606 * Sets the highlighter to be used. By default this will be set 607 * by the UI that gets installed. This can be changed to 608 * a custom highlighter if desired. The highlighter can be set to 609 * <code>null</code> to disable it. 610 * A PropertyChange event ("highlighter") is fired 611 * when a new highlighter is installed. 612 * 613 * @param h the highlighter 614 * @see #getHighlighter 615 * @beaninfo 616 * description: object responsible for background highlights 617 * bound: true 618 * expert: true 619 */ 620 public void setHighlighter(Highlighter h) { 621 if (highlighter != null) { 622 highlighter.deinstall(this); 623 } 624 Highlighter old = highlighter; 625 highlighter = h; 626 if (highlighter != null) { 627 highlighter.install(this); 628 } 629 firePropertyChange("highlighter", old, h); 630 } 631 632 /** 633 * Sets the keymap to use for binding events to 634 * actions. Setting to <code>null</code> effectively disables 635 * keyboard input. 636 * A PropertyChange event ("keymap") is fired when a new keymap 637 * is installed. 638 * 639 * @param map the keymap 640 * @see #getKeymap 641 * @beaninfo 642 * description: set of key event to action bindings to use 643 * bound: true 644 */ 645 public void setKeymap(Keymap map) { 646 Keymap old = keymap; 647 keymap = map; 648 firePropertyChange("keymap", old, keymap); 649 updateInputMap(old, map); 650 } 651 652 /** 653 * Turns on or off automatic drag handling. In order to enable automatic 654 * drag handling, this property should be set to {@code true}, and the 655 * component's {@code TransferHandler} needs to be {@code non-null}. 656 * The default value of the {@code dragEnabled} property is {@code false}. 657 * <p> 658 * The job of honoring this property, and recognizing a user drag gesture, 659 * lies with the look and feel implementation, and in particular, the component's 660 * {@code TextUI}. When automatic drag handling is enabled, most look and 661 * feels (including those that subclass {@code BasicLookAndFeel}) begin a 662 * drag and drop operation whenever the user presses the mouse button over 663 * a selection and then moves the mouse a few pixels. Setting this property to 664 * {@code true} can therefore have a subtle effect on how selections behave. 665 * <p> 666 * If a look and feel is used that ignores this property, you can still 667 * begin a drag and drop operation by calling {@code exportAsDrag} on the 668 * component's {@code TransferHandler}. 669 * 670 * @param b whether or not to enable automatic drag handling 671 * @exception HeadlessException if 672 * <code>b</code> is <code>true</code> and 673 * <code>GraphicsEnvironment.isHeadless()</code> 674 * returns <code>true</code> 675 * @see java.awt.GraphicsEnvironment#isHeadless 676 * @see #getDragEnabled 677 * @see #setTransferHandler 678 * @see TransferHandler 679 * @since 1.4 680 * 681 * @beaninfo 682 * description: determines whether automatic drag handling is enabled 683 * bound: false 684 */ 685 public void setDragEnabled(boolean b) { 686 if (b && GraphicsEnvironment.isHeadless()) { 687 throw new HeadlessException(); 688 } 689 dragEnabled = b; 690 } 691 692 /** 693 * Returns whether or not automatic drag handling is enabled. 694 * 695 * @return the value of the {@code dragEnabled} property 696 * @see #setDragEnabled 697 * @since 1.4 698 */ 699 public boolean getDragEnabled() { 700 return dragEnabled; 701 } 702 703 /** 704 * Sets the drop mode for this component. For backward compatibility, 705 * the default for this property is <code>DropMode.USE_SELECTION</code>. 706 * Usage of <code>DropMode.INSERT</code> is recommended, however, 707 * for an improved user experience. It offers similar behavior of dropping 708 * between text locations, but does so without affecting the actual text 709 * selection and caret location. 710 * <p> 711 * <code>JTextComponents</code> support the following drop modes: 712 * <ul> 713 * <li><code>DropMode.USE_SELECTION</code></li> 714 * <li><code>DropMode.INSERT</code></li> 715 * </ul> 716 * <p> 717 * The drop mode is only meaningful if this component has a 718 * <code>TransferHandler</code> that accepts drops. 719 * 720 * @param dropMode the drop mode to use 721 * @throws IllegalArgumentException if the drop mode is unsupported 722 * or <code>null</code> 723 * @see #getDropMode 724 * @see #getDropLocation 725 * @see #setTransferHandler 726 * @see javax.swing.TransferHandler 727 * @since 1.6 728 */ 729 public final void setDropMode(DropMode dropMode) { 730 if (dropMode != null) { 731 switch (dropMode) { 732 case USE_SELECTION: 733 case INSERT: 734 this.dropMode = dropMode; 735 return; 736 } 737 } 738 739 throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for text"); 740 } 741 742 /** 743 * Returns the drop mode for this component. 744 * 745 * @return the drop mode for this component 746 * @see #setDropMode 747 * @since 1.6 748 */ 749 public final DropMode getDropMode() { 750 return dropMode; 751 } 752 753 static { 754 SwingAccessor.setJTextComponentAccessor( 755 new SwingAccessor.JTextComponentAccessor() { 756 public TransferHandler.DropLocation dropLocationForPoint(JTextComponent textComp, 757 Point p) 758 { 759 return textComp.dropLocationForPoint(p); 760 } 761 public Object setDropLocation(JTextComponent textComp, 762 TransferHandler.DropLocation location, 763 Object state, boolean forDrop) 764 { 765 return textComp.setDropLocation(location, state, forDrop); 766 } 767 }); 768 } 769 770 771 /** 772 * Calculates a drop location in this component, representing where a 773 * drop at the given point should insert data. 774 * <p> 775 * Note: This method is meant to override 776 * <code>JComponent.dropLocationForPoint()</code>, which is package-private 777 * in javax.swing. <code>TransferHandler</code> will detect text components 778 * and call this method instead via reflection. It's name should therefore 779 * not be changed. 780 * 781 * @param p the point to calculate a drop location for 782 * @return the drop location, or <code>null</code> 783 */ 784 DropLocation dropLocationForPoint(Point p) { 785 Position.Bias[] bias = new Position.Bias[1]; 786 int index = getUI().viewToModel(this, p, bias); 787 788 // viewToModel currently returns null for some HTML content 789 // when the point is within the component's top inset 790 if (bias[0] == null) { 791 bias[0] = Position.Bias.Forward; 792 } 793 794 return new DropLocation(p, index, bias[0]); 795 } 796 797 /** 798 * Called to set or clear the drop location during a DnD operation. 799 * In some cases, the component may need to use it's internal selection 800 * temporarily to indicate the drop location. To help facilitate this, 801 * this method returns and accepts as a parameter a state object. 802 * This state object can be used to store, and later restore, the selection 803 * state. Whatever this method returns will be passed back to it in 804 * future calls, as the state parameter. If it wants the DnD system to 805 * continue storing the same state, it must pass it back every time. 806 * Here's how this is used: 807 * <p> 808 * Let's say that on the first call to this method the component decides 809 * to save some state (because it is about to use the selection to show 810 * a drop index). It can return a state object to the caller encapsulating 811 * any saved selection state. On a second call, let's say the drop location 812 * is being changed to something else. The component doesn't need to 813 * restore anything yet, so it simply passes back the same state object 814 * to have the DnD system continue storing it. Finally, let's say this 815 * method is messaged with <code>null</code>. This means DnD 816 * is finished with this component for now, meaning it should restore 817 * state. At this point, it can use the state parameter to restore 818 * said state, and of course return <code>null</code> since there's 819 * no longer anything to store. 820 * <p> 821 * Note: This method is meant to override 822 * <code>JComponent.setDropLocation()</code>, which is package-private 823 * in javax.swing. <code>TransferHandler</code> will detect text components 824 * and call this method instead via reflection. It's name should therefore 825 * not be changed. 826 * 827 * @param location the drop location (as calculated by 828 * <code>dropLocationForPoint</code>) or <code>null</code> 829 * if there's no longer a valid drop location 830 * @param state the state object saved earlier for this component, 831 * or <code>null</code> 832 * @param forDrop whether or not the method is being called because an 833 * actual drop occurred 834 * @return any saved state for this component, or <code>null</code> if none 835 */ 836 Object setDropLocation(TransferHandler.DropLocation location, 837 Object state, 838 boolean forDrop) { 839 840 Object retVal = null; 841 DropLocation textLocation = (DropLocation)location; 842 843 if (dropMode == DropMode.USE_SELECTION) { 844 if (textLocation == null) { 845 if (state != null) { 846 /* 847 * This object represents the state saved earlier. 848 * If the caret is a DefaultCaret it will be 849 * an Object array containing, in order: 850 * - the saved caret mark (Integer) 851 * - the saved caret dot (Integer) 852 * - the saved caret visibility (Boolean) 853 * - the saved mark bias (Position.Bias) 854 * - the saved dot bias (Position.Bias) 855 * If the caret is not a DefaultCaret it will 856 * be similar, but will not contain the dot 857 * or mark bias. 858 */ 859 Object[] vals = (Object[])state; 860 861 if (!forDrop) { 862 if (caret instanceof DefaultCaret) { 863 ((DefaultCaret)caret).setDot(((Integer)vals[0]).intValue(), 864 (Position.Bias)vals[3]); 865 ((DefaultCaret)caret).moveDot(((Integer)vals[1]).intValue(), 866 (Position.Bias)vals[4]); 867 } else { 868 caret.setDot(((Integer)vals[0]).intValue()); 869 caret.moveDot(((Integer)vals[1]).intValue()); 870 } 871 } 872 873 caret.setVisible(((Boolean)vals[2]).booleanValue()); 874 } 875 } else { 876 if (dropLocation == null) { 877 boolean visible; 878 879 if (caret instanceof DefaultCaret) { 880 DefaultCaret dc = (DefaultCaret)caret; 881 visible = dc.isActive(); 882 retVal = new Object[] {Integer.valueOf(dc.getMark()), 883 Integer.valueOf(dc.getDot()), 884 Boolean.valueOf(visible), 885 dc.getMarkBias(), 886 dc.getDotBias()}; 887 } else { 888 visible = caret.isVisible(); 889 retVal = new Object[] {Integer.valueOf(caret.getMark()), 890 Integer.valueOf(caret.getDot()), 891 Boolean.valueOf(visible)}; 892 } 893 894 caret.setVisible(true); 895 } else { 896 retVal = state; 897 } 898 899 if (caret instanceof DefaultCaret) { 900 ((DefaultCaret)caret).setDot(textLocation.getIndex(), textLocation.getBias()); 901 } else { 902 caret.setDot(textLocation.getIndex()); 903 } 904 } 905 } else { 906 if (textLocation == null) { 907 if (state != null) { 908 caret.setVisible(((Boolean)state).booleanValue()); 909 } 910 } else { 911 if (dropLocation == null) { 912 boolean visible = caret instanceof DefaultCaret 913 ? ((DefaultCaret)caret).isActive() 914 : caret.isVisible(); 915 retVal = Boolean.valueOf(visible); 916 caret.setVisible(false); 917 } else { 918 retVal = state; 919 } 920 } 921 } 922 923 DropLocation old = dropLocation; 924 dropLocation = textLocation; 925 firePropertyChange("dropLocation", old, dropLocation); 926 927 return retVal; 928 } 929 930 /** 931 * Returns the location that this component should visually indicate 932 * as the drop location during a DnD operation over the component, 933 * or {@code null} if no location is to currently be shown. 934 * <p> 935 * This method is not meant for querying the drop location 936 * from a {@code TransferHandler}, as the drop location is only 937 * set after the {@code TransferHandler}'s <code>canImport</code> 938 * has returned and has allowed for the location to be shown. 939 * <p> 940 * When this property changes, a property change event with 941 * name "dropLocation" is fired by the component. 942 * 943 * @return the drop location 944 * @see #setDropMode 945 * @see TransferHandler#canImport(TransferHandler.TransferSupport) 946 * @since 1.6 947 */ 948 public final DropLocation getDropLocation() { 949 return dropLocation; 950 } 951 952 953 /** 954 * Updates the <code>InputMap</code>s in response to a 955 * <code>Keymap</code> change. 956 * @param oldKm the old <code>Keymap</code> 957 * @param newKm the new <code>Keymap</code> 958 */ 959 void updateInputMap(Keymap oldKm, Keymap newKm) { 960 // Locate the current KeymapWrapper. 961 InputMap km = getInputMap(JComponent.WHEN_FOCUSED); 962 InputMap last = km; 963 while (km != null && !(km instanceof KeymapWrapper)) { 964 last = km; 965 km = km.getParent(); 966 } 967 if (km != null) { 968 // Found it, tweak the InputMap that points to it, as well 969 // as anything it points to. 970 if (newKm == null) { 971 if (last != km) { 972 last.setParent(km.getParent()); 973 } 974 else { 975 last.setParent(null); 976 } 977 } 978 else { 979 InputMap newKM = new KeymapWrapper(newKm); 980 last.setParent(newKM); 981 if (last != km) { 982 newKM.setParent(km.getParent()); 983 } 984 } 985 } 986 else if (newKm != null) { 987 km = getInputMap(JComponent.WHEN_FOCUSED); 988 if (km != null) { 989 // Couldn't find it. 990 // Set the parent of WHEN_FOCUSED InputMap to be the new one. 991 InputMap newKM = new KeymapWrapper(newKm); 992 newKM.setParent(km.getParent()); 993 km.setParent(newKM); 994 } 995 } 996 997 // Do the same thing with the ActionMap 998 ActionMap am = getActionMap(); 999 ActionMap lastAM = am; 1000 while (am != null && !(am instanceof KeymapActionMap)) { 1001 lastAM = am; 1002 am = am.getParent(); 1003 } 1004 if (am != null) { 1005 // Found it, tweak the Actionap that points to it, as well 1006 // as anything it points to. 1007 if (newKm == null) { 1008 if (lastAM != am) { 1009 lastAM.setParent(am.getParent()); 1010 } 1011 else { 1012 lastAM.setParent(null); 1013 } 1014 } 1015 else { 1016 ActionMap newAM = new KeymapActionMap(newKm); 1017 lastAM.setParent(newAM); 1018 if (lastAM != am) { 1019 newAM.setParent(am.getParent()); 1020 } 1021 } 1022 } 1023 else if (newKm != null) { 1024 am = getActionMap(); 1025 if (am != null) { 1026 // Couldn't find it. 1027 // Set the parent of ActionMap to be the new one. 1028 ActionMap newAM = new KeymapActionMap(newKm); 1029 newAM.setParent(am.getParent()); 1030 am.setParent(newAM); 1031 } 1032 } 1033 } 1034 1035 /** 1036 * Fetches the keymap currently active in this text 1037 * component. 1038 * 1039 * @return the keymap 1040 */ 1041 public Keymap getKeymap() { 1042 return keymap; 1043 } 1044 1045 /** 1046 * Adds a new keymap into the keymap hierarchy. Keymap bindings 1047 * resolve from bottom up so an attribute specified in a child 1048 * will override an attribute specified in the parent. 1049 * 1050 * @param nm the name of the keymap (must be unique within the 1051 * collection of named keymaps in the document); the name may 1052 * be <code>null</code> if the keymap is unnamed, 1053 * but the caller is responsible for managing the reference 1054 * returned as an unnamed keymap can't 1055 * be fetched by name 1056 * @param parent the parent keymap; this may be <code>null</code> if 1057 * unspecified bindings need not be resolved in some other keymap 1058 * @return the keymap 1059 */ 1060 public static Keymap addKeymap(String nm, Keymap parent) { 1061 Keymap map = new DefaultKeymap(nm, parent); 1062 if (nm != null) { 1063 // add a named keymap, a class of bindings 1064 getKeymapTable().put(nm, map); 1065 } 1066 return map; 1067 } 1068 1069 /** 1070 * Removes a named keymap previously added to the document. Keymaps 1071 * with <code>null</code> names may not be removed in this way. 1072 * 1073 * @param nm the name of the keymap to remove 1074 * @return the keymap that was removed 1075 */ 1076 public static Keymap removeKeymap(String nm) { 1077 return getKeymapTable().remove(nm); 1078 } 1079 1080 /** 1081 * Fetches a named keymap previously added to the document. 1082 * This does not work with <code>null</code>-named keymaps. 1083 * 1084 * @param nm the name of the keymap 1085 * @return the keymap 1086 */ 1087 public static Keymap getKeymap(String nm) { 1088 return getKeymapTable().get(nm); 1089 } 1090 1091 private static HashMap<String,Keymap> getKeymapTable() { 1092 synchronized (KEYMAP_TABLE) { 1093 AppContext appContext = AppContext.getAppContext(); 1094 HashMap<String,Keymap> keymapTable = 1095 (HashMap<String,Keymap>)appContext.get(KEYMAP_TABLE); 1096 if (keymapTable == null) { 1097 keymapTable = new HashMap<String,Keymap>(17); 1098 appContext.put(KEYMAP_TABLE, keymapTable); 1099 //initialize default keymap 1100 Keymap binding = addKeymap(DEFAULT_KEYMAP, null); 1101 binding.setDefaultAction(new 1102 DefaultEditorKit.DefaultKeyTypedAction()); 1103 } 1104 return keymapTable; 1105 } 1106 } 1107 1108 /** 1109 * Binding record for creating key bindings. 1110 * <p> 1111 * <strong>Warning:</strong> 1112 * Serialized objects of this class will not be compatible with 1113 * future Swing releases. The current serialization support is 1114 * appropriate for short term storage or RMI between applications running 1115 * the same version of Swing. As of 1.4, support for long term storage 1116 * of all JavaBeans™ 1117 * has been added to the <code>java.beans</code> package. 1118 * Please see {@link java.beans.XMLEncoder}. 1119 */ 1120 @SuppressWarnings("serial") // Same-version serialization only 1121 public static class KeyBinding { 1122 1123 /** 1124 * The key. 1125 */ 1126 public KeyStroke key; 1127 1128 /** 1129 * The name of the action for the key. 1130 */ 1131 public String actionName; 1132 1133 /** 1134 * Creates a new key binding. 1135 * 1136 * @param key the key 1137 * @param actionName the name of the action for the key 1138 */ 1139 public KeyBinding(KeyStroke key, String actionName) { 1140 this.key = key; 1141 this.actionName = actionName; 1142 } 1143 } 1144 1145 /** 1146 * <p> 1147 * Loads a keymap with a bunch of 1148 * bindings. This can be used to take a static table of 1149 * definitions and load them into some keymap. The following 1150 * example illustrates an example of binding some keys to 1151 * the cut, copy, and paste actions associated with a 1152 * JTextComponent. A code fragment to accomplish 1153 * this might look as follows: 1154 * <pre><code> 1155 * 1156 * static final JTextComponent.KeyBinding[] defaultBindings = { 1157 * new JTextComponent.KeyBinding( 1158 * KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK), 1159 * DefaultEditorKit.copyAction), 1160 * new JTextComponent.KeyBinding( 1161 * KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK), 1162 * DefaultEditorKit.pasteAction), 1163 * new JTextComponent.KeyBinding( 1164 * KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK), 1165 * DefaultEditorKit.cutAction), 1166 * }; 1167 * 1168 * JTextComponent c = new JTextPane(); 1169 * Keymap k = c.getKeymap(); 1170 * JTextComponent.loadKeymap(k, defaultBindings, c.getActions()); 1171 * 1172 * </code></pre> 1173 * The sets of bindings and actions may be empty but must be 1174 * non-<code>null</code>. 1175 * 1176 * @param map the keymap 1177 * @param bindings the bindings 1178 * @param actions the set of actions 1179 */ 1180 public static void loadKeymap(Keymap map, KeyBinding[] bindings, Action[] actions) { 1181 Hashtable<String, Action> h = new Hashtable<String, Action>(); 1182 for (Action a : actions) { 1183 String value = (String)a.getValue(Action.NAME); 1184 h.put((value!=null ? value:""), a); 1185 } 1186 for (KeyBinding binding : bindings) { 1187 Action a = h.get(binding.actionName); 1188 if (a != null) { 1189 map.addActionForKeyStroke(binding.key, a); 1190 } 1191 } 1192 } 1193 1194 /** 1195 * Fetches the current color used to render the 1196 * caret. 1197 * 1198 * @return the color 1199 */ 1200 public Color getCaretColor() { 1201 return caretColor; 1202 } 1203 1204 /** 1205 * Sets the current color used to render the caret. 1206 * Setting to <code>null</code> effectively restores the default color. 1207 * Setting the color results in a PropertyChange event ("caretColor") 1208 * being fired. 1209 * 1210 * @param c the color 1211 * @see #getCaretColor 1212 * @beaninfo 1213 * description: the color used to render the caret 1214 * bound: true 1215 * preferred: true 1216 */ 1217 public void setCaretColor(Color c) { 1218 Color old = caretColor; 1219 caretColor = c; 1220 firePropertyChange("caretColor", old, caretColor); 1221 } 1222 1223 /** 1224 * Fetches the current color used to render the 1225 * selection. 1226 * 1227 * @return the color 1228 */ 1229 public Color getSelectionColor() { 1230 return selectionColor; 1231 } 1232 1233 /** 1234 * Sets the current color used to render the selection. 1235 * Setting the color to <code>null</code> is the same as setting 1236 * <code>Color.white</code>. Setting the color results in a 1237 * PropertyChange event ("selectionColor"). 1238 * 1239 * @param c the color 1240 * @see #getSelectionColor 1241 * @beaninfo 1242 * description: color used to render selection background 1243 * bound: true 1244 * preferred: true 1245 */ 1246 public void setSelectionColor(Color c) { 1247 Color old = selectionColor; 1248 selectionColor = c; 1249 firePropertyChange("selectionColor", old, selectionColor); 1250 } 1251 1252 /** 1253 * Fetches the current color used to render the 1254 * selected text. 1255 * 1256 * @return the color 1257 */ 1258 public Color getSelectedTextColor() { 1259 return selectedTextColor; 1260 } 1261 1262 /** 1263 * Sets the current color used to render the selected text. 1264 * Setting the color to <code>null</code> is the same as 1265 * <code>Color.black</code>. Setting the color results in a 1266 * PropertyChange event ("selectedTextColor") being fired. 1267 * 1268 * @param c the color 1269 * @see #getSelectedTextColor 1270 * @beaninfo 1271 * description: color used to render selected text 1272 * bound: true 1273 * preferred: true 1274 */ 1275 public void setSelectedTextColor(Color c) { 1276 Color old = selectedTextColor; 1277 selectedTextColor = c; 1278 firePropertyChange("selectedTextColor", old, selectedTextColor); 1279 } 1280 1281 /** 1282 * Fetches the current color used to render the 1283 * disabled text. 1284 * 1285 * @return the color 1286 */ 1287 public Color getDisabledTextColor() { 1288 return disabledTextColor; 1289 } 1290 1291 /** 1292 * Sets the current color used to render the 1293 * disabled text. Setting the color fires off a 1294 * PropertyChange event ("disabledTextColor"). 1295 * 1296 * @param c the color 1297 * @see #getDisabledTextColor 1298 * @beaninfo 1299 * description: color used to render disabled text 1300 * bound: true 1301 * preferred: true 1302 */ 1303 public void setDisabledTextColor(Color c) { 1304 Color old = disabledTextColor; 1305 disabledTextColor = c; 1306 firePropertyChange("disabledTextColor", old, disabledTextColor); 1307 } 1308 1309 /** 1310 * Replaces the currently selected content with new content 1311 * represented by the given string. If there is no selection 1312 * this amounts to an insert of the given text. If there 1313 * is no replacement text this amounts to a removal of the 1314 * current selection. 1315 * <p> 1316 * This is the method that is used by the default implementation 1317 * of the action for inserting content that gets bound to the 1318 * keymap actions. 1319 * 1320 * @param content the content to replace the selection with 1321 */ 1322 public void replaceSelection(String content) { 1323 Document doc = getDocument(); 1324 if (doc != null) { 1325 try { 1326 boolean composedTextSaved = saveComposedText(caret.getDot()); 1327 int p0 = Math.min(caret.getDot(), caret.getMark()); 1328 int p1 = Math.max(caret.getDot(), caret.getMark()); 1329 if (doc instanceof AbstractDocument) { 1330 ((AbstractDocument)doc).replace(p0, p1 - p0, content,null); 1331 } 1332 else { 1333 if (p0 != p1) { 1334 doc.remove(p0, p1 - p0); 1335 } 1336 if (content != null && content.length() > 0) { 1337 doc.insertString(p0, content, null); 1338 } 1339 } 1340 if (composedTextSaved) { 1341 restoreComposedText(); 1342 } 1343 } catch (BadLocationException e) { 1344 UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this); 1345 } 1346 } 1347 } 1348 1349 /** 1350 * Fetches a portion of the text represented by the 1351 * component. Returns an empty string if length is 0. 1352 * 1353 * @param offs the offset ≥ 0 1354 * @param len the length ≥ 0 1355 * @return the text 1356 * @exception BadLocationException if the offset or length are invalid 1357 */ 1358 public String getText(int offs, int len) throws BadLocationException { 1359 return getDocument().getText(offs, len); 1360 } 1361 1362 /** 1363 * Converts the given location in the model to a place in 1364 * the view coordinate system. 1365 * The component must have a positive size for 1366 * this translation to be computed (i.e. layout cannot 1367 * be computed until the component has been sized). The 1368 * component does not have to be visible or painted. 1369 * 1370 * @param pos the position ≥ 0 1371 * @return the coordinates as a rectangle, with (r.x, r.y) as the location 1372 * in the coordinate system, or null if the component does 1373 * not yet have a positive size. 1374 * @exception BadLocationException if the given position does not 1375 * represent a valid location in the associated document 1376 * @see TextUI#modelToView 1377 */ 1378 public Rectangle modelToView(int pos) throws BadLocationException { 1379 return getUI().modelToView(this, pos); 1380 } 1381 1382 /** 1383 * Converts the given place in the view coordinate system 1384 * to the nearest representative location in the model. 1385 * The component must have a positive size for 1386 * this translation to be computed (i.e. layout cannot 1387 * be computed until the component has been sized). The 1388 * component does not have to be visible or painted. 1389 * 1390 * @param pt the location in the view to translate 1391 * @return the offset ≥ 0 from the start of the document, 1392 * or -1 if the component does not yet have a positive 1393 * size. 1394 * @see TextUI#viewToModel 1395 */ 1396 public int viewToModel(Point pt) { 1397 return getUI().viewToModel(this, pt); 1398 } 1399 1400 /** 1401 * Transfers the currently selected range in the associated 1402 * text model to the system clipboard, removing the contents 1403 * from the model. The current selection is reset. Does nothing 1404 * for <code>null</code> selections. 1405 * 1406 * @see java.awt.Toolkit#getSystemClipboard 1407 * @see java.awt.datatransfer.Clipboard 1408 */ 1409 public void cut() { 1410 if (isEditable() && isEnabled()) { 1411 invokeAction("cut", TransferHandler.getCutAction()); 1412 } 1413 } 1414 1415 /** 1416 * Transfers the currently selected range in the associated 1417 * text model to the system clipboard, leaving the contents 1418 * in the text model. The current selection remains intact. 1419 * Does nothing for <code>null</code> selections. 1420 * 1421 * @see java.awt.Toolkit#getSystemClipboard 1422 * @see java.awt.datatransfer.Clipboard 1423 */ 1424 public void copy() { 1425 invokeAction("copy", TransferHandler.getCopyAction()); 1426 } 1427 1428 /** 1429 * Transfers the contents of the system clipboard into the 1430 * associated text model. If there is a selection in the 1431 * associated view, it is replaced with the contents of the 1432 * clipboard. If there is no selection, the clipboard contents 1433 * are inserted in front of the current insert position in 1434 * the associated view. If the clipboard is empty, does nothing. 1435 * 1436 * @see #replaceSelection 1437 * @see java.awt.Toolkit#getSystemClipboard 1438 * @see java.awt.datatransfer.Clipboard 1439 */ 1440 public void paste() { 1441 if (isEditable() && isEnabled()) { 1442 invokeAction("paste", TransferHandler.getPasteAction()); 1443 } 1444 } 1445 1446 /** 1447 * This is a convenience method that is only useful for 1448 * <code>cut</code>, <code>copy</code> and <code>paste</code>. If 1449 * an <code>Action</code> with the name <code>name</code> does not 1450 * exist in the <code>ActionMap</code>, this will attempt to install a 1451 * <code>TransferHandler</code> and then use <code>altAction</code>. 1452 */ 1453 private void invokeAction(String name, Action altAction) { 1454 ActionMap map = getActionMap(); 1455 Action action = null; 1456 1457 if (map != null) { 1458 action = map.get(name); 1459 } 1460 if (action == null) { 1461 installDefaultTransferHandlerIfNecessary(); 1462 action = altAction; 1463 } 1464 action.actionPerformed(new ActionEvent(this, 1465 ActionEvent.ACTION_PERFORMED, (String)action. 1466 getValue(Action.NAME), 1467 EventQueue.getMostRecentEventTime(), 1468 getCurrentEventModifiers())); 1469 } 1470 1471 /** 1472 * If the current <code>TransferHandler</code> is null, this will 1473 * install a new one. 1474 */ 1475 private void installDefaultTransferHandlerIfNecessary() { 1476 if (getTransferHandler() == null) { 1477 if (defaultTransferHandler == null) { 1478 defaultTransferHandler = new DefaultTransferHandler(); 1479 } 1480 setTransferHandler(defaultTransferHandler); 1481 } 1482 } 1483 1484 /** 1485 * Moves the caret to a new position, leaving behind a mark 1486 * defined by the last time <code>setCaretPosition</code> was 1487 * called. This forms a selection. 1488 * If the document is <code>null</code>, does nothing. The position 1489 * must be between 0 and the length of the component's text or else 1490 * an exception is thrown. 1491 * 1492 * @param pos the position 1493 * @exception IllegalArgumentException if the value supplied 1494 * for <code>position</code> is less than zero or greater 1495 * than the component's text length 1496 * @see #setCaretPosition 1497 */ 1498 public void moveCaretPosition(int pos) { 1499 Document doc = getDocument(); 1500 if (doc != null) { 1501 if (pos > doc.getLength() || pos < 0) { 1502 throw new IllegalArgumentException("bad position: " + pos); 1503 } 1504 caret.moveDot(pos); 1505 } 1506 } 1507 1508 /** 1509 * The bound property name for the focus accelerator. 1510 */ 1511 public static final String FOCUS_ACCELERATOR_KEY = "focusAcceleratorKey"; 1512 1513 /** 1514 * Sets the key accelerator that will cause the receiving text 1515 * component to get the focus. The accelerator will be the 1516 * key combination of the platform-specific modifier key and 1517 * the character given (converted to upper case). For example, 1518 * the ALT key is used as a modifier on Windows and the CTRL+ALT 1519 * combination is used on Mac. By default, there is no focus 1520 * accelerator key. Any previous key accelerator setting will be 1521 * superseded. A '\0' key setting will be registered, and has the 1522 * effect of turning off the focus accelerator. When the new key 1523 * is set, a PropertyChange event (FOCUS_ACCELERATOR_KEY) will be fired. 1524 * 1525 * @param aKey the key 1526 * @see #getFocusAccelerator 1527 * @beaninfo 1528 * description: accelerator character used to grab focus 1529 * bound: true 1530 */ 1531 public void setFocusAccelerator(char aKey) { 1532 aKey = Character.toUpperCase(aKey); 1533 char old = focusAccelerator; 1534 focusAccelerator = aKey; 1535 // Fix for 4341002: value of FOCUS_ACCELERATOR_KEY is wrong. 1536 // So we fire both FOCUS_ACCELERATOR_KEY, for compatibility, 1537 // and the correct event here. 1538 firePropertyChange(FOCUS_ACCELERATOR_KEY, old, focusAccelerator); 1539 firePropertyChange("focusAccelerator", old, focusAccelerator); 1540 } 1541 1542 /** 1543 * Returns the key accelerator that will cause the receiving 1544 * text component to get the focus. Return '\0' if no focus 1545 * accelerator has been set. 1546 * 1547 * @return the key 1548 */ 1549 public char getFocusAccelerator() { 1550 return focusAccelerator; 1551 } 1552 1553 /** 1554 * Initializes from a stream. This creates a 1555 * model of the type appropriate for the component 1556 * and initializes the model from the stream. 1557 * By default this will load the model as plain 1558 * text. Previous contents of the model are discarded. 1559 * 1560 * @param in the stream to read from 1561 * @param desc an object describing the stream; this 1562 * might be a string, a File, a URL, etc. Some kinds 1563 * of documents (such as html for example) might be 1564 * able to make use of this information; if non-<code>null</code>, 1565 * it is added as a property of the document 1566 * @exception IOException as thrown by the stream being 1567 * used to initialize 1568 * @see EditorKit#createDefaultDocument 1569 * @see #setDocument 1570 * @see PlainDocument 1571 */ 1572 public void read(Reader in, Object desc) throws IOException { 1573 EditorKit kit = getUI().getEditorKit(this); 1574 Document doc = kit.createDefaultDocument(); 1575 if (desc != null) { 1576 doc.putProperty(Document.StreamDescriptionProperty, desc); 1577 } 1578 try { 1579 kit.read(in, doc, 0); 1580 setDocument(doc); 1581 } catch (BadLocationException e) { 1582 throw new IOException(e.getMessage()); 1583 } 1584 } 1585 1586 /** 1587 * Stores the contents of the model into the given 1588 * stream. By default this will store the model as plain 1589 * text. 1590 * 1591 * @param out the output stream 1592 * @exception IOException on any I/O error 1593 */ 1594 public void write(Writer out) throws IOException { 1595 Document doc = getDocument(); 1596 try { 1597 getUI().getEditorKit(this).write(out, doc, 0, doc.getLength()); 1598 } catch (BadLocationException e) { 1599 throw new IOException(e.getMessage()); 1600 } 1601 } 1602 1603 public void removeNotify() { 1604 super.removeNotify(); 1605 if (getFocusedComponent() == this) { 1606 AppContext.getAppContext().remove(FOCUSED_COMPONENT); 1607 } 1608 } 1609 1610 // --- java.awt.TextComponent methods ------------------------ 1611 1612 /** 1613 * Sets the position of the text insertion caret for the 1614 * <code>TextComponent</code>. Note that the caret tracks change, 1615 * so this may move if the underlying text of the component is changed. 1616 * If the document is <code>null</code>, does nothing. The position 1617 * must be between 0 and the length of the component's text or else 1618 * an exception is thrown. 1619 * 1620 * @param position the position 1621 * @exception IllegalArgumentException if the value supplied 1622 * for <code>position</code> is less than zero or greater 1623 * than the component's text length 1624 * @beaninfo 1625 * description: the caret position 1626 */ 1627 public void setCaretPosition(int position) { 1628 Document doc = getDocument(); 1629 if (doc != null) { 1630 if (position > doc.getLength() || position < 0) { 1631 throw new IllegalArgumentException("bad position: " + position); 1632 } 1633 caret.setDot(position); 1634 } 1635 } 1636 1637 /** 1638 * Returns the position of the text insertion caret for the 1639 * text component. 1640 * 1641 * @return the position of the text insertion caret for the 1642 * text component ≥ 0 1643 */ 1644 @Transient 1645 public int getCaretPosition() { 1646 return caret.getDot(); 1647 } 1648 1649 /** 1650 * Sets the text of this <code>TextComponent</code> 1651 * to the specified text. If the text is <code>null</code> 1652 * or empty, has the effect of simply deleting the old text. 1653 * When text has been inserted, the resulting caret location 1654 * is determined by the implementation of the caret class. 1655 * 1656 * <p> 1657 * Note that text is not a bound property, so no <code>PropertyChangeEvent 1658 * </code> is fired when it changes. To listen for changes to the text, 1659 * use <code>DocumentListener</code>. 1660 * 1661 * @param t the new text to be set 1662 * @see #getText 1663 * @see DefaultCaret 1664 * @beaninfo 1665 * description: the text of this component 1666 */ 1667 public void setText(String t) { 1668 try { 1669 Document doc = getDocument(); 1670 if (doc instanceof AbstractDocument) { 1671 ((AbstractDocument)doc).replace(0, doc.getLength(), t,null); 1672 } 1673 else { 1674 doc.remove(0, doc.getLength()); 1675 doc.insertString(0, t, null); 1676 } 1677 } catch (BadLocationException e) { 1678 UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this); 1679 } 1680 } 1681 1682 /** 1683 * Returns the text contained in this <code>TextComponent</code>. 1684 * If the underlying document is <code>null</code>, 1685 * will give a <code>NullPointerException</code>. 1686 * 1687 * Note that text is not a bound property, so no <code>PropertyChangeEvent 1688 * </code> is fired when it changes. To listen for changes to the text, 1689 * use <code>DocumentListener</code>. 1690 * 1691 * @return the text 1692 * @exception NullPointerException if the document is <code>null</code> 1693 * @see #setText 1694 */ 1695 public String getText() { 1696 Document doc = getDocument(); 1697 String txt; 1698 try { 1699 txt = doc.getText(0, doc.getLength()); 1700 } catch (BadLocationException e) { 1701 txt = null; 1702 } 1703 return txt; 1704 } 1705 1706 /** 1707 * Returns the selected text contained in this 1708 * <code>TextComponent</code>. If the selection is 1709 * <code>null</code> or the document empty, returns <code>null</code>. 1710 * 1711 * @return the text 1712 * @exception IllegalArgumentException if the selection doesn't 1713 * have a valid mapping into the document for some reason 1714 * @see #setText 1715 */ 1716 public String getSelectedText() { 1717 String txt = null; 1718 int p0 = Math.min(caret.getDot(), caret.getMark()); 1719 int p1 = Math.max(caret.getDot(), caret.getMark()); 1720 if (p0 != p1) { 1721 try { 1722 Document doc = getDocument(); 1723 txt = doc.getText(p0, p1 - p0); 1724 } catch (BadLocationException e) { 1725 throw new IllegalArgumentException(e.getMessage()); 1726 } 1727 } 1728 return txt; 1729 } 1730 1731 /** 1732 * Returns the boolean indicating whether this 1733 * <code>TextComponent</code> is editable or not. 1734 * 1735 * @return the boolean value 1736 * @see #setEditable 1737 */ 1738 public boolean isEditable() { 1739 return editable; 1740 } 1741 1742 /** 1743 * Sets the specified boolean to indicate whether or not this 1744 * <code>TextComponent</code> should be editable. 1745 * A PropertyChange event ("editable") is fired when the 1746 * state is changed. 1747 * 1748 * @param b the boolean to be set 1749 * @see #isEditable 1750 * @beaninfo 1751 * description: specifies if the text can be edited 1752 * bound: true 1753 */ 1754 public void setEditable(boolean b) { 1755 if (b != editable) { 1756 boolean oldVal = editable; 1757 editable = b; 1758 enableInputMethods(editable); 1759 firePropertyChange("editable", Boolean.valueOf(oldVal), Boolean.valueOf(editable)); 1760 repaint(); 1761 } 1762 } 1763 1764 /** 1765 * Returns the selected text's start position. Return 0 for an 1766 * empty document, or the value of dot if no selection. 1767 * 1768 * @return the start position ≥ 0 1769 */ 1770 @Transient 1771 public int getSelectionStart() { 1772 int start = Math.min(caret.getDot(), caret.getMark()); 1773 return start; 1774 } 1775 1776 /** 1777 * Sets the selection start to the specified position. The new 1778 * starting point is constrained to be before or at the current 1779 * selection end. 1780 * <p> 1781 * This is available for backward compatibility to code 1782 * that called this method on <code>java.awt.TextComponent</code>. 1783 * This is implemented to forward to the <code>Caret</code> 1784 * implementation which is where the actual selection is maintained. 1785 * 1786 * @param selectionStart the start position of the text ≥ 0 1787 * @beaninfo 1788 * description: starting location of the selection. 1789 */ 1790 public void setSelectionStart(int selectionStart) { 1791 /* Route through select method to enforce consistent policy 1792 * between selectionStart and selectionEnd. 1793 */ 1794 select(selectionStart, getSelectionEnd()); 1795 } 1796 1797 /** 1798 * Returns the selected text's end position. Return 0 if the document 1799 * is empty, or the value of dot if there is no selection. 1800 * 1801 * @return the end position ≥ 0 1802 */ 1803 @Transient 1804 public int getSelectionEnd() { 1805 int end = Math.max(caret.getDot(), caret.getMark()); 1806 return end; 1807 } 1808 1809 /** 1810 * Sets the selection end to the specified position. The new 1811 * end point is constrained to be at or after the current 1812 * selection start. 1813 * <p> 1814 * This is available for backward compatibility to code 1815 * that called this method on <code>java.awt.TextComponent</code>. 1816 * This is implemented to forward to the <code>Caret</code> 1817 * implementation which is where the actual selection is maintained. 1818 * 1819 * @param selectionEnd the end position of the text ≥ 0 1820 * @beaninfo 1821 * description: ending location of the selection. 1822 */ 1823 public void setSelectionEnd(int selectionEnd) { 1824 /* Route through select method to enforce consistent policy 1825 * between selectionStart and selectionEnd. 1826 */ 1827 select(getSelectionStart(), selectionEnd); 1828 } 1829 1830 /** 1831 * Selects the text between the specified start and end positions. 1832 * <p> 1833 * This method sets the start and end positions of the 1834 * selected text, enforcing the restriction that the start position 1835 * must be greater than or equal to zero. The end position must be 1836 * greater than or equal to the start position, and less than or 1837 * equal to the length of the text component's text. 1838 * <p> 1839 * If the caller supplies values that are inconsistent or out of 1840 * bounds, the method enforces these constraints silently, and 1841 * without failure. Specifically, if the start position or end 1842 * position is greater than the length of the text, it is reset to 1843 * equal the text length. If the start position is less than zero, 1844 * it is reset to zero, and if the end position is less than the 1845 * start position, it is reset to the start position. 1846 * <p> 1847 * This call is provided for backward compatibility. 1848 * It is routed to a call to <code>setCaretPosition</code> 1849 * followed by a call to <code>moveCaretPosition</code>. 1850 * The preferred way to manage selection is by calling 1851 * those methods directly. 1852 * 1853 * @param selectionStart the start position of the text 1854 * @param selectionEnd the end position of the text 1855 * @see #setCaretPosition 1856 * @see #moveCaretPosition 1857 */ 1858 public void select(int selectionStart, int selectionEnd) { 1859 // argument adjustment done by java.awt.TextComponent 1860 int docLength = getDocument().getLength(); 1861 1862 if (selectionStart < 0) { 1863 selectionStart = 0; 1864 } 1865 if (selectionStart > docLength) { 1866 selectionStart = docLength; 1867 } 1868 if (selectionEnd > docLength) { 1869 selectionEnd = docLength; 1870 } 1871 if (selectionEnd < selectionStart) { 1872 selectionEnd = selectionStart; 1873 } 1874 1875 setCaretPosition(selectionStart); 1876 moveCaretPosition(selectionEnd); 1877 } 1878 1879 /** 1880 * Selects all the text in the <code>TextComponent</code>. 1881 * Does nothing on a <code>null</code> or empty document. 1882 */ 1883 public void selectAll() { 1884 Document doc = getDocument(); 1885 if (doc != null) { 1886 setCaretPosition(0); 1887 moveCaretPosition(doc.getLength()); 1888 } 1889 } 1890 1891 // --- Tooltip Methods --------------------------------------------- 1892 1893 /** 1894 * Returns the string to be used as the tooltip for <code>event</code>. 1895 * This will return one of: 1896 * <ol> 1897 * <li>If <code>setToolTipText</code> has been invoked with a 1898 * non-<code>null</code> 1899 * value, it will be returned, otherwise 1900 * <li>The value from invoking <code>getToolTipText</code> on 1901 * the UI will be returned. 1902 * </ol> 1903 * By default <code>JTextComponent</code> does not register 1904 * itself with the <code>ToolTipManager</code>. 1905 * This means that tooltips will NOT be shown from the 1906 * <code>TextUI</code> unless <code>registerComponent</code> has 1907 * been invoked on the <code>ToolTipManager</code>. 1908 * 1909 * @param event the event in question 1910 * @return the string to be used as the tooltip for <code>event</code> 1911 * @see javax.swing.JComponent#setToolTipText 1912 * @see javax.swing.plaf.TextUI#getToolTipText 1913 * @see javax.swing.ToolTipManager#registerComponent 1914 */ 1915 public String getToolTipText(MouseEvent event) { 1916 String retValue = super.getToolTipText(event); 1917 1918 if (retValue == null) { 1919 TextUI ui = getUI(); 1920 if (ui != null) { 1921 retValue = ui.getToolTipText(this, new Point(event.getX(), 1922 event.getY())); 1923 } 1924 } 1925 return retValue; 1926 } 1927 1928 // --- Scrollable methods --------------------------------------------- 1929 1930 /** 1931 * Returns the preferred size of the viewport for a view component. 1932 * This is implemented to do the default behavior of returning 1933 * the preferred size of the component. 1934 * 1935 * @return the <code>preferredSize</code> of a <code>JViewport</code> 1936 * whose view is this <code>Scrollable</code> 1937 */ 1938 public Dimension getPreferredScrollableViewportSize() { 1939 return getPreferredSize(); 1940 } 1941 1942 1943 /** 1944 * Components that display logical rows or columns should compute 1945 * the scroll increment that will completely expose one new row 1946 * or column, depending on the value of orientation. Ideally, 1947 * components should handle a partially exposed row or column by 1948 * returning the distance required to completely expose the item. 1949 * <p> 1950 * The default implementation of this is to simply return 10% of 1951 * the visible area. Subclasses are likely to be able to provide 1952 * a much more reasonable value. 1953 * 1954 * @param visibleRect the view area visible within the viewport 1955 * @param orientation either <code>SwingConstants.VERTICAL</code> or 1956 * <code>SwingConstants.HORIZONTAL</code> 1957 * @param direction less than zero to scroll up/left, greater than 1958 * zero for down/right 1959 * @return the "unit" increment for scrolling in the specified direction 1960 * @exception IllegalArgumentException for an invalid orientation 1961 * @see JScrollBar#setUnitIncrement 1962 */ 1963 public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { 1964 switch(orientation) { 1965 case SwingConstants.VERTICAL: 1966 return visibleRect.height / 10; 1967 case SwingConstants.HORIZONTAL: 1968 return visibleRect.width / 10; 1969 default: 1970 throw new IllegalArgumentException("Invalid orientation: " + orientation); 1971 } 1972 } 1973 1974 1975 /** 1976 * Components that display logical rows or columns should compute 1977 * the scroll increment that will completely expose one block 1978 * of rows or columns, depending on the value of orientation. 1979 * <p> 1980 * The default implementation of this is to simply return the visible 1981 * area. Subclasses will likely be able to provide a much more 1982 * reasonable value. 1983 * 1984 * @param visibleRect the view area visible within the viewport 1985 * @param orientation either <code>SwingConstants.VERTICAL</code> or 1986 * <code>SwingConstants.HORIZONTAL</code> 1987 * @param direction less than zero to scroll up/left, greater than zero 1988 * for down/right 1989 * @return the "block" increment for scrolling in the specified direction 1990 * @exception IllegalArgumentException for an invalid orientation 1991 * @see JScrollBar#setBlockIncrement 1992 */ 1993 public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { 1994 switch(orientation) { 1995 case SwingConstants.VERTICAL: 1996 return visibleRect.height; 1997 case SwingConstants.HORIZONTAL: 1998 return visibleRect.width; 1999 default: 2000 throw new IllegalArgumentException("Invalid orientation: " + orientation); 2001 } 2002 } 2003 2004 2005 /** 2006 * Returns true if a viewport should always force the width of this 2007 * <code>Scrollable</code> to match the width of the viewport. 2008 * For example a normal text view that supported line wrapping 2009 * would return true here, since it would be undesirable for 2010 * wrapped lines to disappear beyond the right 2011 * edge of the viewport. Note that returning true for a 2012 * <code>Scrollable</code> whose ancestor is a <code>JScrollPane</code> 2013 * effectively disables horizontal scrolling. 2014 * <p> 2015 * Scrolling containers, like <code>JViewport</code>, 2016 * will use this method each time they are validated. 2017 * 2018 * @return true if a viewport should force the <code>Scrollable</code>s 2019 * width to match its own 2020 */ 2021 public boolean getScrollableTracksViewportWidth() { 2022 Container parent = SwingUtilities.getUnwrappedParent(this); 2023 if (parent instanceof JViewport) { 2024 return parent.getWidth() > getPreferredSize().width; 2025 } 2026 return false; 2027 } 2028 2029 /** 2030 * Returns true if a viewport should always force the height of this 2031 * <code>Scrollable</code> to match the height of the viewport. 2032 * For example a columnar text view that flowed text in left to 2033 * right columns could effectively disable vertical scrolling by 2034 * returning true here. 2035 * <p> 2036 * Scrolling containers, like <code>JViewport</code>, 2037 * will use this method each time they are validated. 2038 * 2039 * @return true if a viewport should force the Scrollables height 2040 * to match its own 2041 */ 2042 public boolean getScrollableTracksViewportHeight() { 2043 Container parent = SwingUtilities.getUnwrappedParent(this); 2044 if (parent instanceof JViewport) { 2045 return parent.getHeight() > getPreferredSize().height; 2046 } 2047 return false; 2048 } 2049 2050 2051 ////////////////// 2052 // Printing Support 2053 ////////////////// 2054 2055 /** 2056 * A convenience print method that displays a print dialog, and then 2057 * prints this {@code JTextComponent} in <i>interactive</i> mode with no 2058 * header or footer text. Note: this method 2059 * blocks until printing is done. 2060 * <p> 2061 * Note: In <i>headless</i> mode, no dialogs will be shown. 2062 * 2063 * <p> This method calls the full featured 2064 * {@link #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean) 2065 * print} method to perform printing. 2066 * @return {@code true}, unless printing is canceled by the user 2067 * @throws PrinterException if an error in the print system causes the job 2068 * to be aborted 2069 * @throws SecurityException if this thread is not allowed to 2070 * initiate a print job request 2071 * 2072 * @see #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean) 2073 * 2074 * @since 1.6 2075 */ 2076 2077 public boolean print() throws PrinterException { 2078 return print(null, null, true, null, null, true); 2079 } 2080 2081 /** 2082 * A convenience print method that displays a print dialog, and then 2083 * prints this {@code JTextComponent} in <i>interactive</i> mode with 2084 * the specified header and footer text. Note: this method 2085 * blocks until printing is done. 2086 * <p> 2087 * Note: In <i>headless</i> mode, no dialogs will be shown. 2088 * 2089 * <p> This method calls the full featured 2090 * {@link #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean) 2091 * print} method to perform printing. 2092 * @param headerFormat the text, in {@code MessageFormat}, to be 2093 * used as the header, or {@code null} for no header 2094 * @param footerFormat the text, in {@code MessageFormat}, to be 2095 * used as the footer, or {@code null} for no footer 2096 * @return {@code true}, unless printing is canceled by the user 2097 * @throws PrinterException if an error in the print system causes the job 2098 * to be aborted 2099 * @throws SecurityException if this thread is not allowed to 2100 * initiate a print job request 2101 * 2102 * @see #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean) 2103 * @see java.text.MessageFormat 2104 * @since 1.6 2105 */ 2106 public boolean print(final MessageFormat headerFormat, 2107 final MessageFormat footerFormat) throws PrinterException { 2108 return print(headerFormat, footerFormat, true, null, null, true); 2109 } 2110 2111 /** 2112 * Prints the content of this {@code JTextComponent}. Note: this method 2113 * blocks until printing is done. 2114 * 2115 * <p> 2116 * Page header and footer text can be added to the output by providing 2117 * {@code MessageFormat} arguments. The printing code requests 2118 * {@code Strings} from the formats, providing a single item which may be 2119 * included in the formatted string: an {@code Integer} representing the 2120 * current page number. 2121 * 2122 * <p> 2123 * {@code showPrintDialog boolean} parameter allows you to specify whether 2124 * a print dialog is displayed to the user. When it is, the user 2125 * may use the dialog to change printing attributes or even cancel the 2126 * print. 2127 * 2128 * <p> 2129 * {@code service} allows you to provide the initial 2130 * {@code PrintService} for the print dialog, or to specify 2131 * {@code PrintService} to print to when the dialog is not shown. 2132 * 2133 * <p> 2134 * {@code attributes} can be used to provide the 2135 * initial values for the print dialog, or to supply any needed 2136 * attributes when the dialog is not shown. {@code attributes} can 2137 * be used to control how the job will print, for example 2138 * <i>duplex</i> or <i>single-sided</i>. 2139 * 2140 * <p> 2141 * {@code interactive boolean} parameter allows you to specify 2142 * whether to perform printing in <i>interactive</i> 2143 * mode. If {@code true}, a progress dialog, with an abort option, 2144 * is displayed for the duration of printing. This dialog is 2145 * <i>modal</i> when {@code print} is invoked on the <i>Event Dispatch 2146 * Thread</i> and <i>non-modal</i> otherwise. <b>Warning</b>: 2147 * calling this method on the <i>Event Dispatch Thread</i> with {@code 2148 * interactive false} blocks <i>all</i> events, including repaints, from 2149 * being processed until printing is complete. It is only 2150 * recommended when printing from an application with no 2151 * visible GUI. 2152 * 2153 * <p> 2154 * Note: In <i>headless</i> mode, {@code showPrintDialog} and 2155 * {@code interactive} parameters are ignored and no dialogs are 2156 * shown. 2157 * 2158 * <p> 2159 * This method ensures the {@code document} is not mutated during printing. 2160 * To indicate it visually, {@code setEnabled(false)} is set for the 2161 * duration of printing. 2162 * 2163 * <p> 2164 * This method uses {@link #getPrintable} to render document content. 2165 * 2166 * <p> 2167 * This method is thread-safe, although most Swing methods are not. Please 2168 * see <A 2169 * HREF="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"> 2170 * Concurrency in Swing</A> for more information. 2171 * 2172 * <p> 2173 * <b>Sample Usage</b>. This code snippet shows a cross-platform print 2174 * dialog and then prints the {@code JTextComponent} in <i>interactive</i> mode 2175 * unless the user cancels the dialog: 2176 * 2177 * <pre> 2178 * textComponent.print(new MessageFormat("My text component header"), 2179 * new MessageFormat("Footer. Page - {0}"), true, null, null, true); 2180 * </pre> 2181 * <p> 2182 * Executing this code off the <i>Event Dispatch Thread</i> 2183 * performs printing on the <i>background</i>. 2184 * The following pattern might be used for <i>background</i> 2185 * printing: 2186 * <pre> 2187 * FutureTask<Boolean> future = 2188 * new FutureTask<Boolean>( 2189 * new Callable<Boolean>() { 2190 * public Boolean call() { 2191 * return textComponent.print(.....); 2192 * } 2193 * }); 2194 * executor.execute(future); 2195 * </pre> 2196 * 2197 * @param headerFormat the text, in {@code MessageFormat}, to be 2198 * used as the header, or {@code null} for no header 2199 * @param footerFormat the text, in {@code MessageFormat}, to be 2200 * used as the footer, or {@code null} for no footer 2201 * @param showPrintDialog {@code true} to display a print dialog, 2202 * {@code false} otherwise 2203 * @param service initial {@code PrintService}, or {@code null} for the 2204 * default 2205 * @param attributes the job attributes to be applied to the print job, or 2206 * {@code null} for none 2207 * @param interactive whether to print in an interactive mode 2208 * @return {@code true}, unless printing is canceled by the user 2209 * @throws PrinterException if an error in the print system causes the job 2210 * to be aborted 2211 * @throws SecurityException if this thread is not allowed to 2212 * initiate a print job request 2213 * 2214 * @see #getPrintable 2215 * @see java.text.MessageFormat 2216 * @see java.awt.GraphicsEnvironment#isHeadless 2217 * @see java.util.concurrent.FutureTask 2218 * 2219 * @since 1.6 2220 */ 2221 public boolean print(final MessageFormat headerFormat, 2222 final MessageFormat footerFormat, 2223 final boolean showPrintDialog, 2224 final PrintService service, 2225 final PrintRequestAttributeSet attributes, 2226 final boolean interactive) 2227 throws PrinterException { 2228 2229 final PrinterJob job = PrinterJob.getPrinterJob(); 2230 final Printable printable; 2231 final PrintingStatus printingStatus; 2232 final boolean isHeadless = GraphicsEnvironment.isHeadless(); 2233 final boolean isEventDispatchThread = 2234 SwingUtilities.isEventDispatchThread(); 2235 final Printable textPrintable = getPrintable(headerFormat, footerFormat); 2236 if (interactive && ! isHeadless) { 2237 printingStatus = 2238 PrintingStatus.createPrintingStatus(this, job); 2239 printable = 2240 printingStatus.createNotificationPrintable(textPrintable); 2241 } else { 2242 printingStatus = null; 2243 printable = textPrintable; 2244 } 2245 2246 if (service != null) { 2247 job.setPrintService(service); 2248 } 2249 2250 job.setPrintable(printable); 2251 2252 final PrintRequestAttributeSet attr = (attributes == null) 2253 ? new HashPrintRequestAttributeSet() 2254 : attributes; 2255 2256 if (showPrintDialog && ! isHeadless && ! job.printDialog(attr)) { 2257 return false; 2258 } 2259 2260 /* 2261 * there are three cases for printing: 2262 * 1. print non interactively (! interactive || isHeadless) 2263 * 2. print interactively off EDT 2264 * 3. print interactively on EDT 2265 * 2266 * 1 and 2 prints on the current thread (3 prints on another thread) 2267 * 2 and 3 deal with PrintingStatusDialog 2268 */ 2269 final Callable<Object> doPrint = 2270 new Callable<Object>() { 2271 public Object call() throws Exception { 2272 try { 2273 job.print(attr); 2274 } finally { 2275 if (printingStatus != null) { 2276 printingStatus.dispose(); 2277 } 2278 } 2279 return null; 2280 } 2281 }; 2282 2283 final FutureTask<Object> futurePrinting = 2284 new FutureTask<Object>(doPrint); 2285 2286 final Runnable runnablePrinting = 2287 new Runnable() { 2288 public void run() { 2289 //disable component 2290 boolean wasEnabled = false; 2291 if (isEventDispatchThread) { 2292 if (isEnabled()) { 2293 wasEnabled = true; 2294 setEnabled(false); 2295 } 2296 } else { 2297 try { 2298 wasEnabled = SwingUtilities2.submit( 2299 new Callable<Boolean>() { 2300 public Boolean call() throws Exception { 2301 boolean rv = isEnabled(); 2302 if (rv) { 2303 setEnabled(false); 2304 } 2305 return rv; 2306 } 2307 }).get(); 2308 } catch (InterruptedException e) { 2309 throw new RuntimeException(e); 2310 } catch (ExecutionException e) { 2311 Throwable cause = e.getCause(); 2312 if (cause instanceof Error) { 2313 throw (Error) cause; 2314 } 2315 if (cause instanceof RuntimeException) { 2316 throw (RuntimeException) cause; 2317 } 2318 throw new AssertionError(cause); 2319 } 2320 } 2321 2322 getDocument().render(futurePrinting); 2323 2324 //enable component 2325 if (wasEnabled) { 2326 if (isEventDispatchThread) { 2327 setEnabled(true); 2328 } else { 2329 try { 2330 SwingUtilities2.submit( 2331 new Runnable() { 2332 public void run() { 2333 setEnabled(true); 2334 } 2335 }, null).get(); 2336 } catch (InterruptedException e) { 2337 throw new RuntimeException(e); 2338 } catch (ExecutionException e) { 2339 Throwable cause = e.getCause(); 2340 if (cause instanceof Error) { 2341 throw (Error) cause; 2342 } 2343 if (cause instanceof RuntimeException) { 2344 throw (RuntimeException) cause; 2345 } 2346 throw new AssertionError(cause); 2347 } 2348 } 2349 } 2350 } 2351 }; 2352 2353 if (! interactive || isHeadless) { 2354 runnablePrinting.run(); 2355 } else { 2356 if (isEventDispatchThread) { 2357 (new Thread(runnablePrinting)).start(); 2358 printingStatus.showModal(true); 2359 } else { 2360 printingStatus.showModal(false); 2361 runnablePrinting.run(); 2362 } 2363 } 2364 2365 //the printing is done successfully or otherwise. 2366 //dialog is hidden if needed. 2367 try { 2368 futurePrinting.get(); 2369 } catch (InterruptedException e) { 2370 throw new RuntimeException(e); 2371 } catch (ExecutionException e) { 2372 Throwable cause = e.getCause(); 2373 if (cause instanceof PrinterAbortException) { 2374 if (printingStatus != null 2375 && printingStatus.isAborted()) { 2376 return false; 2377 } else { 2378 throw (PrinterAbortException) cause; 2379 } 2380 } else if (cause instanceof PrinterException) { 2381 throw (PrinterException) cause; 2382 } else if (cause instanceof RuntimeException) { 2383 throw (RuntimeException) cause; 2384 } else if (cause instanceof Error) { 2385 throw (Error) cause; 2386 } else { 2387 throw new AssertionError(cause); 2388 } 2389 } 2390 return true; 2391 } 2392 2393 2394 /** 2395 * Returns a {@code Printable} to use for printing the content of this 2396 * {@code JTextComponent}. The returned {@code Printable} prints 2397 * the document as it looks on the screen except being reformatted 2398 * to fit the paper. 2399 * The returned {@code Printable} can be wrapped inside another 2400 * {@code Printable} in order to create complex reports and 2401 * documents. 2402 * 2403 * 2404 * <p> 2405 * The returned {@code Printable} shares the {@code document} with this 2406 * {@code JTextComponent}. It is the responsibility of the developer to 2407 * ensure that the {@code document} is not mutated while this {@code Printable} 2408 * is used. Printing behavior is undefined when the {@code document} is 2409 * mutated during printing. 2410 * 2411 * <p> 2412 * Page header and footer text can be added to the output by providing 2413 * {@code MessageFormat} arguments. The printing code requests 2414 * {@code Strings} from the formats, providing a single item which may be 2415 * included in the formatted string: an {@code Integer} representing the 2416 * current page number. 2417 * 2418 * <p> 2419 * The returned {@code Printable} when printed, formats the 2420 * document content appropriately for the page size. For correct 2421 * line wrapping the {@code imageable width} of all pages must be the 2422 * same. See {@link java.awt.print.PageFormat#getImageableWidth}. 2423 * 2424 * <p> 2425 * This method is thread-safe, although most Swing methods are not. Please 2426 * see <A 2427 * HREF="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"> 2428 * Concurrency in Swing</A> for more information. 2429 * 2430 * <p> 2431 * The returned {@code Printable} can be printed on any thread. 2432 * 2433 * <p> 2434 * This implementation returned {@code Printable} performs all painting on 2435 * the <i>Event Dispatch Thread</i>, regardless of what thread it is 2436 * used on. 2437 * 2438 * @param headerFormat the text, in {@code MessageFormat}, to be 2439 * used as the header, or {@code null} for no header 2440 * @param footerFormat the text, in {@code MessageFormat}, to be 2441 * used as the footer, or {@code null} for no footer 2442 * @return a {@code Printable} for use in printing content of this 2443 * {@code JTextComponent} 2444 * 2445 * 2446 * @see java.awt.print.Printable 2447 * @see java.awt.print.PageFormat 2448 * @see javax.swing.text.Document#render(java.lang.Runnable) 2449 * 2450 * @since 1.6 2451 */ 2452 public Printable getPrintable(final MessageFormat headerFormat, 2453 final MessageFormat footerFormat) { 2454 return TextComponentPrintable.getPrintable( 2455 this, headerFormat, footerFormat); 2456 } 2457 2458 2459 ///////////////// 2460 // Accessibility support 2461 //////////////// 2462 2463 2464 /** 2465 * Gets the <code>AccessibleContext</code> associated with this 2466 * <code>JTextComponent</code>. For text components, 2467 * the <code>AccessibleContext</code> takes the form of an 2468 * <code>AccessibleJTextComponent</code>. 2469 * A new <code>AccessibleJTextComponent</code> instance 2470 * is created if necessary. 2471 * 2472 * @return an <code>AccessibleJTextComponent</code> that serves as the 2473 * <code>AccessibleContext</code> of this 2474 * <code>JTextComponent</code> 2475 */ 2476 public AccessibleContext getAccessibleContext() { 2477 if (accessibleContext == null) { 2478 accessibleContext = new AccessibleJTextComponent(); 2479 } 2480 return accessibleContext; 2481 } 2482 2483 /** 2484 * This class implements accessibility support for the 2485 * <code>JTextComponent</code> class. It provides an implementation of 2486 * the Java Accessibility API appropriate to menu user-interface elements. 2487 * <p> 2488 * <strong>Warning:</strong> 2489 * Serialized objects of this class will not be compatible with 2490 * future Swing releases. The current serialization support is 2491 * appropriate for short term storage or RMI between applications running 2492 * the same version of Swing. As of 1.4, support for long term storage 2493 * of all JavaBeans™ 2494 * has been added to the <code>java.beans</code> package. 2495 * Please see {@link java.beans.XMLEncoder}. 2496 */ 2497 @SuppressWarnings("serial") // Same-version serialization only 2498 public class AccessibleJTextComponent extends AccessibleJComponent 2499 implements AccessibleText, CaretListener, DocumentListener, 2500 AccessibleAction, AccessibleEditableText, 2501 AccessibleExtendedText { 2502 2503 int caretPos; 2504 Point oldLocationOnScreen; 2505 2506 /** 2507 * Constructs an AccessibleJTextComponent. Adds a listener to track 2508 * caret change. 2509 */ 2510 public AccessibleJTextComponent() { 2511 Document doc = JTextComponent.this.getDocument(); 2512 if (doc != null) { 2513 doc.addDocumentListener(this); 2514 } 2515 JTextComponent.this.addCaretListener(this); 2516 caretPos = getCaretPosition(); 2517 2518 try { 2519 oldLocationOnScreen = getLocationOnScreen(); 2520 } catch (IllegalComponentStateException iae) { 2521 } 2522 2523 // Fire a ACCESSIBLE_VISIBLE_DATA_PROPERTY PropertyChangeEvent 2524 // when the text component moves (e.g., when scrolling). 2525 // Using an anonymous class since making AccessibleJTextComponent 2526 // implement ComponentListener would be an API change. 2527 JTextComponent.this.addComponentListener(new ComponentAdapter() { 2528 2529 public void componentMoved(ComponentEvent e) { 2530 try { 2531 Point newLocationOnScreen = getLocationOnScreen(); 2532 firePropertyChange(ACCESSIBLE_VISIBLE_DATA_PROPERTY, 2533 oldLocationOnScreen, 2534 newLocationOnScreen); 2535 2536 oldLocationOnScreen = newLocationOnScreen; 2537 } catch (IllegalComponentStateException iae) { 2538 } 2539 } 2540 }); 2541 } 2542 2543 /** 2544 * Handles caret updates (fire appropriate property change event, 2545 * which are AccessibleContext.ACCESSIBLE_CARET_PROPERTY and 2546 * AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY). 2547 * This keeps track of the dot position internally. When the caret 2548 * moves, the internal position is updated after firing the event. 2549 * 2550 * @param e the CaretEvent 2551 */ 2552 public void caretUpdate(CaretEvent e) { 2553 int dot = e.getDot(); 2554 int mark = e.getMark(); 2555 if (caretPos != dot) { 2556 // the caret moved 2557 firePropertyChange(ACCESSIBLE_CARET_PROPERTY, 2558 new Integer(caretPos), new Integer(dot)); 2559 caretPos = dot; 2560 2561 try { 2562 oldLocationOnScreen = getLocationOnScreen(); 2563 } catch (IllegalComponentStateException iae) { 2564 } 2565 } 2566 if (mark != dot) { 2567 // there is a selection 2568 firePropertyChange(ACCESSIBLE_SELECTION_PROPERTY, null, 2569 getSelectedText()); 2570 } 2571 } 2572 2573 // DocumentListener methods 2574 2575 /** 2576 * Handles document insert (fire appropriate property change event 2577 * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). 2578 * This tracks the changed offset via the event. 2579 * 2580 * @param e the DocumentEvent 2581 */ 2582 public void insertUpdate(DocumentEvent e) { 2583 final Integer pos = new Integer (e.getOffset()); 2584 if (SwingUtilities.isEventDispatchThread()) { 2585 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos); 2586 } else { 2587 Runnable doFire = new Runnable() { 2588 public void run() { 2589 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, 2590 null, pos); 2591 } 2592 }; 2593 SwingUtilities.invokeLater(doFire); 2594 } 2595 } 2596 2597 /** 2598 * Handles document remove (fire appropriate property change event, 2599 * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). 2600 * This tracks the changed offset via the event. 2601 * 2602 * @param e the DocumentEvent 2603 */ 2604 public void removeUpdate(DocumentEvent e) { 2605 final Integer pos = new Integer (e.getOffset()); 2606 if (SwingUtilities.isEventDispatchThread()) { 2607 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos); 2608 } else { 2609 Runnable doFire = new Runnable() { 2610 public void run() { 2611 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, 2612 null, pos); 2613 } 2614 }; 2615 SwingUtilities.invokeLater(doFire); 2616 } 2617 } 2618 2619 /** 2620 * Handles document remove (fire appropriate property change event, 2621 * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). 2622 * This tracks the changed offset via the event. 2623 * 2624 * @param e the DocumentEvent 2625 */ 2626 public void changedUpdate(DocumentEvent e) { 2627 final Integer pos = new Integer (e.getOffset()); 2628 if (SwingUtilities.isEventDispatchThread()) { 2629 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos); 2630 } else { 2631 Runnable doFire = new Runnable() { 2632 public void run() { 2633 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, 2634 null, pos); 2635 } 2636 }; 2637 SwingUtilities.invokeLater(doFire); 2638 } 2639 } 2640 2641 /** 2642 * Gets the state set of the JTextComponent. 2643 * The AccessibleStateSet of an object is composed of a set of 2644 * unique AccessibleState's. A change in the AccessibleStateSet 2645 * of an object will cause a PropertyChangeEvent to be fired 2646 * for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property. 2647 * 2648 * @return an instance of AccessibleStateSet containing the 2649 * current state set of the object 2650 * @see AccessibleStateSet 2651 * @see AccessibleState 2652 * @see #addPropertyChangeListener 2653 */ 2654 public AccessibleStateSet getAccessibleStateSet() { 2655 AccessibleStateSet states = super.getAccessibleStateSet(); 2656 if (JTextComponent.this.isEditable()) { 2657 states.add(AccessibleState.EDITABLE); 2658 } 2659 return states; 2660 } 2661 2662 2663 /** 2664 * Gets the role of this object. 2665 * 2666 * @return an instance of AccessibleRole describing the role of the 2667 * object (AccessibleRole.TEXT) 2668 * @see AccessibleRole 2669 */ 2670 public AccessibleRole getAccessibleRole() { 2671 return AccessibleRole.TEXT; 2672 } 2673 2674 /** 2675 * Get the AccessibleText associated with this object. In the 2676 * implementation of the Java Accessibility API for this class, 2677 * return this object, which is responsible for implementing the 2678 * AccessibleText interface on behalf of itself. 2679 * 2680 * @return this object 2681 */ 2682 public AccessibleText getAccessibleText() { 2683 return this; 2684 } 2685 2686 2687 // --- interface AccessibleText methods ------------------------ 2688 2689 /** 2690 * Many of these methods are just convenience methods; they 2691 * just call the equivalent on the parent 2692 */ 2693 2694 /** 2695 * Given a point in local coordinates, return the zero-based index 2696 * of the character under that Point. If the point is invalid, 2697 * this method returns -1. 2698 * 2699 * @param p the Point in local coordinates 2700 * @return the zero-based index of the character under Point p. 2701 */ 2702 public int getIndexAtPoint(Point p) { 2703 if (p == null) { 2704 return -1; 2705 } 2706 return JTextComponent.this.viewToModel(p); 2707 } 2708 2709 /** 2710 * Gets the editor's drawing rectangle. Stolen 2711 * from the unfortunately named 2712 * BasicTextUI.getVisibleEditorRect() 2713 * 2714 * @return the bounding box for the root view 2715 */ 2716 Rectangle getRootEditorRect() { 2717 Rectangle alloc = JTextComponent.this.getBounds(); 2718 if ((alloc.width > 0) && (alloc.height > 0)) { 2719 alloc.x = alloc.y = 0; 2720 Insets insets = JTextComponent.this.getInsets(); 2721 alloc.x += insets.left; 2722 alloc.y += insets.top; 2723 alloc.width -= insets.left + insets.right; 2724 alloc.height -= insets.top + insets.bottom; 2725 return alloc; 2726 } 2727 return null; 2728 } 2729 2730 /** 2731 * Determines the bounding box of the character at the given 2732 * index into the string. The bounds are returned in local 2733 * coordinates. If the index is invalid a null rectangle 2734 * is returned. 2735 * 2736 * The screen coordinates returned are "unscrolled coordinates" 2737 * if the JTextComponent is contained in a JScrollPane in which 2738 * case the resulting rectangle should be composed with the parent 2739 * coordinates. A good algorithm to use is: 2740 * <pre> 2741 * Accessible a: 2742 * AccessibleText at = a.getAccessibleText(); 2743 * AccessibleComponent ac = a.getAccessibleComponent(); 2744 * Rectangle r = at.getCharacterBounds(); 2745 * Point p = ac.getLocation(); 2746 * r.x += p.x; 2747 * r.y += p.y; 2748 * </pre> 2749 * 2750 * Note: the JTextComponent must have a valid size (e.g. have 2751 * been added to a parent container whose ancestor container 2752 * is a valid top-level window) for this method to be able 2753 * to return a meaningful (non-null) value. 2754 * 2755 * @param i the index into the String ≥ 0 2756 * @return the screen coordinates of the character's bounding box 2757 */ 2758 public Rectangle getCharacterBounds(int i) { 2759 if (i < 0 || i > model.getLength()-1) { 2760 return null; 2761 } 2762 TextUI ui = getUI(); 2763 if (ui == null) { 2764 return null; 2765 } 2766 Rectangle rect = null; 2767 Rectangle alloc = getRootEditorRect(); 2768 if (alloc == null) { 2769 return null; 2770 } 2771 if (model instanceof AbstractDocument) { 2772 ((AbstractDocument)model).readLock(); 2773 } 2774 try { 2775 View rootView = ui.getRootView(JTextComponent.this); 2776 if (rootView != null) { 2777 rootView.setSize(alloc.width, alloc.height); 2778 2779 Shape bounds = rootView.modelToView(i, 2780 Position.Bias.Forward, i+1, 2781 Position.Bias.Backward, alloc); 2782 2783 rect = (bounds instanceof Rectangle) ? 2784 (Rectangle)bounds : bounds.getBounds(); 2785 2786 } 2787 } catch (BadLocationException e) { 2788 } finally { 2789 if (model instanceof AbstractDocument) { 2790 ((AbstractDocument)model).readUnlock(); 2791 } 2792 } 2793 return rect; 2794 } 2795 2796 /** 2797 * Returns the number of characters (valid indices) 2798 * 2799 * @return the number of characters ≥ 0 2800 */ 2801 public int getCharCount() { 2802 return model.getLength(); 2803 } 2804 2805 /** 2806 * Returns the zero-based offset of the caret. 2807 * 2808 * Note: The character to the right of the caret will have the 2809 * same index value as the offset (the caret is between 2810 * two characters). 2811 * 2812 * @return the zero-based offset of the caret. 2813 */ 2814 public int getCaretPosition() { 2815 return JTextComponent.this.getCaretPosition(); 2816 } 2817 2818 /** 2819 * Returns the AttributeSet for a given character (at a given index). 2820 * 2821 * @param i the zero-based index into the text 2822 * @return the AttributeSet of the character 2823 */ 2824 public AttributeSet getCharacterAttribute(int i) { 2825 Element e = null; 2826 if (model instanceof AbstractDocument) { 2827 ((AbstractDocument)model).readLock(); 2828 } 2829 try { 2830 for (e = model.getDefaultRootElement(); ! e.isLeaf(); ) { 2831 int index = e.getElementIndex(i); 2832 e = e.getElement(index); 2833 } 2834 } finally { 2835 if (model instanceof AbstractDocument) { 2836 ((AbstractDocument)model).readUnlock(); 2837 } 2838 } 2839 return e.getAttributes(); 2840 } 2841 2842 2843 /** 2844 * Returns the start offset within the selected text. 2845 * If there is no selection, but there is 2846 * a caret, the start and end offsets will be the same. 2847 * Return 0 if the text is empty, or the caret position 2848 * if no selection. 2849 * 2850 * @return the index into the text of the start of the selection ≥ 0 2851 */ 2852 public int getSelectionStart() { 2853 return JTextComponent.this.getSelectionStart(); 2854 } 2855 2856 /** 2857 * Returns the end offset within the selected text. 2858 * If there is no selection, but there is 2859 * a caret, the start and end offsets will be the same. 2860 * Return 0 if the text is empty, or the caret position 2861 * if no selection. 2862 * 2863 * @return the index into the text of the end of the selection ≥ 0 2864 */ 2865 public int getSelectionEnd() { 2866 return JTextComponent.this.getSelectionEnd(); 2867 } 2868 2869 /** 2870 * Returns the portion of the text that is selected. 2871 * 2872 * @return the text, null if no selection 2873 */ 2874 public String getSelectedText() { 2875 return JTextComponent.this.getSelectedText(); 2876 } 2877 2878 /** 2879 * IndexedSegment extends Segment adding the offset into the 2880 * the model the <code>Segment</code> was asked for. 2881 */ 2882 private class IndexedSegment extends Segment { 2883 /** 2884 * Offset into the model that the position represents. 2885 */ 2886 public int modelOffset; 2887 } 2888 2889 2890 // TIGER - 4170173 2891 /** 2892 * Returns the String at a given index. Whitespace 2893 * between words is treated as a word. 2894 * 2895 * @param part the CHARACTER, WORD, or SENTENCE to retrieve 2896 * @param index an index within the text 2897 * @return the letter, word, or sentence. 2898 * 2899 */ 2900 public String getAtIndex(int part, int index) { 2901 return getAtIndex(part, index, 0); 2902 } 2903 2904 2905 /** 2906 * Returns the String after a given index. Whitespace 2907 * between words is treated as a word. 2908 * 2909 * @param part the CHARACTER, WORD, or SENTENCE to retrieve 2910 * @param index an index within the text 2911 * @return the letter, word, or sentence. 2912 */ 2913 public String getAfterIndex(int part, int index) { 2914 return getAtIndex(part, index, 1); 2915 } 2916 2917 2918 /** 2919 * Returns the String before a given index. Whitespace 2920 * between words is treated a word. 2921 * 2922 * @param part the CHARACTER, WORD, or SENTENCE to retrieve 2923 * @param index an index within the text 2924 * @return the letter, word, or sentence. 2925 */ 2926 public String getBeforeIndex(int part, int index) { 2927 return getAtIndex(part, index, -1); 2928 } 2929 2930 2931 /** 2932 * Gets the word, sentence, or character at <code>index</code>. 2933 * If <code>direction</code> is non-null this will find the 2934 * next/previous word/sentence/character. 2935 */ 2936 private String getAtIndex(int part, int index, int direction) { 2937 if (model instanceof AbstractDocument) { 2938 ((AbstractDocument)model).readLock(); 2939 } 2940 try { 2941 if (index < 0 || index >= model.getLength()) { 2942 return null; 2943 } 2944 switch (part) { 2945 case AccessibleText.CHARACTER: 2946 if (index + direction < model.getLength() && 2947 index + direction >= 0) { 2948 return model.getText(index + direction, 1); 2949 } 2950 break; 2951 2952 2953 case AccessibleText.WORD: 2954 case AccessibleText.SENTENCE: 2955 IndexedSegment seg = getSegmentAt(part, index); 2956 if (seg != null) { 2957 if (direction != 0) { 2958 int next; 2959 2960 2961 if (direction < 0) { 2962 next = seg.modelOffset - 1; 2963 } 2964 else { 2965 next = seg.modelOffset + direction * seg.count; 2966 } 2967 if (next >= 0 && next <= model.getLength()) { 2968 seg = getSegmentAt(part, next); 2969 } 2970 else { 2971 seg = null; 2972 } 2973 } 2974 if (seg != null) { 2975 return new String(seg.array, seg.offset, 2976 seg.count); 2977 } 2978 } 2979 break; 2980 2981 2982 default: 2983 break; 2984 } 2985 } catch (BadLocationException e) { 2986 } finally { 2987 if (model instanceof AbstractDocument) { 2988 ((AbstractDocument)model).readUnlock(); 2989 } 2990 } 2991 return null; 2992 } 2993 2994 2995 /* 2996 * Returns the paragraph element for the specified index. 2997 */ 2998 private Element getParagraphElement(int index) { 2999 if (model instanceof PlainDocument ) { 3000 PlainDocument sdoc = (PlainDocument)model; 3001 return sdoc.getParagraphElement(index); 3002 } else if (model instanceof StyledDocument) { 3003 StyledDocument sdoc = (StyledDocument)model; 3004 return sdoc.getParagraphElement(index); 3005 } else { 3006 Element para; 3007 for (para = model.getDefaultRootElement(); ! para.isLeaf(); ) { 3008 int pos = para.getElementIndex(index); 3009 para = para.getElement(pos); 3010 } 3011 if (para == null) { 3012 return null; 3013 } 3014 return para.getParentElement(); 3015 } 3016 } 3017 3018 /* 3019 * Returns a <code>Segment</code> containing the paragraph text 3020 * at <code>index</code>, or null if <code>index</code> isn't 3021 * valid. 3022 */ 3023 private IndexedSegment getParagraphElementText(int index) 3024 throws BadLocationException { 3025 Element para = getParagraphElement(index); 3026 3027 3028 if (para != null) { 3029 IndexedSegment segment = new IndexedSegment(); 3030 try { 3031 int length = para.getEndOffset() - para.getStartOffset(); 3032 model.getText(para.getStartOffset(), length, segment); 3033 } catch (BadLocationException e) { 3034 return null; 3035 } 3036 segment.modelOffset = para.getStartOffset(); 3037 return segment; 3038 } 3039 return null; 3040 } 3041 3042 3043 /** 3044 * Returns the Segment at <code>index</code> representing either 3045 * the paragraph or sentence as identified by <code>part</code>, or 3046 * null if a valid paragraph/sentence can't be found. The offset 3047 * will point to the start of the word/sentence in the array, and 3048 * the modelOffset will point to the location of the word/sentence 3049 * in the model. 3050 */ 3051 private IndexedSegment getSegmentAt(int part, int index) throws 3052 BadLocationException { 3053 IndexedSegment seg = getParagraphElementText(index); 3054 if (seg == null) { 3055 return null; 3056 } 3057 BreakIterator iterator; 3058 switch (part) { 3059 case AccessibleText.WORD: 3060 iterator = BreakIterator.getWordInstance(getLocale()); 3061 break; 3062 case AccessibleText.SENTENCE: 3063 iterator = BreakIterator.getSentenceInstance(getLocale()); 3064 break; 3065 default: 3066 return null; 3067 } 3068 seg.first(); 3069 iterator.setText(seg); 3070 int end = iterator.following(index - seg.modelOffset + seg.offset); 3071 if (end == BreakIterator.DONE) { 3072 return null; 3073 } 3074 if (end > seg.offset + seg.count) { 3075 return null; 3076 } 3077 int begin = iterator.previous(); 3078 if (begin == BreakIterator.DONE || 3079 begin >= seg.offset + seg.count) { 3080 return null; 3081 } 3082 seg.modelOffset = seg.modelOffset + begin - seg.offset; 3083 seg.offset = begin; 3084 seg.count = end - begin; 3085 return seg; 3086 } 3087 3088 // begin AccessibleEditableText methods ----- 3089 3090 /** 3091 * Returns the AccessibleEditableText interface for 3092 * this text component. 3093 * 3094 * @return the AccessibleEditableText interface 3095 * @since 1.4 3096 */ 3097 public AccessibleEditableText getAccessibleEditableText() { 3098 return this; 3099 } 3100 3101 /** 3102 * Sets the text contents to the specified string. 3103 * 3104 * @param s the string to set the text contents 3105 * @since 1.4 3106 */ 3107 public void setTextContents(String s) { 3108 JTextComponent.this.setText(s); 3109 } 3110 3111 /** 3112 * Inserts the specified string at the given index 3113 * 3114 * @param index the index in the text where the string will 3115 * be inserted 3116 * @param s the string to insert in the text 3117 * @since 1.4 3118 */ 3119 public void insertTextAtIndex(int index, String s) { 3120 Document doc = JTextComponent.this.getDocument(); 3121 if (doc != null) { 3122 try { 3123 if (s != null && s.length() > 0) { 3124 boolean composedTextSaved = saveComposedText(index); 3125 doc.insertString(index, s, null); 3126 if (composedTextSaved) { 3127 restoreComposedText(); 3128 } 3129 } 3130 } catch (BadLocationException e) { 3131 UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this); 3132 } 3133 } 3134 } 3135 3136 /** 3137 * Returns the text string between two indices. 3138 * 3139 * @param startIndex the starting index in the text 3140 * @param endIndex the ending index in the text 3141 * @return the text string between the indices 3142 * @since 1.4 3143 */ 3144 public String getTextRange(int startIndex, int endIndex) { 3145 String txt = null; 3146 int p0 = Math.min(startIndex, endIndex); 3147 int p1 = Math.max(startIndex, endIndex); 3148 if (p0 != p1) { 3149 try { 3150 Document doc = JTextComponent.this.getDocument(); 3151 txt = doc.getText(p0, p1 - p0); 3152 } catch (BadLocationException e) { 3153 throw new IllegalArgumentException(e.getMessage()); 3154 } 3155 } 3156 return txt; 3157 } 3158 3159 /** 3160 * Deletes the text between two indices 3161 * 3162 * @param startIndex the starting index in the text 3163 * @param endIndex the ending index in the text 3164 * @since 1.4 3165 */ 3166 public void delete(int startIndex, int endIndex) { 3167 if (isEditable() && isEnabled()) { 3168 try { 3169 int p0 = Math.min(startIndex, endIndex); 3170 int p1 = Math.max(startIndex, endIndex); 3171 if (p0 != p1) { 3172 Document doc = getDocument(); 3173 doc.remove(p0, p1 - p0); 3174 } 3175 } catch (BadLocationException e) { 3176 } 3177 } else { 3178 UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this); 3179 } 3180 } 3181 3182 /** 3183 * Cuts the text between two indices into the system clipboard. 3184 * 3185 * @param startIndex the starting index in the text 3186 * @param endIndex the ending index in the text 3187 * @since 1.4 3188 */ 3189 public void cut(int startIndex, int endIndex) { 3190 selectText(startIndex, endIndex); 3191 JTextComponent.this.cut(); 3192 } 3193 3194 /** 3195 * Pastes the text from the system clipboard into the text 3196 * starting at the specified index. 3197 * 3198 * @param startIndex the starting index in the text 3199 * @since 1.4 3200 */ 3201 public void paste(int startIndex) { 3202 setCaretPosition(startIndex); 3203 JTextComponent.this.paste(); 3204 } 3205 3206 /** 3207 * Replaces the text between two indices with the specified 3208 * string. 3209 * 3210 * @param startIndex the starting index in the text 3211 * @param endIndex the ending index in the text 3212 * @param s the string to replace the text between two indices 3213 * @since 1.4 3214 */ 3215 public void replaceText(int startIndex, int endIndex, String s) { 3216 selectText(startIndex, endIndex); 3217 JTextComponent.this.replaceSelection(s); 3218 } 3219 3220 /** 3221 * Selects the text between two indices. 3222 * 3223 * @param startIndex the starting index in the text 3224 * @param endIndex the ending index in the text 3225 * @since 1.4 3226 */ 3227 public void selectText(int startIndex, int endIndex) { 3228 JTextComponent.this.select(startIndex, endIndex); 3229 } 3230 3231 /** 3232 * Sets attributes for the text between two indices. 3233 * 3234 * @param startIndex the starting index in the text 3235 * @param endIndex the ending index in the text 3236 * @param as the attribute set 3237 * @see AttributeSet 3238 * @since 1.4 3239 */ 3240 public void setAttributes(int startIndex, int endIndex, 3241 AttributeSet as) { 3242 3243 // Fixes bug 4487492 3244 Document doc = JTextComponent.this.getDocument(); 3245 if (doc != null && doc instanceof StyledDocument) { 3246 StyledDocument sDoc = (StyledDocument)doc; 3247 int offset = startIndex; 3248 int length = endIndex - startIndex; 3249 sDoc.setCharacterAttributes(offset, length, as, true); 3250 } 3251 } 3252 3253 // ----- end AccessibleEditableText methods 3254 3255 3256 // ----- begin AccessibleExtendedText methods 3257 3258 // Probably should replace the helper method getAtIndex() to return 3259 // instead an AccessibleTextSequence also for LINE & ATTRIBUTE_RUN 3260 // and then make the AccessibleText methods get[At|After|Before]Point 3261 // call this new method instead and return only the string portion 3262 3263 /** 3264 * Returns the AccessibleTextSequence at a given <code>index</code>. 3265 * If <code>direction</code> is non-null this will find the 3266 * next/previous word/sentence/character. 3267 * 3268 * @param part the <code>CHARACTER</code>, <code>WORD</code>, 3269 * <code>SENTENCE</code>, <code>LINE</code> or 3270 * <code>ATTRIBUTE_RUN</code> to retrieve 3271 * @param index an index within the text 3272 * @param direction is either -1, 0, or 1 3273 * @return an <code>AccessibleTextSequence</code> specifying the text 3274 * if <code>part</code> and <code>index</code> are valid. Otherwise, 3275 * <code>null</code> is returned. 3276 * 3277 * @see javax.accessibility.AccessibleText#CHARACTER 3278 * @see javax.accessibility.AccessibleText#WORD 3279 * @see javax.accessibility.AccessibleText#SENTENCE 3280 * @see javax.accessibility.AccessibleExtendedText#LINE 3281 * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN 3282 * 3283 * @since 1.6 3284 */ 3285 private AccessibleTextSequence getSequenceAtIndex(int part, 3286 int index, int direction) { 3287 if (index < 0 || index >= model.getLength()) { 3288 return null; 3289 } 3290 if (direction < -1 || direction > 1) { 3291 return null; // direction must be 1, 0, or -1 3292 } 3293 3294 switch (part) { 3295 case AccessibleText.CHARACTER: 3296 if (model instanceof AbstractDocument) { 3297 ((AbstractDocument)model).readLock(); 3298 } 3299 AccessibleTextSequence charSequence = null; 3300 try { 3301 if (index + direction < model.getLength() && 3302 index + direction >= 0) { 3303 charSequence = 3304 new AccessibleTextSequence(index + direction, 3305 index + direction + 1, 3306 model.getText(index + direction, 1)); 3307 } 3308 3309 } catch (BadLocationException e) { 3310 // we are intentionally silent; our contract says we return 3311 // null if there is any failure in this method 3312 } finally { 3313 if (model instanceof AbstractDocument) { 3314 ((AbstractDocument)model).readUnlock(); 3315 } 3316 } 3317 return charSequence; 3318 3319 case AccessibleText.WORD: 3320 case AccessibleText.SENTENCE: 3321 if (model instanceof AbstractDocument) { 3322 ((AbstractDocument)model).readLock(); 3323 } 3324 AccessibleTextSequence rangeSequence = null; 3325 try { 3326 IndexedSegment seg = getSegmentAt(part, index); 3327 if (seg != null) { 3328 if (direction != 0) { 3329 int next; 3330 3331 if (direction < 0) { 3332 next = seg.modelOffset - 1; 3333 } 3334 else { 3335 next = seg.modelOffset + seg.count; 3336 } 3337 if (next >= 0 && next <= model.getLength()) { 3338 seg = getSegmentAt(part, next); 3339 } 3340 else { 3341 seg = null; 3342 } 3343 } 3344 if (seg != null && 3345 (seg.offset + seg.count) <= model.getLength()) { 3346 rangeSequence = 3347 new AccessibleTextSequence (seg.offset, 3348 seg.offset + seg.count, 3349 new String(seg.array, seg.offset, seg.count)); 3350 } // else we leave rangeSequence set to null 3351 } 3352 } catch(BadLocationException e) { 3353 // we are intentionally silent; our contract says we return 3354 // null if there is any failure in this method 3355 } finally { 3356 if (model instanceof AbstractDocument) { 3357 ((AbstractDocument)model).readUnlock(); 3358 } 3359 } 3360 return rangeSequence; 3361 3362 case AccessibleExtendedText.LINE: 3363 AccessibleTextSequence lineSequence = null; 3364 if (model instanceof AbstractDocument) { 3365 ((AbstractDocument)model).readLock(); 3366 } 3367 try { 3368 int startIndex = 3369 Utilities.getRowStart(JTextComponent.this, index); 3370 int endIndex = 3371 Utilities.getRowEnd(JTextComponent.this, index); 3372 if (startIndex >= 0 && endIndex >= startIndex) { 3373 if (direction == 0) { 3374 lineSequence = 3375 new AccessibleTextSequence(startIndex, endIndex, 3376 model.getText(startIndex, 3377 endIndex - startIndex + 1)); 3378 } else if (direction == -1 && startIndex > 0) { 3379 endIndex = 3380 Utilities.getRowEnd(JTextComponent.this, 3381 startIndex - 1); 3382 startIndex = 3383 Utilities.getRowStart(JTextComponent.this, 3384 startIndex - 1); 3385 if (startIndex >= 0 && endIndex >= startIndex) { 3386 lineSequence = 3387 new AccessibleTextSequence(startIndex, 3388 endIndex, 3389 model.getText(startIndex, 3390 endIndex - startIndex + 1)); 3391 } 3392 } else if (direction == 1 && 3393 endIndex < model.getLength()) { 3394 startIndex = 3395 Utilities.getRowStart(JTextComponent.this, 3396 endIndex + 1); 3397 endIndex = 3398 Utilities.getRowEnd(JTextComponent.this, 3399 endIndex + 1); 3400 if (startIndex >= 0 && endIndex >= startIndex) { 3401 lineSequence = 3402 new AccessibleTextSequence(startIndex, 3403 endIndex, model.getText(startIndex, 3404 endIndex - startIndex + 1)); 3405 } 3406 } 3407 // already validated 'direction' above... 3408 } 3409 } catch(BadLocationException e) { 3410 // we are intentionally silent; our contract says we return 3411 // null if there is any failure in this method 3412 } finally { 3413 if (model instanceof AbstractDocument) { 3414 ((AbstractDocument)model).readUnlock(); 3415 } 3416 } 3417 return lineSequence; 3418 3419 case AccessibleExtendedText.ATTRIBUTE_RUN: 3420 // assumptions: (1) that all characters in a single element 3421 // share the same attribute set; (2) that adjacent elements 3422 // *may* share the same attribute set 3423 3424 int attributeRunStartIndex, attributeRunEndIndex; 3425 String runText = null; 3426 if (model instanceof AbstractDocument) { 3427 ((AbstractDocument)model).readLock(); 3428 } 3429 3430 try { 3431 attributeRunStartIndex = attributeRunEndIndex = 3432 Integer.MIN_VALUE; 3433 int tempIndex = index; 3434 switch (direction) { 3435 case -1: 3436 // going backwards, so find left edge of this run - 3437 // that'll be the end of the previous run 3438 // (off-by-one counting) 3439 attributeRunEndIndex = getRunEdge(index, direction); 3440 // now set ourselves up to find the left edge of the 3441 // prev. run 3442 tempIndex = attributeRunEndIndex - 1; 3443 break; 3444 case 1: 3445 // going forward, so find right edge of this run - 3446 // that'll be the start of the next run 3447 // (off-by-one counting) 3448 attributeRunStartIndex = getRunEdge(index, direction); 3449 // now set ourselves up to find the right edge of the 3450 // next run 3451 tempIndex = attributeRunStartIndex; 3452 break; 3453 case 0: 3454 // interested in the current run, so nothing special to 3455 // set up in advance... 3456 break; 3457 default: 3458 // only those three values of direction allowed... 3459 throw new AssertionError(direction); 3460 } 3461 3462 // set the unset edge; if neither set then we're getting 3463 // both edges of the current run around our 'index' 3464 attributeRunStartIndex = 3465 (attributeRunStartIndex != Integer.MIN_VALUE) ? 3466 attributeRunStartIndex : getRunEdge(tempIndex, -1); 3467 attributeRunEndIndex = 3468 (attributeRunEndIndex != Integer.MIN_VALUE) ? 3469 attributeRunEndIndex : getRunEdge(tempIndex, 1); 3470 3471 runText = model.getText(attributeRunStartIndex, 3472 attributeRunEndIndex - 3473 attributeRunStartIndex); 3474 } catch (BadLocationException e) { 3475 // we are intentionally silent; our contract says we return 3476 // null if there is any failure in this method 3477 return null; 3478 } finally { 3479 if (model instanceof AbstractDocument) { 3480 ((AbstractDocument)model).readUnlock(); 3481 } 3482 } 3483 return new AccessibleTextSequence(attributeRunStartIndex, 3484 attributeRunEndIndex, 3485 runText); 3486 3487 default: 3488 break; 3489 } 3490 return null; 3491 } 3492 3493 3494 /** 3495 * Starting at text position <code>index</code>, and going in 3496 * <code>direction</code>, return the edge of run that shares the 3497 * same <code>AttributeSet</code> and parent element as those at 3498 * <code>index</code>. 3499 * 3500 * Note: we assume the document is already locked... 3501 */ 3502 private int getRunEdge(int index, int direction) throws 3503 BadLocationException { 3504 if (index < 0 || index >= model.getLength()) { 3505 throw new BadLocationException("Location out of bounds", index); 3506 } 3507 // locate the Element at index 3508 Element indexElement; 3509 // locate the Element at our index/offset 3510 int elementIndex = -1; // test for initialization 3511 for (indexElement = model.getDefaultRootElement(); 3512 ! indexElement.isLeaf(); ) { 3513 elementIndex = indexElement.getElementIndex(index); 3514 indexElement = indexElement.getElement(elementIndex); 3515 } 3516 if (elementIndex == -1) { 3517 throw new AssertionError(index); 3518 } 3519 // cache the AttributeSet and parentElement atindex 3520 AttributeSet indexAS = indexElement.getAttributes(); 3521 Element parent = indexElement.getParentElement(); 3522 3523 // find the first Element before/after ours w/the same AttributeSet 3524 // if we are already at edge of the first element in our parent 3525 // then return that edge 3526 Element edgeElement; 3527 switch (direction) { 3528 case -1: 3529 case 1: 3530 int edgeElementIndex = elementIndex; 3531 int elementCount = parent.getElementCount(); 3532 while ((edgeElementIndex + direction) > 0 && 3533 ((edgeElementIndex + direction) < elementCount) && 3534 parent.getElement(edgeElementIndex 3535 + direction).getAttributes().isEqual(indexAS)) { 3536 edgeElementIndex += direction; 3537 } 3538 edgeElement = parent.getElement(edgeElementIndex); 3539 break; 3540 default: 3541 throw new AssertionError(direction); 3542 } 3543 switch (direction) { 3544 case -1: 3545 return edgeElement.getStartOffset(); 3546 case 1: 3547 return edgeElement.getEndOffset(); 3548 default: 3549 // we already caught this case earlier; this is to satisfy 3550 // the compiler... 3551 return Integer.MIN_VALUE; 3552 } 3553 } 3554 3555 // getTextRange() not needed; defined in AccessibleEditableText 3556 3557 /** 3558 * Returns the <code>AccessibleTextSequence</code> at a given 3559 * <code>index</code>. 3560 * 3561 * @param part the <code>CHARACTER</code>, <code>WORD</code>, 3562 * <code>SENTENCE</code>, <code>LINE</code> or 3563 * <code>ATTRIBUTE_RUN</code> to retrieve 3564 * @param index an index within the text 3565 * @return an <code>AccessibleTextSequence</code> specifying the text if 3566 * <code>part</code> and <code>index</code> are valid. Otherwise, 3567 * <code>null</code> is returned 3568 * 3569 * @see javax.accessibility.AccessibleText#CHARACTER 3570 * @see javax.accessibility.AccessibleText#WORD 3571 * @see javax.accessibility.AccessibleText#SENTENCE 3572 * @see javax.accessibility.AccessibleExtendedText#LINE 3573 * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN 3574 * 3575 * @since 1.6 3576 */ 3577 public AccessibleTextSequence getTextSequenceAt(int part, int index) { 3578 return getSequenceAtIndex(part, index, 0); 3579 } 3580 3581 /** 3582 * Returns the <code>AccessibleTextSequence</code> after a given 3583 * <code>index</code>. 3584 * 3585 * @param part the <code>CHARACTER</code>, <code>WORD</code>, 3586 * <code>SENTENCE</code>, <code>LINE</code> or 3587 * <code>ATTRIBUTE_RUN</code> to retrieve 3588 * @param index an index within the text 3589 * @return an <code>AccessibleTextSequence</code> specifying the text 3590 * if <code>part</code> and <code>index</code> are valid. Otherwise, 3591 * <code>null</code> is returned 3592 * 3593 * @see javax.accessibility.AccessibleText#CHARACTER 3594 * @see javax.accessibility.AccessibleText#WORD 3595 * @see javax.accessibility.AccessibleText#SENTENCE 3596 * @see javax.accessibility.AccessibleExtendedText#LINE 3597 * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN 3598 * 3599 * @since 1.6 3600 */ 3601 public AccessibleTextSequence getTextSequenceAfter(int part, int index) { 3602 return getSequenceAtIndex(part, index, 1); 3603 } 3604 3605 /** 3606 * Returns the <code>AccessibleTextSequence</code> before a given 3607 * <code>index</code>. 3608 * 3609 * @param part the <code>CHARACTER</code>, <code>WORD</code>, 3610 * <code>SENTENCE</code>, <code>LINE</code> or 3611 * <code>ATTRIBUTE_RUN</code> to retrieve 3612 * @param index an index within the text 3613 * @return an <code>AccessibleTextSequence</code> specifying the text 3614 * if <code>part</code> and <code>index</code> are valid. Otherwise, 3615 * <code>null</code> is returned 3616 * 3617 * @see javax.accessibility.AccessibleText#CHARACTER 3618 * @see javax.accessibility.AccessibleText#WORD 3619 * @see javax.accessibility.AccessibleText#SENTENCE 3620 * @see javax.accessibility.AccessibleExtendedText#LINE 3621 * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN 3622 * 3623 * @since 1.6 3624 */ 3625 public AccessibleTextSequence getTextSequenceBefore(int part, int index) { 3626 return getSequenceAtIndex(part, index, -1); 3627 } 3628 3629 /** 3630 * Returns the <code>Rectangle</code> enclosing the text between 3631 * two indicies. 3632 * 3633 * @param startIndex the start index in the text 3634 * @param endIndex the end index in the text 3635 * @return the bounding rectangle of the text if the indices are valid. 3636 * Otherwise, <code>null</code> is returned 3637 * 3638 * @since 1.6 3639 */ 3640 public Rectangle getTextBounds(int startIndex, int endIndex) { 3641 if (startIndex < 0 || startIndex > model.getLength()-1 || 3642 endIndex < 0 || endIndex > model.getLength()-1 || 3643 startIndex > endIndex) { 3644 return null; 3645 } 3646 TextUI ui = getUI(); 3647 if (ui == null) { 3648 return null; 3649 } 3650 Rectangle rect = null; 3651 Rectangle alloc = getRootEditorRect(); 3652 if (alloc == null) { 3653 return null; 3654 } 3655 if (model instanceof AbstractDocument) { 3656 ((AbstractDocument)model).readLock(); 3657 } 3658 try { 3659 View rootView = ui.getRootView(JTextComponent.this); 3660 if (rootView != null) { 3661 Shape bounds = rootView.modelToView(startIndex, 3662 Position.Bias.Forward, endIndex, 3663 Position.Bias.Backward, alloc); 3664 3665 rect = (bounds instanceof Rectangle) ? 3666 (Rectangle)bounds : bounds.getBounds(); 3667 3668 } 3669 } catch (BadLocationException e) { 3670 } finally { 3671 if (model instanceof AbstractDocument) { 3672 ((AbstractDocument)model).readUnlock(); 3673 } 3674 } 3675 return rect; 3676 } 3677 3678 // ----- end AccessibleExtendedText methods 3679 3680 3681 // --- interface AccessibleAction methods ------------------------ 3682 3683 public AccessibleAction getAccessibleAction() { 3684 return this; 3685 } 3686 3687 /** 3688 * Returns the number of accessible actions available in this object 3689 * If there are more than one, the first one is considered the 3690 * "default" action of the object. 3691 * 3692 * @return the zero-based number of Actions in this object 3693 * @since 1.4 3694 */ 3695 public int getAccessibleActionCount() { 3696 Action [] actions = JTextComponent.this.getActions(); 3697 return actions.length; 3698 } 3699 3700 /** 3701 * Returns a description of the specified action of the object. 3702 * 3703 * @param i zero-based index of the actions 3704 * @return a String description of the action 3705 * @see #getAccessibleActionCount 3706 * @since 1.4 3707 */ 3708 public String getAccessibleActionDescription(int i) { 3709 Action [] actions = JTextComponent.this.getActions(); 3710 if (i < 0 || i >= actions.length) { 3711 return null; 3712 } 3713 return (String)actions[i].getValue(Action.NAME); 3714 } 3715 3716 /** 3717 * Performs the specified Action on the object 3718 * 3719 * @param i zero-based index of actions 3720 * @return true if the action was performed; otherwise false. 3721 * @see #getAccessibleActionCount 3722 * @since 1.4 3723 */ 3724 public boolean doAccessibleAction(int i) { 3725 Action [] actions = JTextComponent.this.getActions(); 3726 if (i < 0 || i >= actions.length) { 3727 return false; 3728 } 3729 ActionEvent ae = 3730 new ActionEvent(JTextComponent.this, 3731 ActionEvent.ACTION_PERFORMED, null, 3732 EventQueue.getMostRecentEventTime(), 3733 getCurrentEventModifiers()); 3734 actions[i].actionPerformed(ae); 3735 return true; 3736 } 3737 3738 // ----- end AccessibleAction methods 3739 3740 3741 } 3742 3743 3744 // --- serialization --------------------------------------------- 3745 3746 private void readObject(ObjectInputStream s) 3747 throws IOException, ClassNotFoundException 3748 { 3749 s.defaultReadObject(); 3750 caretEvent = new MutableCaretEvent(this); 3751 addMouseListener(caretEvent); 3752 addFocusListener(caretEvent); 3753 } 3754 3755 // --- member variables ---------------------------------- 3756 3757 /** 3758 * The document model. 3759 */ 3760 private Document model; 3761 3762 /** 3763 * The caret used to display the insert position 3764 * and navigate throughout the document. 3765 * 3766 * PENDING(prinz) 3767 * This should be serializable, default installed 3768 * by UI. 3769 */ 3770 private transient Caret caret; 3771 3772 /** 3773 * Object responsible for restricting the cursor navigation. 3774 */ 3775 private NavigationFilter navigationFilter; 3776 3777 /** 3778 * The object responsible for managing highlights. 3779 * 3780 * PENDING(prinz) 3781 * This should be serializable, default installed 3782 * by UI. 3783 */ 3784 private transient Highlighter highlighter; 3785 3786 /** 3787 * The current key bindings in effect. 3788 * 3789 * PENDING(prinz) 3790 * This should be serializable, default installed 3791 * by UI. 3792 */ 3793 private transient Keymap keymap; 3794 3795 private transient MutableCaretEvent caretEvent; 3796 private Color caretColor; 3797 private Color selectionColor; 3798 private Color selectedTextColor; 3799 private Color disabledTextColor; 3800 private boolean editable; 3801 private Insets margin; 3802 private char focusAccelerator; 3803 private boolean dragEnabled; 3804 3805 /** 3806 * The drop mode for this component. 3807 */ 3808 private DropMode dropMode = DropMode.USE_SELECTION; 3809 3810 /** 3811 * The drop location. 3812 */ 3813 private transient DropLocation dropLocation; 3814 3815 /** 3816 * Represents a drop location for <code>JTextComponent</code>s. 3817 * 3818 * @see #getDropLocation 3819 * @since 1.6 3820 */ 3821 public static final class DropLocation extends TransferHandler.DropLocation { 3822 private final int index; 3823 private final Position.Bias bias; 3824 3825 private DropLocation(Point p, int index, Position.Bias bias) { 3826 super(p); 3827 this.index = index; 3828 this.bias = bias; 3829 } 3830 3831 /** 3832 * Returns the index where dropped data should be inserted into the 3833 * associated component. This index represents a position between 3834 * characters, as would be interpreted by a caret. 3835 * 3836 * @return the drop index 3837 */ 3838 public int getIndex() { 3839 return index; 3840 } 3841 3842 /** 3843 * Returns the bias for the drop index. 3844 * 3845 * @return the drop bias 3846 */ 3847 public Position.Bias getBias() { 3848 return bias; 3849 } 3850 3851 /** 3852 * Returns a string representation of this drop location. 3853 * This method is intended to be used for debugging purposes, 3854 * and the content and format of the returned string may vary 3855 * between implementations. 3856 * 3857 * @return a string representation of this drop location 3858 */ 3859 public String toString() { 3860 return getClass().getName() 3861 + "[dropPoint=" + getDropPoint() + "," 3862 + "index=" + index + "," 3863 + "bias=" + bias + "]"; 3864 } 3865 } 3866 3867 /** 3868 * TransferHandler used if one hasn't been supplied by the UI. 3869 */ 3870 private static DefaultTransferHandler defaultTransferHandler; 3871 3872 /** 3873 * Maps from class name to Boolean indicating if 3874 * <code>processInputMethodEvent</code> has been overriden. 3875 */ 3876 private static Cache<Class<?>,Boolean> METHOD_OVERRIDDEN 3877 = new Cache<Class<?>,Boolean>(Cache.Kind.WEAK, Cache.Kind.STRONG) { 3878 /** 3879 * Returns {@code true} if the specified {@code type} extends {@link JTextComponent} 3880 * and the {@link JTextComponent#processInputMethodEvent} method is overridden. 3881 */ 3882 @Override 3883 public Boolean create(final Class<?> type) { 3884 if (JTextComponent.class == type) { 3885 return Boolean.FALSE; 3886 } 3887 if (get(type.getSuperclass())) { 3888 return Boolean.TRUE; 3889 } 3890 return AccessController.doPrivileged( 3891 new PrivilegedAction<Boolean>() { 3892 public Boolean run() { 3893 try { 3894 type.getDeclaredMethod("processInputMethodEvent", InputMethodEvent.class); 3895 return Boolean.TRUE; 3896 } catch (NoSuchMethodException exception) { 3897 return Boolean.FALSE; 3898 } 3899 } 3900 }); 3901 } 3902 }; 3903 3904 /** 3905 * Returns a string representation of this <code>JTextComponent</code>. 3906 * This method is intended to be used only for debugging purposes, and the 3907 * content and format of the returned string may vary between 3908 * implementations. The returned string may be empty but may not 3909 * be <code>null</code>. 3910 * <P> 3911 * Overriding <code>paramString</code> to provide information about the 3912 * specific new aspects of the JFC components. 3913 * 3914 * @return a string representation of this <code>JTextComponent</code> 3915 */ 3916 protected String paramString() { 3917 String editableString = (editable ? 3918 "true" : "false"); 3919 String caretColorString = (caretColor != null ? 3920 caretColor.toString() : ""); 3921 String selectionColorString = (selectionColor != null ? 3922 selectionColor.toString() : ""); 3923 String selectedTextColorString = (selectedTextColor != null ? 3924 selectedTextColor.toString() : ""); 3925 String disabledTextColorString = (disabledTextColor != null ? 3926 disabledTextColor.toString() : ""); 3927 String marginString = (margin != null ? 3928 margin.toString() : ""); 3929 3930 return super.paramString() + 3931 ",caretColor=" + caretColorString + 3932 ",disabledTextColor=" + disabledTextColorString + 3933 ",editable=" + editableString + 3934 ",margin=" + marginString + 3935 ",selectedTextColor=" + selectedTextColorString + 3936 ",selectionColor=" + selectionColorString; 3937 } 3938 3939 3940 /** 3941 * A Simple TransferHandler that exports the data as a String, and 3942 * imports the data from the String clipboard. This is only used 3943 * if the UI hasn't supplied one, which would only happen if someone 3944 * hasn't subclassed Basic. 3945 */ 3946 static class DefaultTransferHandler extends TransferHandler implements 3947 UIResource { 3948 public void exportToClipboard(JComponent comp, Clipboard clipboard, 3949 int action) throws IllegalStateException { 3950 if (comp instanceof JTextComponent) { 3951 JTextComponent text = (JTextComponent)comp; 3952 int p0 = text.getSelectionStart(); 3953 int p1 = text.getSelectionEnd(); 3954 if (p0 != p1) { 3955 try { 3956 Document doc = text.getDocument(); 3957 String srcData = doc.getText(p0, p1 - p0); 3958 StringSelection contents =new StringSelection(srcData); 3959 3960 // this may throw an IllegalStateException, 3961 // but it will be caught and handled in the 3962 // action that invoked this method 3963 clipboard.setContents(contents, null); 3964 3965 if (action == TransferHandler.MOVE) { 3966 doc.remove(p0, p1 - p0); 3967 } 3968 } catch (BadLocationException ble) {} 3969 } 3970 } 3971 } 3972 public boolean importData(JComponent comp, Transferable t) { 3973 if (comp instanceof JTextComponent) { 3974 DataFlavor flavor = getFlavor(t.getTransferDataFlavors()); 3975 3976 if (flavor != null) { 3977 InputContext ic = comp.getInputContext(); 3978 if (ic != null) { 3979 ic.endComposition(); 3980 } 3981 try { 3982 String data = (String)t.getTransferData(flavor); 3983 3984 ((JTextComponent)comp).replaceSelection(data); 3985 return true; 3986 } catch (UnsupportedFlavorException ufe) { 3987 } catch (IOException ioe) { 3988 } 3989 } 3990 } 3991 return false; 3992 } 3993 public boolean canImport(JComponent comp, 3994 DataFlavor[] transferFlavors) { 3995 JTextComponent c = (JTextComponent)comp; 3996 if (!(c.isEditable() && c.isEnabled())) { 3997 return false; 3998 } 3999 return (getFlavor(transferFlavors) != null); 4000 } 4001 public int getSourceActions(JComponent c) { 4002 return NONE; 4003 } 4004 private DataFlavor getFlavor(DataFlavor[] flavors) { 4005 if (flavors != null) { 4006 for (DataFlavor flavor : flavors) { 4007 if (flavor.equals(DataFlavor.stringFlavor)) { 4008 return flavor; 4009 } 4010 } 4011 } 4012 return null; 4013 } 4014 } 4015 4016 /** 4017 * Returns the JTextComponent that most recently had focus. The returned 4018 * value may currently have focus. 4019 */ 4020 static final JTextComponent getFocusedComponent() { 4021 return (JTextComponent)AppContext.getAppContext(). 4022 get(FOCUSED_COMPONENT); 4023 } 4024 4025 private int getCurrentEventModifiers() { 4026 int modifiers = 0; 4027 AWTEvent currentEvent = EventQueue.getCurrentEvent(); 4028 if (currentEvent instanceof InputEvent) { 4029 modifiers = ((InputEvent)currentEvent).getModifiers(); 4030 } else if (currentEvent instanceof ActionEvent) { 4031 modifiers = ((ActionEvent)currentEvent).getModifiers(); 4032 } 4033 return modifiers; 4034 } 4035 4036 private static final Object KEYMAP_TABLE = 4037 new StringBuilder("JTextComponent_KeymapTable"); 4038 4039 // 4040 // member variables used for on-the-spot input method 4041 // editing style support 4042 // 4043 private transient InputMethodRequests inputMethodRequestsHandler; 4044 private SimpleAttributeSet composedTextAttribute; 4045 private String composedTextContent; 4046 private Position composedTextStart; 4047 private Position composedTextEnd; 4048 private Position latestCommittedTextStart; 4049 private Position latestCommittedTextEnd; 4050 private ComposedTextCaret composedTextCaret; 4051 private transient Caret originalCaret; 4052 /** 4053 * Set to true after the check for the override of processInputMethodEvent 4054 * has been checked. 4055 */ 4056 private boolean checkedInputOverride; 4057 private boolean needToSendKeyTypedEvent; 4058 4059 static class DefaultKeymap implements Keymap { 4060 4061 DefaultKeymap(String nm, Keymap parent) { 4062 this.nm = nm; 4063 this.parent = parent; 4064 bindings = new Hashtable<KeyStroke, Action>(); 4065 } 4066 4067 /** 4068 * Fetch the default action to fire if a 4069 * key is typed (ie a KEY_TYPED KeyEvent is received) 4070 * and there is no binding for it. Typically this 4071 * would be some action that inserts text so that 4072 * the keymap doesn't require an action for each 4073 * possible key. 4074 */ 4075 public Action getDefaultAction() { 4076 if (defaultAction != null) { 4077 return defaultAction; 4078 } 4079 return (parent != null) ? parent.getDefaultAction() : null; 4080 } 4081 4082 /** 4083 * Set the default action to fire if a key is typed. 4084 */ 4085 public void setDefaultAction(Action a) { 4086 defaultAction = a; 4087 } 4088 4089 public String getName() { 4090 return nm; 4091 } 4092 4093 public Action getAction(KeyStroke key) { 4094 Action a = bindings.get(key); 4095 if ((a == null) && (parent != null)) { 4096 a = parent.getAction(key); 4097 } 4098 return a; 4099 } 4100 4101 public KeyStroke[] getBoundKeyStrokes() { 4102 KeyStroke[] keys = new KeyStroke[bindings.size()]; 4103 int i = 0; 4104 for (Enumeration<KeyStroke> e = bindings.keys() ; e.hasMoreElements() ;) { 4105 keys[i++] = e.nextElement(); 4106 } 4107 return keys; 4108 } 4109 4110 public Action[] getBoundActions() { 4111 Action[] actions = new Action[bindings.size()]; 4112 int i = 0; 4113 for (Enumeration<Action> e = bindings.elements() ; e.hasMoreElements() ;) { 4114 actions[i++] = e.nextElement(); 4115 } 4116 return actions; 4117 } 4118 4119 public KeyStroke[] getKeyStrokesForAction(Action a) { 4120 if (a == null) { 4121 return null; 4122 } 4123 KeyStroke[] retValue = null; 4124 // Determine local bindings first. 4125 Vector<KeyStroke> keyStrokes = null; 4126 for (Enumeration<KeyStroke> keys = bindings.keys(); keys.hasMoreElements();) { 4127 KeyStroke key = keys.nextElement(); 4128 if (bindings.get(key) == a) { 4129 if (keyStrokes == null) { 4130 keyStrokes = new Vector<KeyStroke>(); 4131 } 4132 keyStrokes.addElement(key); 4133 } 4134 } 4135 // See if the parent has any. 4136 if (parent != null) { 4137 KeyStroke[] pStrokes = parent.getKeyStrokesForAction(a); 4138 if (pStrokes != null) { 4139 // Remove any bindings defined in the parent that 4140 // are locally defined. 4141 int rCount = 0; 4142 for (int counter = pStrokes.length - 1; counter >= 0; 4143 counter--) { 4144 if (isLocallyDefined(pStrokes[counter])) { 4145 pStrokes[counter] = null; 4146 rCount++; 4147 } 4148 } 4149 if (rCount > 0 && rCount < pStrokes.length) { 4150 if (keyStrokes == null) { 4151 keyStrokes = new Vector<KeyStroke>(); 4152 } 4153 for (int counter = pStrokes.length - 1; counter >= 0; 4154 counter--) { 4155 if (pStrokes[counter] != null) { 4156 keyStrokes.addElement(pStrokes[counter]); 4157 } 4158 } 4159 } 4160 else if (rCount == 0) { 4161 if (keyStrokes == null) { 4162 retValue = pStrokes; 4163 } 4164 else { 4165 retValue = new KeyStroke[keyStrokes.size() + 4166 pStrokes.length]; 4167 keyStrokes.copyInto(retValue); 4168 System.arraycopy(pStrokes, 0, retValue, 4169 keyStrokes.size(), pStrokes.length); 4170 keyStrokes = null; 4171 } 4172 } 4173 } 4174 } 4175 if (keyStrokes != null) { 4176 retValue = new KeyStroke[keyStrokes.size()]; 4177 keyStrokes.copyInto(retValue); 4178 } 4179 return retValue; 4180 } 4181 4182 public boolean isLocallyDefined(KeyStroke key) { 4183 return bindings.containsKey(key); 4184 } 4185 4186 public void addActionForKeyStroke(KeyStroke key, Action a) { 4187 bindings.put(key, a); 4188 } 4189 4190 public void removeKeyStrokeBinding(KeyStroke key) { 4191 bindings.remove(key); 4192 } 4193 4194 public void removeBindings() { 4195 bindings.clear(); 4196 } 4197 4198 public Keymap getResolveParent() { 4199 return parent; 4200 } 4201 4202 public void setResolveParent(Keymap parent) { 4203 this.parent = parent; 4204 } 4205 4206 /** 4207 * String representation of the keymap... potentially 4208 * a very long string. 4209 */ 4210 public String toString() { 4211 return "Keymap[" + nm + "]" + bindings; 4212 } 4213 4214 String nm; 4215 Keymap parent; 4216 Hashtable<KeyStroke, Action> bindings; 4217 Action defaultAction; 4218 } 4219 4220 4221 /** 4222 * KeymapWrapper wraps a Keymap inside an InputMap. For KeymapWrapper 4223 * to be useful it must be used with a KeymapActionMap. 4224 * KeymapWrapper for the most part, is an InputMap with two parents. 4225 * The first parent visited is ALWAYS the Keymap, with the second 4226 * parent being the parent inherited from InputMap. If 4227 * <code>keymap.getAction</code> returns null, implying the Keymap 4228 * does not have a binding for the KeyStroke, 4229 * the parent is then visited. If the Keymap has a binding, the 4230 * Action is returned, if not and the KeyStroke represents a 4231 * KeyTyped event and the Keymap has a defaultAction, 4232 * <code>DefaultActionKey</code> is returned. 4233 * <p>KeymapActionMap is then able to transate the object passed in 4234 * to either message the Keymap, or message its default implementation. 4235 */ 4236 static class KeymapWrapper extends InputMap { 4237 static final Object DefaultActionKey = new Object(); 4238 4239 private Keymap keymap; 4240 4241 KeymapWrapper(Keymap keymap) { 4242 this.keymap = keymap; 4243 } 4244 4245 public KeyStroke[] keys() { 4246 KeyStroke[] sKeys = super.keys(); 4247 KeyStroke[] keymapKeys = keymap.getBoundKeyStrokes(); 4248 int sCount = (sKeys == null) ? 0 : sKeys.length; 4249 int keymapCount = (keymapKeys == null) ? 0 : keymapKeys.length; 4250 if (sCount == 0) { 4251 return keymapKeys; 4252 } 4253 if (keymapCount == 0) { 4254 return sKeys; 4255 } 4256 KeyStroke[] retValue = new KeyStroke[sCount + keymapCount]; 4257 // There may be some duplication here... 4258 System.arraycopy(sKeys, 0, retValue, 0, sCount); 4259 System.arraycopy(keymapKeys, 0, retValue, sCount, keymapCount); 4260 return retValue; 4261 } 4262 4263 public int size() { 4264 // There may be some duplication here... 4265 KeyStroke[] keymapStrokes = keymap.getBoundKeyStrokes(); 4266 int keymapCount = (keymapStrokes == null) ? 0: 4267 keymapStrokes.length; 4268 return super.size() + keymapCount; 4269 } 4270 4271 public Object get(KeyStroke keyStroke) { 4272 Object retValue = keymap.getAction(keyStroke); 4273 if (retValue == null) { 4274 retValue = super.get(keyStroke); 4275 if (retValue == null && 4276 keyStroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED && 4277 keymap.getDefaultAction() != null) { 4278 // Implies this is a KeyTyped event, use the default 4279 // action. 4280 retValue = DefaultActionKey; 4281 } 4282 } 4283 return retValue; 4284 } 4285 } 4286 4287 4288 /** 4289 * Wraps a Keymap inside an ActionMap. This is used with 4290 * a KeymapWrapper. If <code>get</code> is passed in 4291 * <code>KeymapWrapper.DefaultActionKey</code>, the default action is 4292 * returned, otherwise if the key is an Action, it is returned. 4293 */ 4294 static class KeymapActionMap extends ActionMap { 4295 private Keymap keymap; 4296 4297 KeymapActionMap(Keymap keymap) { 4298 this.keymap = keymap; 4299 } 4300 4301 public Object[] keys() { 4302 Object[] sKeys = super.keys(); 4303 Object[] keymapKeys = keymap.getBoundActions(); 4304 int sCount = (sKeys == null) ? 0 : sKeys.length; 4305 int keymapCount = (keymapKeys == null) ? 0 : keymapKeys.length; 4306 boolean hasDefault = (keymap.getDefaultAction() != null); 4307 if (hasDefault) { 4308 keymapCount++; 4309 } 4310 if (sCount == 0) { 4311 if (hasDefault) { 4312 Object[] retValue = new Object[keymapCount]; 4313 if (keymapCount > 1) { 4314 System.arraycopy(keymapKeys, 0, retValue, 0, 4315 keymapCount - 1); 4316 } 4317 retValue[keymapCount - 1] = KeymapWrapper.DefaultActionKey; 4318 return retValue; 4319 } 4320 return keymapKeys; 4321 } 4322 if (keymapCount == 0) { 4323 return sKeys; 4324 } 4325 Object[] retValue = new Object[sCount + keymapCount]; 4326 // There may be some duplication here... 4327 System.arraycopy(sKeys, 0, retValue, 0, sCount); 4328 if (hasDefault) { 4329 if (keymapCount > 1) { 4330 System.arraycopy(keymapKeys, 0, retValue, sCount, 4331 keymapCount - 1); 4332 } 4333 retValue[sCount + keymapCount - 1] = KeymapWrapper. 4334 DefaultActionKey; 4335 } 4336 else { 4337 System.arraycopy(keymapKeys, 0, retValue, sCount, keymapCount); 4338 } 4339 return retValue; 4340 } 4341 4342 public int size() { 4343 // There may be some duplication here... 4344 Object[] actions = keymap.getBoundActions(); 4345 int keymapCount = (actions == null) ? 0 : actions.length; 4346 if (keymap.getDefaultAction() != null) { 4347 keymapCount++; 4348 } 4349 return super.size() + keymapCount; 4350 } 4351 4352 public Action get(Object key) { 4353 Action retValue = super.get(key); 4354 if (retValue == null) { 4355 // Try the Keymap. 4356 if (key == KeymapWrapper.DefaultActionKey) { 4357 retValue = keymap.getDefaultAction(); 4358 } 4359 else if (key instanceof Action) { 4360 // This is a little iffy, technically an Action is 4361 // a valid Key. We're assuming the Action came from 4362 // the InputMap though. 4363 retValue = (Action)key; 4364 } 4365 } 4366 return retValue; 4367 } 4368 } 4369 4370 private static final Object FOCUSED_COMPONENT = 4371 new StringBuilder("JTextComponent_FocusedComponent"); 4372 4373 /** 4374 * The default keymap that will be shared by all 4375 * <code>JTextComponent</code> instances unless they 4376 * have had a different keymap set. 4377 */ 4378 public static final String DEFAULT_KEYMAP = "default"; 4379 4380 /** 4381 * Event to use when firing a notification of change to caret 4382 * position. This is mutable so that the event can be reused 4383 * since caret events can be fairly high in bandwidth. 4384 */ 4385 static class MutableCaretEvent extends CaretEvent implements ChangeListener, FocusListener, MouseListener { 4386 4387 MutableCaretEvent(JTextComponent c) { 4388 super(c); 4389 } 4390 4391 final void fire() { 4392 JTextComponent c = (JTextComponent) getSource(); 4393 if (c != null) { 4394 Caret caret = c.getCaret(); 4395 dot = caret.getDot(); 4396 mark = caret.getMark(); 4397 c.fireCaretUpdate(this); 4398 } 4399 } 4400 4401 public final String toString() { 4402 return "dot=" + dot + "," + "mark=" + mark; 4403 } 4404 4405 // --- CaretEvent methods ----------------------- 4406 4407 public final int getDot() { 4408 return dot; 4409 } 4410 4411 public final int getMark() { 4412 return mark; 4413 } 4414 4415 // --- ChangeListener methods ------------------- 4416 4417 public final void stateChanged(ChangeEvent e) { 4418 if (! dragActive) { 4419 fire(); 4420 } 4421 } 4422 4423 // --- FocusListener methods ----------------------------------- 4424 public void focusGained(FocusEvent fe) { 4425 AppContext.getAppContext().put(FOCUSED_COMPONENT, 4426 fe.getSource()); 4427 } 4428 4429 public void focusLost(FocusEvent fe) { 4430 } 4431 4432 // --- MouseListener methods ----------------------------------- 4433 4434 /** 4435 * Requests focus on the associated 4436 * text component, and try to set the cursor position. 4437 * 4438 * @param e the mouse event 4439 * @see MouseListener#mousePressed 4440 */ 4441 public final void mousePressed(MouseEvent e) { 4442 dragActive = true; 4443 } 4444 4445 /** 4446 * Called when the mouse is released. 4447 * 4448 * @param e the mouse event 4449 * @see MouseListener#mouseReleased 4450 */ 4451 public final void mouseReleased(MouseEvent e) { 4452 dragActive = false; 4453 fire(); 4454 } 4455 4456 public final void mouseClicked(MouseEvent e) { 4457 } 4458 4459 public final void mouseEntered(MouseEvent e) { 4460 } 4461 4462 public final void mouseExited(MouseEvent e) { 4463 } 4464 4465 private boolean dragActive; 4466 private int dot; 4467 private int mark; 4468 } 4469 4470 // 4471 // Process any input method events that the component itself 4472 // recognizes. The default on-the-spot handling for input method 4473 // composed(uncommitted) text is done here after all input 4474 // method listeners get called for stealing the events. 4475 // 4476 protected void processInputMethodEvent(InputMethodEvent e) { 4477 // let listeners handle the events 4478 super.processInputMethodEvent(e); 4479 4480 if (!e.isConsumed()) { 4481 if (! isEditable()) { 4482 return; 4483 } else { 4484 switch (e.getID()) { 4485 case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: 4486 replaceInputMethodText(e); 4487 4488 // fall through 4489 4490 case InputMethodEvent.CARET_POSITION_CHANGED: 4491 setInputMethodCaretPosition(e); 4492 break; 4493 } 4494 } 4495 4496 e.consume(); 4497 } 4498 } 4499 4500 // 4501 // Overrides this method to become an active input method client. 4502 // 4503 public InputMethodRequests getInputMethodRequests() { 4504 if (inputMethodRequestsHandler == null) { 4505 inputMethodRequestsHandler = new InputMethodRequestsHandler(); 4506 Document doc = getDocument(); 4507 if (doc != null) { 4508 doc.addDocumentListener((DocumentListener)inputMethodRequestsHandler); 4509 } 4510 } 4511 4512 return inputMethodRequestsHandler; 4513 } 4514 4515 // 4516 // Overrides this method to watch the listener installed. 4517 // 4518 public void addInputMethodListener(InputMethodListener l) { 4519 super.addInputMethodListener(l); 4520 if (l != null) { 4521 needToSendKeyTypedEvent = false; 4522 checkedInputOverride = true; 4523 } 4524 } 4525 4526 4527 // 4528 // Default implementation of the InputMethodRequests interface. 4529 // 4530 class InputMethodRequestsHandler implements InputMethodRequests, DocumentListener { 4531 4532 // --- InputMethodRequests methods --- 4533 4534 public AttributedCharacterIterator cancelLatestCommittedText( 4535 Attribute[] attributes) { 4536 Document doc = getDocument(); 4537 if ((doc != null) && (latestCommittedTextStart != null) 4538 && (!latestCommittedTextStart.equals(latestCommittedTextEnd))) { 4539 try { 4540 int startIndex = latestCommittedTextStart.getOffset(); 4541 int endIndex = latestCommittedTextEnd.getOffset(); 4542 String latestCommittedText = 4543 doc.getText(startIndex, endIndex - startIndex); 4544 doc.remove(startIndex, endIndex - startIndex); 4545 return new AttributedString(latestCommittedText).getIterator(); 4546 } catch (BadLocationException ble) {} 4547 } 4548 return null; 4549 } 4550 4551 public AttributedCharacterIterator getCommittedText(int beginIndex, 4552 int endIndex, Attribute[] attributes) { 4553 int composedStartIndex = 0; 4554 int composedEndIndex = 0; 4555 if (composedTextExists()) { 4556 composedStartIndex = composedTextStart.getOffset(); 4557 composedEndIndex = composedTextEnd.getOffset(); 4558 } 4559 4560 String committed; 4561 try { 4562 if (beginIndex < composedStartIndex) { 4563 if (endIndex <= composedStartIndex) { 4564 committed = getText(beginIndex, endIndex - beginIndex); 4565 } else { 4566 int firstPartLength = composedStartIndex - beginIndex; 4567 committed = getText(beginIndex, firstPartLength) + 4568 getText(composedEndIndex, endIndex - beginIndex - firstPartLength); 4569 } 4570 } else { 4571 committed = getText(beginIndex + (composedEndIndex - composedStartIndex), 4572 endIndex - beginIndex); 4573 } 4574 } catch (BadLocationException ble) { 4575 throw new IllegalArgumentException("Invalid range"); 4576 } 4577 return new AttributedString(committed).getIterator(); 4578 } 4579 4580 public int getCommittedTextLength() { 4581 Document doc = getDocument(); 4582 int length = 0; 4583 if (doc != null) { 4584 length = doc.getLength(); 4585 if (composedTextContent != null) { 4586 if (composedTextEnd == null 4587 || composedTextStart == null) { 4588 /* 4589 * fix for : 6355666 4590 * this is the case when this method is invoked 4591 * from DocumentListener. At this point 4592 * composedTextEnd and composedTextStart are 4593 * not defined yet. 4594 */ 4595 length -= composedTextContent.length(); 4596 } else { 4597 length -= composedTextEnd.getOffset() - 4598 composedTextStart.getOffset(); 4599 } 4600 } 4601 } 4602 return length; 4603 } 4604 4605 public int getInsertPositionOffset() { 4606 int composedStartIndex = 0; 4607 int composedEndIndex = 0; 4608 if (composedTextExists()) { 4609 composedStartIndex = composedTextStart.getOffset(); 4610 composedEndIndex = composedTextEnd.getOffset(); 4611 } 4612 int caretIndex = getCaretPosition(); 4613 4614 if (caretIndex < composedStartIndex) { 4615 return caretIndex; 4616 } else if (caretIndex < composedEndIndex) { 4617 return composedStartIndex; 4618 } else { 4619 return caretIndex - (composedEndIndex - composedStartIndex); 4620 } 4621 } 4622 4623 public TextHitInfo getLocationOffset(int x, int y) { 4624 if (composedTextAttribute == null) { 4625 return null; 4626 } else { 4627 Point p = getLocationOnScreen(); 4628 p.x = x - p.x; 4629 p.y = y - p.y; 4630 int pos = viewToModel(p); 4631 if ((pos >= composedTextStart.getOffset()) && 4632 (pos <= composedTextEnd.getOffset())) { 4633 return TextHitInfo.leading(pos - composedTextStart.getOffset()); 4634 } else { 4635 return null; 4636 } 4637 } 4638 } 4639 4640 public Rectangle getTextLocation(TextHitInfo offset) { 4641 Rectangle r; 4642 4643 try { 4644 r = modelToView(getCaretPosition()); 4645 if (r != null) { 4646 Point p = getLocationOnScreen(); 4647 r.translate(p.x, p.y); 4648 } 4649 } catch (BadLocationException ble) { 4650 r = null; 4651 } 4652 4653 if (r == null) 4654 r = new Rectangle(); 4655 4656 return r; 4657 } 4658 4659 public AttributedCharacterIterator getSelectedText( 4660 Attribute[] attributes) { 4661 String selection = JTextComponent.this.getSelectedText(); 4662 if (selection != null) { 4663 return new AttributedString(selection).getIterator(); 4664 } else { 4665 return null; 4666 } 4667 } 4668 4669 // --- DocumentListener methods --- 4670 4671 public void changedUpdate(DocumentEvent e) { 4672 latestCommittedTextStart = latestCommittedTextEnd = null; 4673 } 4674 4675 public void insertUpdate(DocumentEvent e) { 4676 latestCommittedTextStart = latestCommittedTextEnd = null; 4677 } 4678 4679 public void removeUpdate(DocumentEvent e) { 4680 latestCommittedTextStart = latestCommittedTextEnd = null; 4681 } 4682 } 4683 4684 // 4685 // Replaces the current input method (composed) text according to 4686 // the passed input method event. This method also inserts the 4687 // committed text into the document. 4688 // 4689 private void replaceInputMethodText(InputMethodEvent e) { 4690 int commitCount = e.getCommittedCharacterCount(); 4691 AttributedCharacterIterator text = e.getText(); 4692 int composedTextIndex; 4693 4694 // old composed text deletion 4695 Document doc = getDocument(); 4696 if (composedTextExists()) { 4697 try { 4698 doc.remove(composedTextStart.getOffset(), 4699 composedTextEnd.getOffset() - 4700 composedTextStart.getOffset()); 4701 } catch (BadLocationException ble) {} 4702 composedTextStart = composedTextEnd = null; 4703 composedTextAttribute = null; 4704 composedTextContent = null; 4705 } 4706 4707 if (text != null) { 4708 text.first(); 4709 int committedTextStartIndex = 0; 4710 int committedTextEndIndex = 0; 4711 4712 // committed text insertion 4713 if (commitCount > 0) { 4714 // Remember latest committed text start index 4715 committedTextStartIndex = caret.getDot(); 4716 4717 // Need to generate KeyTyped events for the committed text for components 4718 // that are not aware they are active input method clients. 4719 if (shouldSynthensizeKeyEvents()) { 4720 for (char c = text.current(); commitCount > 0; 4721 c = text.next(), commitCount--) { 4722 KeyEvent ke = new KeyEvent(this, KeyEvent.KEY_TYPED, 4723 EventQueue.getMostRecentEventTime(), 4724 0, KeyEvent.VK_UNDEFINED, c); 4725 processKeyEvent(ke); 4726 } 4727 } else { 4728 StringBuilder strBuf = new StringBuilder(); 4729 for (char c = text.current(); commitCount > 0; 4730 c = text.next(), commitCount--) { 4731 strBuf.append(c); 4732 } 4733 4734 // map it to an ActionEvent 4735 mapCommittedTextToAction(strBuf.toString()); 4736 } 4737 4738 // Remember latest committed text end index 4739 committedTextEndIndex = caret.getDot(); 4740 } 4741 4742 // new composed text insertion 4743 composedTextIndex = text.getIndex(); 4744 if (composedTextIndex < text.getEndIndex()) { 4745 createComposedTextAttribute(composedTextIndex, text); 4746 try { 4747 replaceSelection(null); 4748 doc.insertString(caret.getDot(), composedTextContent, 4749 composedTextAttribute); 4750 composedTextStart = doc.createPosition(caret.getDot() - 4751 composedTextContent.length()); 4752 composedTextEnd = doc.createPosition(caret.getDot()); 4753 } catch (BadLocationException ble) { 4754 composedTextStart = composedTextEnd = null; 4755 composedTextAttribute = null; 4756 composedTextContent = null; 4757 } 4758 } 4759 4760 // Save the latest committed text information 4761 if (committedTextStartIndex != committedTextEndIndex) { 4762 try { 4763 latestCommittedTextStart = doc. 4764 createPosition(committedTextStartIndex); 4765 latestCommittedTextEnd = doc. 4766 createPosition(committedTextEndIndex); 4767 } catch (BadLocationException ble) { 4768 latestCommittedTextStart = 4769 latestCommittedTextEnd = null; 4770 } 4771 } else { 4772 latestCommittedTextStart = 4773 latestCommittedTextEnd = null; 4774 } 4775 } 4776 } 4777 4778 private void createComposedTextAttribute(int composedIndex, 4779 AttributedCharacterIterator text) { 4780 Document doc = getDocument(); 4781 StringBuilder strBuf = new StringBuilder(); 4782 4783 // create attributed string with no attributes 4784 for (char c = text.setIndex(composedIndex); 4785 c != CharacterIterator.DONE; c = text.next()) { 4786 strBuf.append(c); 4787 } 4788 4789 composedTextContent = strBuf.toString(); 4790 composedTextAttribute = new SimpleAttributeSet(); 4791 composedTextAttribute.addAttribute(StyleConstants.ComposedTextAttribute, 4792 new AttributedString(text, composedIndex, text.getEndIndex())); 4793 } 4794 4795 /** 4796 * Saves composed text around the specified position. 4797 * 4798 * The composed text (if any) around the specified position is saved 4799 * in a backing store and removed from the document. 4800 * 4801 * @param pos document position to identify the composed text location 4802 * @return {@code true} if the composed text exists and is saved, 4803 * {@code false} otherwise 4804 * @see #restoreComposedText 4805 * @since 1.7 4806 */ 4807 protected boolean saveComposedText(int pos) { 4808 if (composedTextExists()) { 4809 int start = composedTextStart.getOffset(); 4810 int len = composedTextEnd.getOffset() - 4811 composedTextStart.getOffset(); 4812 if (pos >= start && pos <= start + len) { 4813 try { 4814 getDocument().remove(start, len); 4815 return true; 4816 } catch (BadLocationException ble) {} 4817 } 4818 } 4819 return false; 4820 } 4821 4822 /** 4823 * Restores composed text previously saved by {@code saveComposedText}. 4824 * 4825 * The saved composed text is inserted back into the document. This method 4826 * should be invoked only if {@code saveComposedText} returns {@code true}. 4827 * 4828 * @see #saveComposedText 4829 * @since 1.7 4830 */ 4831 protected void restoreComposedText() { 4832 Document doc = getDocument(); 4833 try { 4834 doc.insertString(caret.getDot(), 4835 composedTextContent, 4836 composedTextAttribute); 4837 composedTextStart = doc.createPosition(caret.getDot() - 4838 composedTextContent.length()); 4839 composedTextEnd = doc.createPosition(caret.getDot()); 4840 } catch (BadLocationException ble) {} 4841 } 4842 4843 // 4844 // Map committed text to an ActionEvent. If the committed text length is 1, 4845 // treat it as a KeyStroke, otherwise or there is no KeyStroke defined, 4846 // treat it just as a default action. 4847 // 4848 private void mapCommittedTextToAction(String committedText) { 4849 Keymap binding = getKeymap(); 4850 if (binding != null) { 4851 Action a = null; 4852 if (committedText.length() == 1) { 4853 KeyStroke k = KeyStroke.getKeyStroke(committedText.charAt(0)); 4854 a = binding.getAction(k); 4855 } 4856 4857 if (a == null) { 4858 a = binding.getDefaultAction(); 4859 } 4860 4861 if (a != null) { 4862 ActionEvent ae = 4863 new ActionEvent(this, ActionEvent.ACTION_PERFORMED, 4864 committedText, 4865 EventQueue.getMostRecentEventTime(), 4866 getCurrentEventModifiers()); 4867 a.actionPerformed(ae); 4868 } 4869 } 4870 } 4871 4872 // 4873 // Sets the caret position according to the passed input method 4874 // event. Also, sets/resets composed text caret appropriately. 4875 // 4876 private void setInputMethodCaretPosition(InputMethodEvent e) { 4877 int dot; 4878 4879 if (composedTextExists()) { 4880 dot = composedTextStart.getOffset(); 4881 if (!(caret instanceof ComposedTextCaret)) { 4882 if (composedTextCaret == null) { 4883 composedTextCaret = new ComposedTextCaret(); 4884 } 4885 originalCaret = caret; 4886 // Sets composed text caret 4887 exchangeCaret(originalCaret, composedTextCaret); 4888 } 4889 4890 TextHitInfo caretPos = e.getCaret(); 4891 if (caretPos != null) { 4892 int index = caretPos.getInsertionIndex(); 4893 dot += index; 4894 if (index == 0) { 4895 // Scroll the component if needed so that the composed text 4896 // becomes visible. 4897 try { 4898 Rectangle d = modelToView(dot); 4899 Rectangle end = modelToView(composedTextEnd.getOffset()); 4900 Rectangle b = getBounds(); 4901 d.x += Math.min(end.x - d.x, b.width); 4902 scrollRectToVisible(d); 4903 } catch (BadLocationException ble) {} 4904 } 4905 } 4906 caret.setDot(dot); 4907 } else if (caret instanceof ComposedTextCaret) { 4908 dot = caret.getDot(); 4909 // Restores original caret 4910 exchangeCaret(caret, originalCaret); 4911 caret.setDot(dot); 4912 } 4913 } 4914 4915 private void exchangeCaret(Caret oldCaret, Caret newCaret) { 4916 int blinkRate = oldCaret.getBlinkRate(); 4917 setCaret(newCaret); 4918 caret.setBlinkRate(blinkRate); 4919 caret.setVisible(hasFocus()); 4920 } 4921 4922 /** 4923 * Returns true if KeyEvents should be synthesized from an InputEvent. 4924 */ 4925 private boolean shouldSynthensizeKeyEvents() { 4926 if (!checkedInputOverride) { 4927 // Checks whether the client code overrides processInputMethodEvent. 4928 // If it is overridden, need not to generate KeyTyped events for committed text. 4929 // If it's not, behave as an passive input method client. 4930 needToSendKeyTypedEvent = !METHOD_OVERRIDDEN.get(getClass()); 4931 checkedInputOverride = true; 4932 } 4933 return needToSendKeyTypedEvent; 4934 } 4935 4936 // 4937 // Checks whether a composed text in this text component 4938 // 4939 boolean composedTextExists() { 4940 return (composedTextStart != null); 4941 } 4942 4943 // 4944 // Caret implementation for editing the composed text. 4945 // 4946 class ComposedTextCaret extends DefaultCaret implements Serializable { 4947 Color bg; 4948 4949 // 4950 // Get the background color of the component 4951 // 4952 public void install(JTextComponent c) { 4953 super.install(c); 4954 4955 Document doc = c.getDocument(); 4956 if (doc instanceof StyledDocument) { 4957 StyledDocument sDoc = (StyledDocument)doc; 4958 Element elem = sDoc.getCharacterElement(c.composedTextStart.getOffset()); 4959 AttributeSet attr = elem.getAttributes(); 4960 bg = sDoc.getBackground(attr); 4961 } 4962 4963 if (bg == null) { 4964 bg = c.getBackground(); 4965 } 4966 } 4967 4968 // 4969 // Draw caret in XOR mode. 4970 // 4971 public void paint(Graphics g) { 4972 if(isVisible()) { 4973 try { 4974 Rectangle r = component.modelToView(getDot()); 4975 g.setXORMode(bg); 4976 g.drawLine(r.x, r.y, r.x, r.y + r.height - 1); 4977 g.setPaintMode(); 4978 } catch (BadLocationException e) { 4979 // can't render I guess 4980 //System.err.println("Can't render cursor"); 4981 } 4982 } 4983 } 4984 4985 // 4986 // If some area other than the composed text is clicked by mouse, 4987 // issue endComposition() to force commit the composed text. 4988 // 4989 protected void positionCaret(MouseEvent me) { 4990 JTextComponent host = component; 4991 Point pt = new Point(me.getX(), me.getY()); 4992 int offset = host.viewToModel(pt); 4993 int composedStartIndex = host.composedTextStart.getOffset(); 4994 if ((offset < composedStartIndex) || 4995 (offset > composedTextEnd.getOffset())) { 4996 try { 4997 // Issue endComposition 4998 Position newPos = host.getDocument().createPosition(offset); 4999 host.getInputContext().endComposition(); 5000 5001 // Post a caret positioning runnable to assure that the positioning 5002 // occurs *after* committing the composed text. 5003 EventQueue.invokeLater(new DoSetCaretPosition(host, newPos)); 5004 } catch (BadLocationException ble) { 5005 System.err.println(ble); 5006 } 5007 } else { 5008 // Normal processing 5009 super.positionCaret(me); 5010 } 5011 } 5012 } 5013 5014 // 5015 // Runnable class for invokeLater() to set caret position later. 5016 // 5017 private class DoSetCaretPosition implements Runnable { 5018 JTextComponent host; 5019 Position newPos; 5020 5021 DoSetCaretPosition(JTextComponent host, Position newPos) { 5022 this.host = host; 5023 this.newPos = newPos; 5024 } 5025 5026 public void run() { 5027 host.setCaretPosition(newPos.getOffset()); 5028 } 5029 } 5030 }