1 /*
   2  * Copyright (c) 1995, 2006, 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 java.awt;
  26 
  27 import java.awt.peer.TextComponentPeer;
  28 import java.awt.event.*;
  29 import java.util.EventListener;
  30 import java.io.ObjectOutputStream;
  31 import java.io.ObjectInputStream;
  32 import java.io.IOException;
  33 import sun.awt.InputMethodSupport;
  34 import java.text.BreakIterator;
  35 import javax.swing.text.AttributeSet;
  36 import javax.accessibility.*;
  37 import java.awt.im.InputMethodRequests;
  38 import javax.tools.annotation.GenerateNativeHeader;
  39 
  40 /**
  41  * The <code>TextComponent</code> class is the superclass of
  42  * any component that allows the editing of some text.
  43  * <p>
  44  * A text component embodies a string of text.  The
  45  * <code>TextComponent</code> class defines a set of methods
  46  * that determine whether or not this text is editable. If the
  47  * component is editable, it defines another set of methods
  48  * that supports a text insertion caret.
  49  * <p>
  50  * In addition, the class defines methods that are used
  51  * to maintain a current <em>selection</em> from the text.
  52  * The text selection, a substring of the component's text,
  53  * is the target of editing operations. It is also referred
  54  * to as the <em>selected text</em>.
  55  *
  56  * @author      Sami Shaio
  57  * @author      Arthur van Hoff
  58  * @since       JDK1.0
  59  */
  60 /* No native methods here, but the constants are needed in the supporting JNI code */
  61 @GenerateNativeHeader
  62 public class TextComponent extends Component implements Accessible {
  63 
  64     /**
  65      * The value of the text.
  66      * A <code>null</code> value is the same as "".
  67      *
  68      * @serial
  69      * @see #setText(String)
  70      * @see #getText()
  71      */
  72     String text;
  73 
  74     /**
  75      * A boolean indicating whether or not this
  76      * <code>TextComponent</code> is editable.
  77      * It will be <code>true</code> if the text component
  78      * is editable and <code>false</code> if not.
  79      *
  80      * @serial
  81      * @see #isEditable()
  82      */
  83     boolean editable = true;
  84 
  85     /**
  86      * The selection refers to the selected text, and the
  87      * <code>selectionStart</code> is the start position
  88      * of the selected text.
  89      *
  90      * @serial
  91      * @see #getSelectionStart()
  92      * @see #setSelectionStart(int)
  93      */
  94     int selectionStart;
  95 
  96     /**
  97      * The selection refers to the selected text, and the
  98      * <code>selectionEnd</code>
  99      * is the end position of the selected text.
 100      *
 101      * @serial
 102      * @see #getSelectionEnd()
 103      * @see #setSelectionEnd(int)
 104      */
 105     int selectionEnd;
 106 
 107     // A flag used to tell whether the background has been set by
 108     // developer code (as opposed to AWT code).  Used to determine
 109     // the background color of non-editable TextComponents.
 110     boolean backgroundSetByClientCode = false;
 111 
 112     /**
 113      * True if this <code>TextComponent</code> has access
 114      * to the System clipboard.
 115      */
 116     transient private boolean canAccessClipboard;
 117 
 118     transient protected TextListener textListener;
 119 
 120     /*
 121      * JDK 1.1 serialVersionUID
 122      */
 123     private static final long serialVersionUID = -2214773872412987419L;
 124 
 125     /**
 126      * Constructs a new text component initialized with the
 127      * specified text. Sets the value of the cursor to
 128      * <code>Cursor.TEXT_CURSOR</code>.
 129      * @param      text       the text to be displayed; if
 130      *             <code>text</code> is <code>null</code>, the empty
 131      *             string <code>""</code> will be displayed
 132      * @exception  HeadlessException if
 133      *             <code>GraphicsEnvironment.isHeadless</code>
 134      *             returns true
 135      * @see        java.awt.GraphicsEnvironment#isHeadless
 136      * @see        java.awt.Cursor
 137      */
 138     TextComponent(String text) throws HeadlessException {
 139         GraphicsEnvironment.checkHeadless();
 140         this.text = (text != null) ? text : "";
 141         setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
 142         checkSystemClipboardAccess();
 143     }
 144 
 145     private void enableInputMethodsIfNecessary() {
 146         if (checkForEnableIM) {
 147             checkForEnableIM = false;
 148             try {
 149                 Toolkit toolkit = Toolkit.getDefaultToolkit();
 150                 boolean shouldEnable = false;
 151                 if (toolkit instanceof InputMethodSupport) {
 152                     shouldEnable = ((InputMethodSupport)toolkit)
 153                       .enableInputMethodsForTextComponent();
 154                 }
 155                 enableInputMethods(shouldEnable);
 156             } catch (Exception e) {
 157                 // if something bad happens, just don't enable input methods
 158             }
 159         }
 160     }
 161 
 162     /**
 163      * Enables or disables input method support for this text component. If input
 164      * method support is enabled and the text component also processes key events,
 165      * incoming events are offered to the current input method and will only be
 166      * processed by the component or dispatched to its listeners if the input method
 167      * does not consume them. Whether and how input method support for this text
 168      * component is enabled or disabled by default is implementation dependent.
 169      *
 170      * @param enable true to enable, false to disable
 171      * @see #processKeyEvent
 172      * @since 1.2
 173      */
 174     public void enableInputMethods(boolean enable) {
 175         checkForEnableIM = false;
 176         super.enableInputMethods(enable);
 177     }
 178 
 179     boolean areInputMethodsEnabled() {
 180         // moved from the constructor above to here and addNotify below,
 181         // this call will initialize the toolkit if not already initialized.
 182         if (checkForEnableIM) {
 183             enableInputMethodsIfNecessary();
 184         }
 185 
 186         // TextComponent handles key events without touching the eventMask or
 187         // having a key listener, so just check whether the flag is set
 188         return (eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0;
 189     }
 190 
 191     public InputMethodRequests getInputMethodRequests() {
 192         TextComponentPeer peer = (TextComponentPeer)this.peer;
 193         if (peer != null) return peer.getInputMethodRequests();
 194         else return null;
 195     }
 196 
 197 
 198 
 199     /**
 200      * Makes this Component displayable by connecting it to a
 201      * native screen resource.
 202      * This method is called internally by the toolkit and should
 203      * not be called directly by programs.
 204      * @see       java.awt.TextComponent#removeNotify
 205      */
 206     public void addNotify() {
 207         super.addNotify();
 208         enableInputMethodsIfNecessary();
 209     }
 210 
 211     /**
 212      * Removes the <code>TextComponent</code>'s peer.
 213      * The peer allows us to modify the appearance of the
 214      * <code>TextComponent</code> without changing its
 215      * functionality.
 216      */
 217     public void removeNotify() {
 218         synchronized (getTreeLock()) {
 219             TextComponentPeer peer = (TextComponentPeer)this.peer;
 220             if (peer != null) {
 221                 text = peer.getText();
 222                 selectionStart = peer.getSelectionStart();
 223                 selectionEnd = peer.getSelectionEnd();
 224             }
 225             super.removeNotify();
 226         }
 227     }
 228 
 229     /**
 230      * Sets the text that is presented by this
 231      * text component to be the specified text.
 232      * @param       t   the new text;
 233      *                  if this parameter is <code>null</code> then
 234      *                  the text is set to the empty string ""
 235      * @see         java.awt.TextComponent#getText
 236      */
 237     public synchronized void setText(String t) {
 238         boolean skipTextEvent = (text == null || text.isEmpty())
 239                 && (t == null || t.isEmpty());
 240         text = (t != null) ? t : "";
 241         TextComponentPeer peer = (TextComponentPeer)this.peer;
 242         // Please note that we do not want to post an event
 243         // if TextArea.setText() or TextField.setText() replaces an empty text
 244         // by an empty text, that is, if component's text remains unchanged.
 245         if (peer != null && !skipTextEvent) {
 246             peer.setText(text);
 247         }
 248     }
 249 
 250     /**
 251      * Returns the text that is presented by this text component.
 252      * By default, this is an empty string.
 253      *
 254      * @return the value of this <code>TextComponent</code>
 255      * @see     java.awt.TextComponent#setText
 256      */
 257     public synchronized String getText() {
 258         TextComponentPeer peer = (TextComponentPeer)this.peer;
 259         if (peer != null) {
 260             text = peer.getText();
 261         }
 262         return text;
 263     }
 264 
 265     /**
 266      * Returns the selected text from the text that is
 267      * presented by this text component.
 268      * @return      the selected text of this text component
 269      * @see         java.awt.TextComponent#select
 270      */
 271     public synchronized String getSelectedText() {
 272         return getText().substring(getSelectionStart(), getSelectionEnd());
 273     }
 274 
 275     /**
 276      * Indicates whether or not this text component is editable.
 277      * @return     <code>true</code> if this text component is
 278      *                  editable; <code>false</code> otherwise.
 279      * @see        java.awt.TextComponent#setEditable
 280      * @since      JDK1.0
 281      */
 282     public boolean isEditable() {
 283         return editable;
 284     }
 285 
 286     /**
 287      * Sets the flag that determines whether or not this
 288      * text component is editable.
 289      * <p>
 290      * If the flag is set to <code>true</code>, this text component
 291      * becomes user editable. If the flag is set to <code>false</code>,
 292      * the user cannot change the text of this text component.
 293      * By default, non-editable text components have a background color
 294      * of SystemColor.control.  This default can be overridden by
 295      * calling setBackground.
 296      *
 297      * @param     b   a flag indicating whether this text component
 298      *                      is user editable.
 299      * @see       java.awt.TextComponent#isEditable
 300      * @since     JDK1.0
 301      */
 302     public synchronized void setEditable(boolean b) {
 303         if (editable == b) {
 304             return;
 305         }
 306 
 307         editable = b;
 308         TextComponentPeer peer = (TextComponentPeer)this.peer;
 309         if (peer != null) {
 310             peer.setEditable(b);
 311         }
 312     }
 313 
 314     /**
 315      * Gets the background color of this text component.
 316      *
 317      * By default, non-editable text components have a background color
 318      * of SystemColor.control.  This default can be overridden by
 319      * calling setBackground.
 320      *
 321      * @return This text component's background color.
 322      *         If this text component does not have a background color,
 323      *         the background color of its parent is returned.
 324      * @see #setBackground(Color)
 325      * @since JDK1.0
 326      */
 327     public Color getBackground() {
 328         if (!editable && !backgroundSetByClientCode) {
 329             return SystemColor.control;
 330         }
 331 
 332         return super.getBackground();
 333     }
 334 
 335     /**
 336      * Sets the background color of this text component.
 337      *
 338      * @param c The color to become this text component's color.
 339      *        If this parameter is null then this text component
 340      *        will inherit the background color of its parent.
 341      * @see #getBackground()
 342      * @since JDK1.0
 343      */
 344     public void setBackground(Color c) {
 345         backgroundSetByClientCode = true;
 346         super.setBackground(c);
 347     }
 348 
 349     /**
 350      * Gets the start position of the selected text in
 351      * this text component.
 352      * @return      the start position of the selected text
 353      * @see         java.awt.TextComponent#setSelectionStart
 354      * @see         java.awt.TextComponent#getSelectionEnd
 355      */
 356     public synchronized int getSelectionStart() {
 357         TextComponentPeer peer = (TextComponentPeer)this.peer;
 358         if (peer != null) {
 359             selectionStart = peer.getSelectionStart();
 360         }
 361         return selectionStart;
 362     }
 363 
 364     /**
 365      * Sets the selection start for this text component to
 366      * the specified position. The new start point is constrained
 367      * to be at or before the current selection end. It also
 368      * cannot be set to less than zero, the beginning of the
 369      * component's text.
 370      * If the caller supplies a value for <code>selectionStart</code>
 371      * that is out of bounds, the method enforces these constraints
 372      * silently, and without failure.
 373      * @param       selectionStart   the start position of the
 374      *                        selected text
 375      * @see         java.awt.TextComponent#getSelectionStart
 376      * @see         java.awt.TextComponent#setSelectionEnd
 377      * @since       JDK1.1
 378      */
 379     public synchronized void setSelectionStart(int selectionStart) {
 380         /* Route through select method to enforce consistent policy
 381          * between selectionStart and selectionEnd.
 382          */
 383         select(selectionStart, getSelectionEnd());
 384     }
 385 
 386     /**
 387      * Gets the end position of the selected text in
 388      * this text component.
 389      * @return      the end position of the selected text
 390      * @see         java.awt.TextComponent#setSelectionEnd
 391      * @see         java.awt.TextComponent#getSelectionStart
 392      */
 393     public synchronized int getSelectionEnd() {
 394         TextComponentPeer peer = (TextComponentPeer)this.peer;
 395         if (peer != null) {
 396             selectionEnd = peer.getSelectionEnd();
 397         }
 398         return selectionEnd;
 399     }
 400 
 401     /**
 402      * Sets the selection end for this text component to
 403      * the specified position. The new end point is constrained
 404      * to be at or after the current selection start. It also
 405      * cannot be set beyond the end of the component's text.
 406      * If the caller supplies a value for <code>selectionEnd</code>
 407      * that is out of bounds, the method enforces these constraints
 408      * silently, and without failure.
 409      * @param       selectionEnd   the end position of the
 410      *                        selected text
 411      * @see         java.awt.TextComponent#getSelectionEnd
 412      * @see         java.awt.TextComponent#setSelectionStart
 413      * @since       JDK1.1
 414      */
 415     public synchronized void setSelectionEnd(int selectionEnd) {
 416         /* Route through select method to enforce consistent policy
 417          * between selectionStart and selectionEnd.
 418          */
 419         select(getSelectionStart(), selectionEnd);
 420     }
 421 
 422     /**
 423      * Selects the text between the specified start and end positions.
 424      * <p>
 425      * This method sets the start and end positions of the
 426      * selected text, enforcing the restriction that the start position
 427      * must be greater than or equal to zero.  The end position must be
 428      * greater than or equal to the start position, and less than or
 429      * equal to the length of the text component's text.  The
 430      * character positions are indexed starting with zero.
 431      * The length of the selection is
 432      * <code>endPosition</code> - <code>startPosition</code>, so the
 433      * character at <code>endPosition</code> is not selected.
 434      * If the start and end positions of the selected text are equal,
 435      * all text is deselected.
 436      * <p>
 437      * If the caller supplies values that are inconsistent or out of
 438      * bounds, the method enforces these constraints silently, and
 439      * without failure. Specifically, if the start position or end
 440      * position is greater than the length of the text, it is reset to
 441      * equal the text length. If the start position is less than zero,
 442      * it is reset to zero, and if the end position is less than the
 443      * start position, it is reset to the start position.
 444      *
 445      * @param        selectionStart the zero-based index of the first
 446                        character (<code>char</code> value) to be selected
 447      * @param        selectionEnd the zero-based end position of the
 448                        text to be selected; the character (<code>char</code> value) at
 449                        <code>selectionEnd</code> is not selected
 450      * @see          java.awt.TextComponent#setSelectionStart
 451      * @see          java.awt.TextComponent#setSelectionEnd
 452      * @see          java.awt.TextComponent#selectAll
 453      */
 454     public synchronized void select(int selectionStart, int selectionEnd) {
 455         String text = getText();
 456         if (selectionStart < 0) {
 457             selectionStart = 0;
 458         }
 459         if (selectionStart > text.length()) {
 460             selectionStart = text.length();
 461         }
 462         if (selectionEnd > text.length()) {
 463             selectionEnd = text.length();
 464         }
 465         if (selectionEnd < selectionStart) {
 466             selectionEnd = selectionStart;
 467         }
 468 
 469         this.selectionStart = selectionStart;
 470         this.selectionEnd = selectionEnd;
 471 
 472         TextComponentPeer peer = (TextComponentPeer)this.peer;
 473         if (peer != null) {
 474             peer.select(selectionStart, selectionEnd);
 475         }
 476     }
 477 
 478     /**
 479      * Selects all the text in this text component.
 480      * @see        java.awt.TextComponent#select
 481      */
 482     public synchronized void selectAll() {
 483         this.selectionStart = 0;
 484         this.selectionEnd = getText().length();
 485 
 486         TextComponentPeer peer = (TextComponentPeer)this.peer;
 487         if (peer != null) {
 488             peer.select(selectionStart, selectionEnd);
 489         }
 490     }
 491 
 492     /**
 493      * Sets the position of the text insertion caret.
 494      * The caret position is constrained to be between 0
 495      * and the last character of the text, inclusive.
 496      * If the passed-in value is greater than this range,
 497      * the value is set to the last character (or 0 if
 498      * the <code>TextComponent</code> contains no text)
 499      * and no error is returned.  If the passed-in value is
 500      * less than 0, an <code>IllegalArgumentException</code>
 501      * is thrown.
 502      *
 503      * @param        position the position of the text insertion caret
 504      * @exception    IllegalArgumentException if <code>position</code>
 505      *               is less than zero
 506      * @since        JDK1.1
 507      */
 508     public synchronized void setCaretPosition(int position) {
 509         if (position < 0) {
 510             throw new IllegalArgumentException("position less than zero.");
 511         }
 512 
 513         int maxposition = getText().length();
 514         if (position > maxposition) {
 515             position = maxposition;
 516         }
 517 
 518         TextComponentPeer peer = (TextComponentPeer)this.peer;
 519         if (peer != null) {
 520             peer.setCaretPosition(position);
 521         } else {
 522             select(position, position);
 523         }
 524     }
 525 
 526     /**
 527      * Returns the position of the text insertion caret.
 528      * The caret position is constrained to be between 0
 529      * and the last character of the text, inclusive.
 530      * If the text or caret have not been set, the default
 531      * caret position is 0.
 532      *
 533      * @return       the position of the text insertion caret
 534      * @see #setCaretPosition(int)
 535      * @since        JDK1.1
 536      */
 537     public synchronized int getCaretPosition() {
 538         TextComponentPeer peer = (TextComponentPeer)this.peer;
 539         int position = 0;
 540 
 541         if (peer != null) {
 542             position = peer.getCaretPosition();
 543         } else {
 544             position = selectionStart;
 545         }
 546         int maxposition = getText().length();
 547         if (position > maxposition) {
 548             position = maxposition;
 549         }
 550         return position;
 551     }
 552 
 553     /**
 554      * Adds the specified text event listener to receive text events
 555      * from this text component.
 556      * If <code>l</code> is <code>null</code>, no exception is
 557      * thrown and no action is performed.
 558      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
 559      * >AWT Threading Issues</a> for details on AWT's threading model.
 560      *
 561      * @param l the text event listener
 562      * @see             #removeTextListener
 563      * @see             #getTextListeners
 564      * @see             java.awt.event.TextListener
 565      */
 566     public synchronized void addTextListener(TextListener l) {
 567         if (l == null) {
 568             return;
 569         }
 570         textListener = AWTEventMulticaster.add(textListener, l);
 571         newEventsOnly = true;
 572     }
 573 
 574     /**
 575      * Removes the specified text event listener so that it no longer
 576      * receives text events from this text component
 577      * If <code>l</code> is <code>null</code>, no exception is
 578      * thrown and no action is performed.
 579      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
 580      * >AWT Threading Issues</a> for details on AWT's threading model.
 581      *
 582      * @param           l     the text listener
 583      * @see             #addTextListener
 584      * @see             #getTextListeners
 585      * @see             java.awt.event.TextListener
 586      * @since           JDK1.1
 587      */
 588     public synchronized void removeTextListener(TextListener l) {
 589         if (l == null) {
 590             return;
 591         }
 592         textListener = AWTEventMulticaster.remove(textListener, l);
 593     }
 594 
 595     /**
 596      * Returns an array of all the text listeners
 597      * registered on this text component.
 598      *
 599      * @return all of this text component's <code>TextListener</code>s
 600      *         or an empty array if no text
 601      *         listeners are currently registered
 602      *
 603      *
 604      * @see #addTextListener
 605      * @see #removeTextListener
 606      * @since 1.4
 607      */
 608     public synchronized TextListener[] getTextListeners() {
 609         return (TextListener[])(getListeners(TextListener.class));
 610     }
 611 
 612     /**
 613      * Returns an array of all the objects currently registered
 614      * as <code><em>Foo</em>Listener</code>s
 615      * upon this <code>TextComponent</code>.
 616      * <code><em>Foo</em>Listener</code>s are registered using the
 617      * <code>add<em>Foo</em>Listener</code> method.
 618      *
 619      * <p>
 620      * You can specify the <code>listenerType</code> argument
 621      * with a class literal, such as
 622      * <code><em>Foo</em>Listener.class</code>.
 623      * For example, you can query a
 624      * <code>TextComponent</code> <code>t</code>
 625      * for its text listeners with the following code:
 626      *
 627      * <pre>TextListener[] tls = (TextListener[])(t.getListeners(TextListener.class));</pre>
 628      *
 629      * If no such listeners exist, this method returns an empty array.
 630      *
 631      * @param listenerType the type of listeners requested; this parameter
 632      *          should specify an interface that descends from
 633      *          <code>java.util.EventListener</code>
 634      * @return an array of all objects registered as
 635      *          <code><em>Foo</em>Listener</code>s on this text component,
 636      *          or an empty array if no such
 637      *          listeners have been added
 638      * @exception ClassCastException if <code>listenerType</code>
 639      *          doesn't specify a class or interface that implements
 640      *          <code>java.util.EventListener</code>
 641      *
 642      * @see #getTextListeners
 643      * @since 1.3
 644      */
 645     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
 646         EventListener l = null;
 647         if  (listenerType == TextListener.class) {
 648             l = textListener;
 649         } else {
 650             return super.getListeners(listenerType);
 651         }
 652         return AWTEventMulticaster.getListeners(l, listenerType);
 653     }
 654 
 655     // REMIND: remove when filtering is done at lower level
 656     boolean eventEnabled(AWTEvent e) {
 657         if (e.id == TextEvent.TEXT_VALUE_CHANGED) {
 658             if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 ||
 659                 textListener != null) {
 660                 return true;
 661             }
 662             return false;
 663         }
 664         return super.eventEnabled(e);
 665     }
 666 
 667     /**
 668      * Processes events on this text component. If the event is a
 669      * <code>TextEvent</code>, it invokes the <code>processTextEvent</code>
 670      * method else it invokes its superclass's <code>processEvent</code>.
 671      * <p>Note that if the event parameter is <code>null</code>
 672      * the behavior is unspecified and may result in an
 673      * exception.
 674      *
 675      * @param e the event
 676      */
 677     protected void processEvent(AWTEvent e) {
 678         if (e instanceof TextEvent) {
 679             processTextEvent((TextEvent)e);
 680             return;
 681         }
 682         super.processEvent(e);
 683     }
 684 
 685     /**
 686      * Processes text events occurring on this text component by
 687      * dispatching them to any registered <code>TextListener</code> objects.
 688      * <p>
 689      * NOTE: This method will not be called unless text events
 690      * are enabled for this component. This happens when one of the
 691      * following occurs:
 692      * <ul>
 693      * <li>A <code>TextListener</code> object is registered
 694      * via <code>addTextListener</code>
 695      * <li>Text events are enabled via <code>enableEvents</code>
 696      * </ul>
 697      * <p>Note that if the event parameter is <code>null</code>
 698      * the behavior is unspecified and may result in an
 699      * exception.
 700      *
 701      * @param e the text event
 702      * @see Component#enableEvents
 703      */
 704     protected void processTextEvent(TextEvent e) {
 705         TextListener listener = textListener;
 706         if (listener != null) {
 707             int id = e.getID();
 708             switch (id) {
 709             case TextEvent.TEXT_VALUE_CHANGED:
 710                 listener.textValueChanged(e);
 711                 break;
 712             }
 713         }
 714     }
 715 
 716     /**
 717      * Returns a string representing the state of this
 718      * <code>TextComponent</code>. This
 719      * method is intended to be used only for debugging purposes, and the
 720      * content and format of the returned string may vary between
 721      * implementations. The returned string may be empty but may not be
 722      * <code>null</code>.
 723      *
 724      * @return      the parameter string of this text component
 725      */
 726     protected String paramString() {
 727         String str = super.paramString() + ",text=" + getText();
 728         if (editable) {
 729             str += ",editable";
 730         }
 731         return str + ",selection=" + getSelectionStart() + "-" + getSelectionEnd();
 732     }
 733 
 734     /**
 735      * Assigns a valid value to the canAccessClipboard instance variable.
 736      */
 737     private void checkSystemClipboardAccess() {
 738         canAccessClipboard = true;
 739         SecurityManager sm = System.getSecurityManager();
 740         if (sm != null) {
 741             try {
 742                 sm.checkSystemClipboardAccess();
 743             }
 744             catch (SecurityException e) {
 745                 canAccessClipboard = false;
 746             }
 747         }
 748     }
 749 
 750     /*
 751      * Serialization support.
 752      */
 753     /**
 754      * The textComponent SerializedDataVersion.
 755      *
 756      * @serial
 757      */
 758     private int textComponentSerializedDataVersion = 1;
 759 
 760     /**
 761      * Writes default serializable fields to stream.  Writes
 762      * a list of serializable TextListener(s) as optional data.
 763      * The non-serializable TextListener(s) are detected and
 764      * no attempt is made to serialize them.
 765      *
 766      * @serialData Null terminated sequence of zero or more pairs.
 767      *             A pair consists of a String and Object.
 768      *             The String indicates the type of object and
 769      *             is one of the following :
 770      *             textListenerK indicating and TextListener object.
 771      *
 772      * @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
 773      * @see java.awt.Component#textListenerK
 774      */
 775     private void writeObject(java.io.ObjectOutputStream s)
 776       throws IOException
 777     {
 778         // Serialization support.  Since the value of the fields
 779         // selectionStart, selectionEnd, and text aren't necessarily
 780         // up to date, we sync them up with the peer before serializing.
 781         TextComponentPeer peer = (TextComponentPeer)this.peer;
 782         if (peer != null) {
 783             text = peer.getText();
 784             selectionStart = peer.getSelectionStart();
 785             selectionEnd = peer.getSelectionEnd();
 786         }
 787 
 788         s.defaultWriteObject();
 789 
 790         AWTEventMulticaster.save(s, textListenerK, textListener);
 791         s.writeObject(null);
 792     }
 793 
 794     /**
 795      * Read the ObjectInputStream, and if it isn't null,
 796      * add a listener to receive text events fired by the
 797      * TextComponent.  Unrecognized keys or values will be
 798      * ignored.
 799      *
 800      * @exception HeadlessException if
 801      * <code>GraphicsEnvironment.isHeadless()</code> returns
 802      * <code>true</code>
 803      * @see #removeTextListener
 804      * @see #addTextListener
 805      * @see java.awt.GraphicsEnvironment#isHeadless
 806      */
 807     private void readObject(ObjectInputStream s)
 808         throws ClassNotFoundException, IOException, HeadlessException
 809     {
 810         GraphicsEnvironment.checkHeadless();
 811         s.defaultReadObject();
 812 
 813         // Make sure the state we just read in for text,
 814         // selectionStart and selectionEnd has legal values
 815         this.text = (text != null) ? text : "";
 816         select(selectionStart, selectionEnd);
 817 
 818         Object keyOrNull;
 819         while(null != (keyOrNull = s.readObject())) {
 820             String key = ((String)keyOrNull).intern();
 821 
 822             if (textListenerK == key) {
 823                 addTextListener((TextListener)(s.readObject()));
 824             } else {
 825                 // skip value for unrecognized key
 826                 s.readObject();
 827             }
 828         }
 829         enableInputMethodsIfNecessary();
 830         checkSystemClipboardAccess();
 831     }
 832 
 833 
 834 /////////////////
 835 // Accessibility support
 836 ////////////////
 837 
 838 
 839     /**
 840      *
 841      */
 842     int getIndexAtPoint(Point p) {
 843         return -1;
 844 /* To be fully implemented in a future release
 845         if (peer == null) {
 846             return -1;
 847         }
 848         TextComponentPeer peer = (TextComponentPeer)this.peer;
 849         return peer.getIndexAtPoint(p.x, p.y);
 850 */
 851     }
 852 
 853 
 854     /**
 855      *
 856      */
 857     Rectangle getCharacterBounds(int i) {
 858         return null;
 859 /* To be fully implemented in a future release
 860         if (peer == null) {
 861             return null;
 862         }
 863         TextComponentPeer peer = (TextComponentPeer)this.peer;
 864         return peer.getCharacterBounds(i);
 865 */
 866     }
 867 
 868 
 869     /**
 870      * Gets the AccessibleContext associated with this TextComponent.
 871      * For text components, the AccessibleContext takes the form of an
 872      * AccessibleAWTTextComponent.
 873      * A new AccessibleAWTTextComponent instance is created if necessary.
 874      *
 875      * @return an AccessibleAWTTextComponent that serves as the
 876      *         AccessibleContext of this TextComponent
 877      * @since 1.3
 878      */
 879     public AccessibleContext getAccessibleContext() {
 880         if (accessibleContext == null) {
 881             accessibleContext = new AccessibleAWTTextComponent();
 882         }
 883         return accessibleContext;
 884     }
 885 
 886     /**
 887      * This class implements accessibility support for the
 888      * <code>TextComponent</code> class.  It provides an implementation of the
 889      * Java Accessibility API appropriate to text component user-interface
 890      * elements.
 891      * @since 1.3
 892      */
 893     protected class AccessibleAWTTextComponent extends AccessibleAWTComponent
 894         implements AccessibleText, TextListener
 895     {
 896         /*
 897          * JDK 1.3 serialVersionUID
 898          */
 899         private static final long serialVersionUID = 3631432373506317811L;
 900 
 901         /**
 902          * Constructs an AccessibleAWTTextComponent.  Adds a listener to track
 903          * caret change.
 904          */
 905         public AccessibleAWTTextComponent() {
 906             TextComponent.this.addTextListener(this);
 907         }
 908 
 909         /**
 910          * TextListener notification of a text value change.
 911          */
 912         public void textValueChanged(TextEvent textEvent)  {
 913             Integer cpos = Integer.valueOf(TextComponent.this.getCaretPosition());
 914             firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, cpos);
 915         }
 916 
 917         /**
 918          * Gets the state set of the TextComponent.
 919          * The AccessibleStateSet of an object is composed of a set of
 920          * unique AccessibleStates.  A change in the AccessibleStateSet
 921          * of an object will cause a PropertyChangeEvent to be fired
 922          * for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property.
 923          *
 924          * @return an instance of AccessibleStateSet containing the
 925          * current state set of the object
 926          * @see AccessibleStateSet
 927          * @see AccessibleState
 928          * @see #addPropertyChangeListener
 929          */
 930         public AccessibleStateSet getAccessibleStateSet() {
 931             AccessibleStateSet states = super.getAccessibleStateSet();
 932             if (TextComponent.this.isEditable()) {
 933                 states.add(AccessibleState.EDITABLE);
 934             }
 935             return states;
 936         }
 937 
 938 
 939         /**
 940          * Gets the role of this object.
 941          *
 942          * @return an instance of AccessibleRole describing the role of the
 943          * object (AccessibleRole.TEXT)
 944          * @see AccessibleRole
 945          */
 946         public AccessibleRole getAccessibleRole() {
 947             return AccessibleRole.TEXT;
 948         }
 949 
 950         /**
 951          * Get the AccessibleText associated with this object.  In the
 952          * implementation of the Java Accessibility API for this class,
 953          * return this object, which is responsible for implementing the
 954          * AccessibleText interface on behalf of itself.
 955          *
 956          * @return this object
 957          */
 958         public AccessibleText getAccessibleText() {
 959             return this;
 960         }
 961 
 962 
 963         // --- interface AccessibleText methods ------------------------
 964 
 965         /**
 966          * Many of these methods are just convenience methods; they
 967          * just call the equivalent on the parent
 968          */
 969 
 970         /**
 971          * Given a point in local coordinates, return the zero-based index
 972          * of the character under that Point.  If the point is invalid,
 973          * this method returns -1.
 974          *
 975          * @param p the Point in local coordinates
 976          * @return the zero-based index of the character under Point p.
 977          */
 978         public int getIndexAtPoint(Point p) {
 979             return TextComponent.this.getIndexAtPoint(p);
 980         }
 981 
 982         /**
 983          * Determines the bounding box of the character at the given
 984          * index into the string.  The bounds are returned in local
 985          * coordinates.  If the index is invalid a null rectangle
 986          * is returned.
 987          *
 988          * @param i the index into the String >= 0
 989          * @return the screen coordinates of the character's bounding box
 990          */
 991         public Rectangle getCharacterBounds(int i) {
 992             return TextComponent.this.getCharacterBounds(i);
 993         }
 994 
 995         /**
 996          * Returns the number of characters (valid indicies)
 997          *
 998          * @return the number of characters >= 0
 999          */
1000         public int getCharCount() {
1001             return TextComponent.this.getText().length();
1002         }
1003 
1004         /**
1005          * Returns the zero-based offset of the caret.
1006          *
1007          * Note: The character to the right of the caret will have the
1008          * same index value as the offset (the caret is between
1009          * two characters).
1010          *
1011          * @return the zero-based offset of the caret.
1012          */
1013         public int getCaretPosition() {
1014             return TextComponent.this.getCaretPosition();
1015         }
1016 
1017         /**
1018          * Returns the AttributeSet for a given character (at a given index).
1019          *
1020          * @param i the zero-based index into the text
1021          * @return the AttributeSet of the character
1022          */
1023         public AttributeSet getCharacterAttribute(int i) {
1024             return null; // No attributes in TextComponent
1025         }
1026 
1027         /**
1028          * Returns the start offset within the selected text.
1029          * If there is no selection, but there is
1030          * a caret, the start and end offsets will be the same.
1031          * Return 0 if the text is empty, or the caret position
1032          * if no selection.
1033          *
1034          * @return the index into the text of the start of the selection >= 0
1035          */
1036         public int getSelectionStart() {
1037             return TextComponent.this.getSelectionStart();
1038         }
1039 
1040         /**
1041          * Returns the end offset within the selected text.
1042          * If there is no selection, but there is
1043          * a caret, the start and end offsets will be the same.
1044          * Return 0 if the text is empty, or the caret position
1045          * if no selection.
1046          *
1047          * @return the index into teh text of the end of the selection >= 0
1048          */
1049         public int getSelectionEnd() {
1050             return TextComponent.this.getSelectionEnd();
1051         }
1052 
1053         /**
1054          * Returns the portion of the text that is selected.
1055          *
1056          * @return the text, null if no selection
1057          */
1058         public String getSelectedText() {
1059             String selText = TextComponent.this.getSelectedText();
1060             // Fix for 4256662
1061             if (selText == null || selText.equals("")) {
1062                 return null;
1063             }
1064             return selText;
1065         }
1066 
1067         /**
1068          * Returns the String at a given index.
1069          *
1070          * @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
1071          * or AccessibleText.SENTENCE to retrieve
1072          * @param index an index within the text >= 0
1073          * @return the letter, word, or sentence,
1074          *   null for an invalid index or part
1075          */
1076         public String getAtIndex(int part, int index) {
1077             if (index < 0 || index >= TextComponent.this.getText().length()) {
1078                 return null;
1079             }
1080             switch (part) {
1081             case AccessibleText.CHARACTER:
1082                 return TextComponent.this.getText().substring(index, index+1);
1083             case AccessibleText.WORD:  {
1084                     String s = TextComponent.this.getText();
1085                     BreakIterator words = BreakIterator.getWordInstance();
1086                     words.setText(s);
1087                     int end = words.following(index);
1088                     return s.substring(words.previous(), end);
1089                 }
1090             case AccessibleText.SENTENCE:  {
1091                     String s = TextComponent.this.getText();
1092                     BreakIterator sentence = BreakIterator.getSentenceInstance();
1093                     sentence.setText(s);
1094                     int end = sentence.following(index);
1095                     return s.substring(sentence.previous(), end);
1096                 }
1097             default:
1098                 return null;
1099             }
1100         }
1101 
1102         private static final boolean NEXT = true;
1103         private static final boolean PREVIOUS = false;
1104 
1105         /**
1106          * Needed to unify forward and backward searching.
1107          * The method assumes that s is the text assigned to words.
1108          */
1109         private int findWordLimit(int index, BreakIterator words, boolean direction,
1110                                          String s) {
1111             // Fix for 4256660 and 4256661.
1112             // Words iterator is different from character and sentence iterators
1113             // in that end of one word is not necessarily start of another word.
1114             // Please see java.text.BreakIterator JavaDoc. The code below is
1115             // based on nextWordStartAfter example from BreakIterator.java.
1116             int last = (direction == NEXT) ? words.following(index)
1117                                            : words.preceding(index);
1118             int current = (direction == NEXT) ? words.next()
1119                                               : words.previous();
1120             while (current != BreakIterator.DONE) {
1121                 for (int p = Math.min(last, current); p < Math.max(last, current); p++) {
1122                     if (Character.isLetter(s.charAt(p))) {
1123                         return last;
1124                     }
1125                 }
1126                 last = current;
1127                 current = (direction == NEXT) ? words.next()
1128                                               : words.previous();
1129             }
1130             return BreakIterator.DONE;
1131         }
1132 
1133         /**
1134          * Returns the String after a given index.
1135          *
1136          * @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
1137          * or AccessibleText.SENTENCE to retrieve
1138          * @param index an index within the text >= 0
1139          * @return the letter, word, or sentence, null for an invalid
1140          *  index or part
1141          */
1142         public String getAfterIndex(int part, int index) {
1143             if (index < 0 || index >= TextComponent.this.getText().length()) {
1144                 return null;
1145             }
1146             switch (part) {
1147             case AccessibleText.CHARACTER:
1148                 if (index+1 >= TextComponent.this.getText().length()) {
1149                    return null;
1150                 }
1151                 return TextComponent.this.getText().substring(index+1, index+2);
1152             case AccessibleText.WORD:  {
1153                     String s = TextComponent.this.getText();
1154                     BreakIterator words = BreakIterator.getWordInstance();
1155                     words.setText(s);
1156                     int start = findWordLimit(index, words, NEXT, s);
1157                     if (start == BreakIterator.DONE || start >= s.length()) {
1158                         return null;
1159                     }
1160                     int end = words.following(start);
1161                     if (end == BreakIterator.DONE || end >= s.length()) {
1162                         return null;
1163                     }
1164                     return s.substring(start, end);
1165                 }
1166             case AccessibleText.SENTENCE:  {
1167                     String s = TextComponent.this.getText();
1168                     BreakIterator sentence = BreakIterator.getSentenceInstance();
1169                     sentence.setText(s);
1170                     int start = sentence.following(index);
1171                     if (start == BreakIterator.DONE || start >= s.length()) {
1172                         return null;
1173                     }
1174                     int end = sentence.following(start);
1175                     if (end == BreakIterator.DONE || end >= s.length()) {
1176                         return null;
1177                     }
1178                     return s.substring(start, end);
1179                 }
1180             default:
1181                 return null;
1182             }
1183         }
1184 
1185 
1186         /**
1187          * Returns the String before a given index.
1188          *
1189          * @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
1190          *   or AccessibleText.SENTENCE to retrieve
1191          * @param index an index within the text >= 0
1192          * @return the letter, word, or sentence, null for an invalid index
1193          *  or part
1194          */
1195         public String getBeforeIndex(int part, int index) {
1196             if (index < 0 || index > TextComponent.this.getText().length()-1) {
1197                 return null;
1198             }
1199             switch (part) {
1200             case AccessibleText.CHARACTER:
1201                 if (index == 0) {
1202                     return null;
1203                 }
1204                 return TextComponent.this.getText().substring(index-1, index);
1205             case AccessibleText.WORD:  {
1206                     String s = TextComponent.this.getText();
1207                     BreakIterator words = BreakIterator.getWordInstance();
1208                     words.setText(s);
1209                     int end = findWordLimit(index, words, PREVIOUS, s);
1210                     if (end == BreakIterator.DONE) {
1211                         return null;
1212                     }
1213                     int start = words.preceding(end);
1214                     if (start == BreakIterator.DONE) {
1215                         return null;
1216                     }
1217                     return s.substring(start, end);
1218                 }
1219             case AccessibleText.SENTENCE:  {
1220                     String s = TextComponent.this.getText();
1221                     BreakIterator sentence = BreakIterator.getSentenceInstance();
1222                     sentence.setText(s);
1223                     int end = sentence.following(index);
1224                     end = sentence.previous();
1225                     int start = sentence.previous();
1226                     if (start == BreakIterator.DONE) {
1227                         return null;
1228                     }
1229                     return s.substring(start, end);
1230                 }
1231             default:
1232                 return null;
1233             }
1234         }
1235     }  // end of AccessibleAWTTextComponent
1236 
1237     private boolean checkForEnableIM = true;
1238 }