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;
  26 
  27 import java.awt.*;
  28 import java.beans.JavaBean;
  29 import java.beans.BeanProperty;
  30 import java.lang.reflect.*;
  31 import java.net.*;
  32 import java.util.*;
  33 import java.io.*;
  34 
  35 import javax.swing.plaf.*;
  36 import javax.swing.text.*;
  37 import javax.swing.event.*;
  38 import javax.swing.text.html.*;
  39 import javax.accessibility.*;
  40 import sun.reflect.misc.ReflectUtil;
  41 
  42 /**
  43  * A text component to edit various kinds of content.
  44  * You can find how-to information and examples of using editor panes in
  45  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/text.html">Using Text Components</a>,
  46  * a section in <em>The Java Tutorial.</em>
  47  *
  48  * <p>
  49  * This component uses implementations of the
  50  * <code>EditorKit</code> to accomplish its behavior. It effectively
  51  * morphs into the proper kind of text editor for the kind
  52  * of content it is given.  The content type that editor is bound
  53  * to at any given time is determined by the <code>EditorKit</code> currently
  54  * installed.  If the content is set to a new URL, its type is used
  55  * to determine the <code>EditorKit</code> that should be used to
  56  * load the content.
  57  * <p>
  58  * By default, the following types of content are known:
  59  * <dl>
  60  * <dt><b>text/plain</b>
  61  * <dd>Plain text, which is the default the type given isn't
  62  * recognized.  The kit used in this case is an extension of
  63  * <code>DefaultEditorKit</code> that produces a wrapped plain text view.
  64  * <dt><b>text/html</b>
  65  * <dd>HTML text.  The kit used in this case is the class
  66  * <code>javax.swing.text.html.HTMLEditorKit</code>
  67  * which provides HTML 3.2 support.
  68  * <dt><b>text/rtf</b>
  69  * <dd>RTF text.  The kit used in this case is the class
  70  * <code>javax.swing.text.rtf.RTFEditorKit</code>
  71  * which provides a limited support of the Rich Text Format.
  72  * </dl>
  73  * <p>
  74  * There are several ways to load content into this component.
  75  * <ol>
  76  * <li>
  77  * The {@link #setText setText} method can be used to initialize
  78  * the component from a string.  In this case the current
  79  * <code>EditorKit</code> will be used, and the content type will be
  80  * expected to be of this type.
  81  * <li>
  82  * The {@link #read read} method can be used to initialize the
  83  * component from a <code>Reader</code>.  Note that if the content type is HTML,
  84  * relative references (e.g. for things like images) can't be resolved
  85  * unless the &lt;base&gt; tag is used or the <em>Base</em> property
  86  * on <code>HTMLDocument</code> is set.
  87  * In this case the current <code>EditorKit</code> will be used,
  88  * and the content type will be expected to be of this type.
  89  * <li>
  90  * The {@link #setPage setPage} method can be used to initialize
  91  * the component from a URL.  In this case, the content type will be
  92  * determined from the URL, and the registered <code>EditorKit</code>
  93  * for that content type will be set.
  94  * </ol>
  95  * <p>
  96  * Some kinds of content may provide hyperlink support by generating
  97  * hyperlink events.  The HTML <code>EditorKit</code> will generate
  98  * hyperlink events if the <code>JEditorPane</code> is <em>not editable</em>
  99  * (<code>JEditorPane.setEditable(false);</code> has been called).
 100  * If HTML frames are embedded in the document, the typical response would be
 101  * to change a portion of the current document.  The following code
 102  * fragment is a possible hyperlink listener implementation, that treats
 103  * HTML frame events specially, and simply displays any other activated
 104  * hyperlinks.
 105  * <pre>
 106 
 107 &nbsp;    class Hyperactive implements HyperlinkListener {
 108 &nbsp;
 109 &nbsp;        public void hyperlinkUpdate(HyperlinkEvent e) {
 110 &nbsp;            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
 111 &nbsp;                JEditorPane pane = (JEditorPane) e.getSource();
 112 &nbsp;                if (e instanceof HTMLFrameHyperlinkEvent) {
 113 &nbsp;                    HTMLFrameHyperlinkEvent  evt = (HTMLFrameHyperlinkEvent)e;
 114 &nbsp;                    HTMLDocument doc = (HTMLDocument)pane.getDocument();
 115 &nbsp;                    doc.processHTMLFrameHyperlinkEvent(evt);
 116 &nbsp;                } else {
 117 &nbsp;                    try {
 118 &nbsp;                        pane.setPage(e.getURL());
 119 &nbsp;                    } catch (Throwable t) {
 120 &nbsp;                        t.printStackTrace();
 121 &nbsp;                    }
 122 &nbsp;                }
 123 &nbsp;            }
 124 &nbsp;        }
 125 &nbsp;    }
 126 
 127  * </pre>
 128  * <p>
 129  * For information on customizing how <b>text/html</b> is rendered please see
 130  * {@link #W3C_LENGTH_UNITS} and {@link #HONOR_DISPLAY_PROPERTIES}
 131  * <p>
 132  * Culturally dependent information in some documents is handled through
 133  * a mechanism called character encoding.  Character encoding is an
 134  * unambiguous mapping of the members of a character set (letters, ideographs,
 135  * digits, symbols, or control functions) to specific numeric code values. It
 136  * represents the way the file is stored. Example character encodings are
 137  * ISO-8859-1, ISO-8859-5, Shift-jis, Euc-jp, and UTF-8. When the file is
 138  * passed to an user agent (<code>JEditorPane</code>) it is converted to
 139  * the document character set (ISO-10646 aka Unicode).
 140  * <p>
 141  * There are multiple ways to get a character set mapping to happen
 142  * with <code>JEditorPane</code>.
 143  * <ol>
 144  * <li>
 145  * One way is to specify the character set as a parameter of the MIME
 146  * type.  This will be established by a call to the
 147  * {@link #setContentType setContentType} method.  If the content
 148  * is loaded by the {@link #setPage setPage} method the content
 149  * type will have been set according to the specification of the URL.
 150  * It the file is loaded directly, the content type would be expected to
 151  * have been set prior to loading.
 152  * <li>
 153  * Another way the character set can be specified is in the document itself.
 154  * This requires reading the document prior to determining the character set
 155  * that is desired.  To handle this, it is expected that the
 156  * <code>EditorKit</code>.read operation throw a
 157  * <code>ChangedCharSetException</code> which will
 158  * be caught.  The read is then restarted with a new Reader that uses
 159  * the character set specified in the <code>ChangedCharSetException</code>
 160  * (which is an <code>IOException</code>).
 161  * </ol>
 162  *
 163  * <dl>
 164  * <dt><b>Newlines</b>
 165  * <dd>
 166  * For a discussion on how newlines are handled, see
 167  * <a href="text/DefaultEditorKit.html">DefaultEditorKit</a>.
 168  * </dl>
 169  *
 170  * <p>
 171  * <strong>Warning:</strong> Swing is not thread safe. For more
 172  * information see <a
 173  * href="package-summary.html#threading">Swing's Threading
 174  * Policy</a>.
 175  * <p>
 176  * <strong>Warning:</strong>
 177  * Serialized objects of this class will not be compatible with
 178  * future Swing releases. The current serialization support is
 179  * appropriate for short term storage or RMI between applications running
 180  * the same version of Swing.  As of 1.4, support for long term storage
 181  * of all JavaBeans&trade;
 182  * has been added to the <code>java.beans</code> package.
 183  * Please see {@link java.beans.XMLEncoder}.
 184  *
 185  * @author  Timothy Prinzing
 186  * @since 1.2
 187  */
 188 @JavaBean(defaultProperty = "UIClassID", description = "A text component to edit various types of content.")
 189 @SwingContainer(false)
 190 @SuppressWarnings("serial") // Same-version serialization only
 191 public class JEditorPane extends JTextComponent {
 192 
 193     /**
 194      * Creates a new <code>JEditorPane</code>.
 195      * The document model is set to <code>null</code>.
 196      */
 197     public JEditorPane() {
 198         super();
 199         setFocusCycleRoot(true);
 200         setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
 201                 public Component getComponentAfter(Container focusCycleRoot,
 202                                                    Component aComponent) {
 203                     if (focusCycleRoot != JEditorPane.this ||
 204                         (!isEditable() && getComponentCount() > 0)) {
 205                         return super.getComponentAfter(focusCycleRoot,
 206                                                        aComponent);
 207                     } else {
 208                         Container rootAncestor = getFocusCycleRootAncestor();
 209                         return (rootAncestor != null)
 210                             ? rootAncestor.getFocusTraversalPolicy().
 211                                   getComponentAfter(rootAncestor,
 212                                                     JEditorPane.this)
 213                             : null;
 214                     }
 215                 }
 216                 public Component getComponentBefore(Container focusCycleRoot,
 217                                                     Component aComponent) {
 218                     if (focusCycleRoot != JEditorPane.this ||
 219                         (!isEditable() && getComponentCount() > 0)) {
 220                         return super.getComponentBefore(focusCycleRoot,
 221                                                         aComponent);
 222                     } else {
 223                         Container rootAncestor = getFocusCycleRootAncestor();
 224                         return (rootAncestor != null)
 225                             ? rootAncestor.getFocusTraversalPolicy().
 226                                   getComponentBefore(rootAncestor,
 227                                                      JEditorPane.this)
 228                             : null;
 229                     }
 230                 }
 231                 public Component getDefaultComponent(Container focusCycleRoot)
 232                 {
 233                     return (focusCycleRoot != JEditorPane.this ||
 234                             (!isEditable() && getComponentCount() > 0))
 235                         ? super.getDefaultComponent(focusCycleRoot)
 236                         : null;
 237                 }
 238                 protected boolean accept(Component aComponent) {
 239                     return (aComponent != JEditorPane.this)
 240                         ? super.accept(aComponent)
 241                         : false;
 242                 }
 243             });
 244         LookAndFeel.installProperty(this,
 245                                     "focusTraversalKeysForward",
 246                                     JComponent.
 247                                     getManagingFocusForwardTraversalKeys());
 248         LookAndFeel.installProperty(this,
 249                                     "focusTraversalKeysBackward",
 250                                     JComponent.
 251                                     getManagingFocusBackwardTraversalKeys());
 252     }
 253 
 254     /**
 255      * Creates a <code>JEditorPane</code> based on a specified URL for input.
 256      *
 257      * @param initialPage the URL
 258      * @exception IOException if the URL is <code>null</code>
 259      *          or cannot be accessed
 260      */
 261     public JEditorPane(URL initialPage) throws IOException {
 262         this();
 263         setPage(initialPage);
 264     }
 265 
 266     /**
 267      * Creates a <code>JEditorPane</code> based on a string containing
 268      * a URL specification.
 269      *
 270      * @param url the URL
 271      * @exception IOException if the URL is <code>null</code> or
 272      *          cannot be accessed
 273      */
 274     public JEditorPane(String url) throws IOException {
 275         this();
 276         setPage(url);
 277     }
 278 
 279     /**
 280      * Creates a <code>JEditorPane</code> that has been initialized
 281      * to the given text.  This is a convenience constructor that calls the
 282      * <code>setContentType</code> and <code>setText</code> methods.
 283      *
 284      * @param type mime type of the given text
 285      * @param text the text to initialize with; may be <code>null</code>
 286      * @exception NullPointerException if the <code>type</code> parameter
 287      *          is <code>null</code>
 288      */
 289     public JEditorPane(String type, String text) {
 290         this();
 291         setContentType(type);
 292         setText(text);
 293     }
 294 
 295     /**
 296      * Adds a hyperlink listener for notification of any changes, for example
 297      * when a link is selected and entered.
 298      *
 299      * @param listener the listener
 300      */
 301     public synchronized void addHyperlinkListener(HyperlinkListener listener) {
 302         listenerList.add(HyperlinkListener.class, listener);
 303     }
 304 
 305     /**
 306      * Removes a hyperlink listener.
 307      *
 308      * @param listener the listener
 309      */
 310     public synchronized void removeHyperlinkListener(HyperlinkListener listener) {
 311         listenerList.remove(HyperlinkListener.class, listener);
 312     }
 313 
 314     /**
 315      * Returns an array of all the <code>HyperLinkListener</code>s added
 316      * to this JEditorPane with addHyperlinkListener().
 317      *
 318      * @return all of the <code>HyperLinkListener</code>s added or an empty
 319      *         array if no listeners have been added
 320      * @since 1.4
 321      */
 322     @BeanProperty(bound = false)
 323     public synchronized HyperlinkListener[] getHyperlinkListeners() {
 324         return listenerList.getListeners(javax.swing.event.HyperlinkListener.class);
 325     }
 326 
 327     /**
 328      * Notifies all listeners that have registered interest for
 329      * notification on this event type.  This is normally called
 330      * by the currently installed <code>EditorKit</code> if a content type
 331      * that supports hyperlinks is currently active and there
 332      * was activity with a link.  The listener list is processed
 333      * last to first.
 334      *
 335      * @param e the event
 336      * @see EventListenerList
 337      */
 338     public void fireHyperlinkUpdate(HyperlinkEvent e) {
 339         // Guaranteed to return a non-null array
 340         Object[] listeners = listenerList.getListenerList();
 341         // Process the listeners last to first, notifying
 342         // those that are interested in this event
 343         for (int i = listeners.length-2; i>=0; i-=2) {
 344             if (listeners[i]==HyperlinkListener.class) {
 345                 ((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e);
 346             }
 347         }
 348     }
 349 
 350 
 351     /**
 352      * Sets the current URL being displayed.  The content type of the
 353      * pane is set, and if the editor kit for the pane is
 354      * non-<code>null</code>, then
 355      * a new default document is created and the URL is read into it.
 356      * If the URL contains and reference location, the location will
 357      * be scrolled to by calling the <code>scrollToReference</code>
 358      * method. If the desired URL is the one currently being displayed,
 359      * the document will not be reloaded. To force a document
 360      * reload it is necessary to clear the stream description property
 361      * of the document. The following code shows how this can be done:
 362      *
 363      * <pre>
 364      *   Document doc = jEditorPane.getDocument();
 365      *   doc.putProperty(Document.StreamDescriptionProperty, null);
 366      * </pre>
 367      *
 368      * If the desired URL is not the one currently being
 369      * displayed, the <code>getStream</code> method is called to
 370      * give subclasses control over the stream provided.
 371      * <p>
 372      * This may load either synchronously or asynchronously
 373      * depending upon the document returned by the <code>EditorKit</code>.
 374      * If the <code>Document</code> is of type
 375      * <code>AbstractDocument</code> and has a value returned by
 376      * <code>AbstractDocument.getAsynchronousLoadPriority</code>
 377      * that is greater than or equal to zero, the page will be
 378      * loaded on a separate thread using that priority.
 379      * <p>
 380      * If the document is loaded synchronously, it will be
 381      * filled in with the stream prior to being installed into
 382      * the editor with a call to <code>setDocument</code>, which
 383      * is bound and will fire a property change event.  If an
 384      * <code>IOException</code> is thrown the partially loaded
 385      * document will
 386      * be discarded and neither the document or page property
 387      * change events will be fired.  If the document is
 388      * successfully loaded and installed, a view will be
 389      * built for it by the UI which will then be scrolled if
 390      * necessary, and then the page property change event
 391      * will be fired.
 392      * <p>
 393      * If the document is loaded asynchronously, the document
 394      * will be installed into the editor immediately using a
 395      * call to <code>setDocument</code> which will fire a
 396      * document property change event, then a thread will be
 397      * created which will begin doing the actual loading.
 398      * In this case, the page property change event will not be
 399      * fired by the call to this method directly, but rather will be
 400      * fired when the thread doing the loading has finished.
 401      * It will also be fired on the event-dispatch thread.
 402      * Since the calling thread can not throw an <code>IOException</code>
 403      * in the event of failure on the other thread, the page
 404      * property change event will be fired when the other
 405      * thread is done whether the load was successful or not.
 406      *
 407      * @param page the URL of the page
 408      * @exception IOException for a <code>null</code> or invalid
 409      *          page specification, or exception from the stream being read
 410      * @see #getPage
 411      */
 412     @BeanProperty(expert = true, description
 413             = "the URL used to set content")
 414     public void setPage(URL page) throws IOException {
 415         if (page == null) {
 416             throw new IOException("invalid url");
 417         }
 418         URL loaded = getPage();
 419 
 420 
 421         // reset scrollbar
 422         if (!page.equals(loaded) && page.getRef() == null) {
 423             scrollRectToVisible(new Rectangle(0,0,1,1));
 424         }
 425         boolean reloaded = false;
 426         Object postData = getPostData();
 427         if ((loaded == null) || !loaded.sameFile(page) || (postData != null)) {
 428             // different url or POST method, load the new content
 429 
 430             int p = getAsynchronousLoadPriority(getDocument());
 431             if (p < 0) {
 432                 // open stream synchronously
 433                 InputStream in = getStream(page);
 434                 if (kit != null) {
 435                     Document doc = initializeModel(kit, page);
 436 
 437                     // At this point, one could either load up the model with no
 438                     // view notifications slowing it down (i.e. best synchronous
 439                     // behavior) or set the model and start to feed it on a separate
 440                     // thread (best asynchronous behavior).
 441                     p = getAsynchronousLoadPriority(doc);
 442                     if (p >= 0) {
 443                         // load asynchronously
 444                         setDocument(doc);
 445                         synchronized(this) {
 446                             pageLoader = new PageLoader(doc, in, loaded, page);
 447                             pageLoader.execute();
 448                         }
 449                         return;
 450                     }
 451                     read(in, doc);
 452                     setDocument(doc);
 453                     reloaded = true;
 454                 }
 455             } else {
 456                 // we may need to cancel background loading
 457                 if (pageLoader != null) {
 458                     pageLoader.cancel(true);
 459                 }
 460 
 461                 // Do everything in a background thread.
 462                 // Model initialization is deferred to that thread, too.
 463                 pageLoader = new PageLoader(null, null, loaded, page);
 464                 pageLoader.execute();
 465                 return;
 466             }
 467         }
 468         final String reference = page.getRef();
 469         if (reference != null) {
 470             if (!reloaded) {
 471                 scrollToReference(reference);
 472             }
 473             else {
 474                 // Have to scroll after painted.
 475                 SwingUtilities.invokeLater(new Runnable() {
 476                     public void run() {
 477                         scrollToReference(reference);
 478                     }
 479                 });
 480             }
 481             getDocument().putProperty(Document.StreamDescriptionProperty, page);
 482         }
 483         firePropertyChange("page", loaded, page);
 484     }
 485 
 486     /**
 487      * Create model and initialize document properties from page properties.
 488      */
 489     private Document initializeModel(EditorKit kit, URL page) {
 490         Document doc = kit.createDefaultDocument();
 491         if (pageProperties != null) {
 492             // transfer properties discovered in stream to the
 493             // document property collection.
 494             for (Enumeration<String> e = pageProperties.keys(); e.hasMoreElements() ;) {
 495                 String key = e.nextElement();
 496                 doc.putProperty(key, pageProperties.get(key));
 497             }
 498             pageProperties.clear();
 499         }
 500         if (doc.getProperty(Document.StreamDescriptionProperty) == null) {
 501             doc.putProperty(Document.StreamDescriptionProperty, page);
 502         }
 503         return doc;
 504     }
 505 
 506     /**
 507      * Return load priority for the document or -1 if priority not supported.
 508      */
 509     private int getAsynchronousLoadPriority(Document doc) {
 510         return (doc instanceof AbstractDocument ?
 511             ((AbstractDocument) doc).getAsynchronousLoadPriority() : -1);
 512     }
 513 
 514     /**
 515      * This method initializes from a stream.  If the kit is
 516      * set to be of type <code>HTMLEditorKit</code>, and the
 517      * <code>desc</code> parameter is an <code>HTMLDocument</code>,
 518      * then it invokes the <code>HTMLEditorKit</code> to initiate
 519      * the read. Otherwise it calls the superclass
 520      * method which loads the model as plain text.
 521      *
 522      * @param in the stream from which to read
 523      * @param desc an object describing the stream
 524      * @exception IOException as thrown by the stream being
 525      *          used to initialize
 526      * @see JTextComponent#read
 527      * @see #setDocument
 528      */
 529     public void read(InputStream in, Object desc) throws IOException {
 530 
 531         if (desc instanceof HTMLDocument &&
 532             kit instanceof HTMLEditorKit) {
 533             HTMLDocument hdoc = (HTMLDocument) desc;
 534             setDocument(hdoc);
 535             read(in, hdoc);
 536         } else {
 537             String charset = (String) getClientProperty("charset");
 538             Reader r = (charset != null) ? new InputStreamReader(in, charset) :
 539                 new InputStreamReader(in);
 540             super.read(r, desc);
 541         }
 542     }
 543 
 544 
 545     /**
 546      * This method invokes the <code>EditorKit</code> to initiate a
 547      * read.  In the case where a <code>ChangedCharSetException</code>
 548      * is thrown this exception will contain the new CharSet.
 549      * Therefore the <code>read</code> operation
 550      * is then restarted after building a new Reader with the new charset.
 551      *
 552      * @param in the inputstream to use
 553      * @param doc the document to load
 554      *
 555      */
 556     void read(InputStream in, Document doc) throws IOException {
 557         if (! Boolean.TRUE.equals(doc.getProperty("IgnoreCharsetDirective"))) {
 558             final int READ_LIMIT = 1024 * 10;
 559             in = new BufferedInputStream(in, READ_LIMIT);
 560             in.mark(READ_LIMIT);
 561         }
 562         try {
 563             String charset = (String) getClientProperty("charset");
 564             Reader r = (charset != null) ? new InputStreamReader(in, charset) :
 565                 new InputStreamReader(in);
 566             kit.read(r, doc, 0);
 567         } catch (BadLocationException e) {
 568             throw new IOException(e.getMessage());
 569         } catch (ChangedCharSetException changedCharSetException) {
 570             String charSetSpec = changedCharSetException.getCharSetSpec();
 571             if (changedCharSetException.keyEqualsCharSet()) {
 572                 putClientProperty("charset", charSetSpec);
 573             } else {
 574                 setCharsetFromContentTypeParameters(charSetSpec);
 575             }
 576             try {
 577                 in.reset();
 578             } catch (IOException exception) {
 579                 //mark was invalidated
 580                 in.close();
 581                 URL url = (URL)doc.getProperty(Document.StreamDescriptionProperty);
 582                 if (url != null) {
 583                     URLConnection conn = url.openConnection();
 584                     in = conn.getInputStream();
 585                 } else {
 586                     //there is nothing we can do to recover stream
 587                     throw changedCharSetException;
 588                 }
 589             }
 590             try {
 591                 doc.remove(0, doc.getLength());
 592             } catch (BadLocationException e) {}
 593             doc.putProperty("IgnoreCharsetDirective", Boolean.valueOf(true));
 594             read(in, doc);
 595         }
 596     }
 597 
 598 
 599     /**
 600      * Loads a stream into the text document model.
 601      */
 602     class PageLoader extends SwingWorker<URL, Object> {
 603 
 604         /**
 605          * Construct an asynchronous page loader.
 606          */
 607         PageLoader(Document doc, InputStream in, URL old, URL page) {
 608             this.in = in;
 609             this.old = old;
 610             this.page = page;
 611             this.doc = doc;
 612         }
 613 
 614         /**
 615          * Try to load the document, then scroll the view
 616          * to the reference (if specified).  When done, fire
 617          * a page property change event.
 618          */
 619         protected URL doInBackground() {
 620             boolean pageLoaded = false;
 621             try {
 622                 if (in == null) {
 623                     in = getStream(page);
 624                     if (kit == null) {
 625                         // We received document of unknown content type.
 626                         UIManager.getLookAndFeel().
 627                                 provideErrorFeedback(JEditorPane.this);
 628                         return old;
 629                     }
 630                 }
 631 
 632                 if (doc == null) {
 633                     try {
 634                         SwingUtilities.invokeAndWait(new Runnable() {
 635                             public void run() {
 636                                 doc = initializeModel(kit, page);
 637                                 setDocument(doc);
 638                             }
 639                         });
 640                     } catch (InvocationTargetException ex) {
 641                         UIManager.getLookAndFeel().provideErrorFeedback(
 642                                                             JEditorPane.this);
 643                         return old;
 644                     } catch (InterruptedException ex) {
 645                         UIManager.getLookAndFeel().provideErrorFeedback(
 646                                                             JEditorPane.this);
 647                         return old;
 648                     }
 649                 }
 650 
 651                 read(in, doc);
 652                 URL page = (URL) doc.getProperty(Document.StreamDescriptionProperty);
 653                 String reference = page.getRef();
 654                 if (reference != null) {
 655                     // scroll the page if necessary, but do it on the
 656                     // event thread... that is the only guarantee that
 657                     // modelToView can be safely called.
 658                     Runnable callScrollToReference = new Runnable() {
 659                         public void run() {
 660                             URL u = (URL) getDocument().getProperty
 661                                 (Document.StreamDescriptionProperty);
 662                             String ref = u.getRef();
 663                             scrollToReference(ref);
 664                         }
 665                     };
 666                     SwingUtilities.invokeLater(callScrollToReference);
 667                 }
 668                 pageLoaded = true;
 669             } catch (IOException ioe) {
 670                 UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
 671             } finally {
 672                 if (pageLoaded) {
 673                     SwingUtilities.invokeLater(new Runnable() {
 674                         public void run() {
 675                             JEditorPane.this.firePropertyChange("page", old, page);
 676                         }
 677                     });
 678                 }
 679             }
 680             return (pageLoaded ? page : old);
 681         }
 682 
 683         /**
 684          * The stream to load the document with
 685          */
 686         InputStream in;
 687 
 688         /**
 689          * URL of the old page that was replaced (for the property change event)
 690          */
 691         URL old;
 692 
 693         /**
 694          * URL of the page being loaded (for the property change event)
 695          */
 696         URL page;
 697 
 698         /**
 699          * The Document instance to load into. This is cached in case a
 700          * new Document is created between the time the thread this is created
 701          * and run.
 702          */
 703         Document doc;
 704     }
 705 
 706     /**
 707      * Fetches a stream for the given URL, which is about to
 708      * be loaded by the <code>setPage</code> method.  By
 709      * default, this simply opens the URL and returns the
 710      * stream.  This can be reimplemented to do useful things
 711      * like fetch the stream from a cache, monitor the progress
 712      * of the stream, etc.
 713      * <p>
 714      * This method is expected to have the the side effect of
 715      * establishing the content type, and therefore setting the
 716      * appropriate <code>EditorKit</code> to use for loading the stream.
 717      * <p>
 718      * If this the stream was an http connection, redirects
 719      * will be followed and the resulting URL will be set as
 720      * the <code>Document.StreamDescriptionProperty</code> so that relative
 721      * URL's can be properly resolved.
 722      *
 723      * @param page  the URL of the page
 724      */
 725     protected InputStream getStream(URL page) throws IOException {
 726         final URLConnection conn = page.openConnection();
 727         if (conn instanceof HttpURLConnection) {
 728             HttpURLConnection hconn = (HttpURLConnection) conn;
 729             hconn.setInstanceFollowRedirects(false);
 730             Object postData = getPostData();
 731             if (postData != null) {
 732                 handlePostData(hconn, postData);
 733             }
 734             int response = hconn.getResponseCode();
 735             boolean redirect = (response >= 300 && response <= 399);
 736 
 737             /*
 738              * In the case of a redirect, we want to actually change the URL
 739              * that was input to the new, redirected URL
 740              */
 741             if (redirect) {
 742                 String loc = conn.getHeaderField("Location");
 743                 if (loc.startsWith("http", 0)) {
 744                     page = new URL(loc);
 745                 } else {
 746                     page = new URL(page, loc);
 747                 }
 748                 return getStream(page);
 749             }
 750         }
 751 
 752         // Connection properties handler should be forced to run on EDT,
 753         // as it instantiates the EditorKit.
 754         if (SwingUtilities.isEventDispatchThread()) {
 755             handleConnectionProperties(conn);
 756         } else {
 757             try {
 758                 SwingUtilities.invokeAndWait(new Runnable() {
 759                     public void run() {
 760                         handleConnectionProperties(conn);
 761                     }
 762                 });
 763             } catch (InterruptedException e) {
 764                 throw new RuntimeException(e);
 765             } catch (InvocationTargetException e) {
 766                 throw new RuntimeException(e);
 767             }
 768         }
 769         return conn.getInputStream();
 770     }
 771 
 772     /**
 773      * Handle URL connection properties (most notably, content type).
 774      */
 775     private void handleConnectionProperties(URLConnection conn) {
 776         if (pageProperties == null) {
 777             pageProperties = new Hashtable<String, Object>();
 778         }
 779         String type = conn.getContentType();
 780         if (type != null) {
 781             setContentType(type);
 782             pageProperties.put("content-type", type);
 783         }
 784         pageProperties.put(Document.StreamDescriptionProperty, conn.getURL());
 785         String enc = conn.getContentEncoding();
 786         if (enc != null) {
 787             pageProperties.put("content-encoding", enc);
 788         }
 789     }
 790 
 791     private Object getPostData() {
 792         return getDocument().getProperty(PostDataProperty);
 793     }
 794 
 795     private void handlePostData(HttpURLConnection conn, Object postData)
 796                                                             throws IOException {
 797         conn.setDoOutput(true);
 798         DataOutputStream os = null;
 799         try {
 800             conn.setRequestProperty("Content-Type",
 801                     "application/x-www-form-urlencoded");
 802             os = new DataOutputStream(conn.getOutputStream());
 803             os.writeBytes((String) postData);
 804         } finally {
 805             if (os != null) {
 806                 os.close();
 807             }
 808         }
 809     }
 810 
 811 
 812     /**
 813      * Scrolls the view to the given reference location
 814      * (that is, the value returned by the <code>UL.getRef</code>
 815      * method for the URL being displayed).  By default, this
 816      * method only knows how to locate a reference in an
 817      * HTMLDocument.  The implementation calls the
 818      * <code>scrollRectToVisible</code> method to
 819      * accomplish the actual scrolling.  If scrolling to a
 820      * reference location is needed for document types other
 821      * than HTML, this method should be reimplemented.
 822      * This method will have no effect if the component
 823      * is not visible.
 824      *
 825      * @param reference the named location to scroll to
 826      */
 827     public void scrollToReference(String reference) {
 828         Document d = getDocument();
 829         if (d instanceof HTMLDocument) {
 830             HTMLDocument doc = (HTMLDocument) d;
 831             HTMLDocument.Iterator iter = doc.getIterator(HTML.Tag.A);
 832             for (; iter.isValid(); iter.next()) {
 833                 AttributeSet a = iter.getAttributes();
 834                 String nm = (String) a.getAttribute(HTML.Attribute.NAME);
 835                 if ((nm != null) && nm.equals(reference)) {
 836                     // found a matching reference in the document.
 837                     try {
 838                         int pos = iter.getStartOffset();
 839                         Rectangle r = modelToView(pos);
 840                         if (r != null) {
 841                             // the view is visible, scroll it to the
 842                             // center of the current visible area.
 843                             Rectangle vis = getVisibleRect();
 844                             //r.y -= (vis.height / 2);
 845                             r.height = vis.height;
 846                             scrollRectToVisible(r);
 847                             setCaretPosition(pos);
 848                         }
 849                     } catch (BadLocationException ble) {
 850                         UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
 851                     }
 852                 }
 853             }
 854         }
 855     }
 856 
 857     /**
 858      * Gets the current URL being displayed.  If a URL was
 859      * not specified in the creation of the document, this
 860      * will return <code>null</code>, and relative URL's will not be
 861      * resolved.
 862      *
 863      * @return the URL, or <code>null</code> if none
 864      */
 865     public URL getPage() {
 866         return (URL) getDocument().getProperty(Document.StreamDescriptionProperty);
 867     }
 868 
 869     /**
 870      * Sets the current URL being displayed.
 871      *
 872      * @param url the URL for display
 873      * @exception IOException for a <code>null</code> or invalid URL
 874      *          specification
 875      */
 876     public void setPage(String url) throws IOException {
 877         if (url == null) {
 878             throw new IOException("invalid url");
 879         }
 880         URL page = new URL(url);
 881         setPage(page);
 882     }
 883 
 884     /**
 885      * Gets the class ID for the UI.
 886      *
 887      * @return the string "EditorPaneUI"
 888      * @see JComponent#getUIClassID
 889      * @see UIDefaults#getUI
 890      */
 891     @BeanProperty(bound = false)
 892     public String getUIClassID() {
 893         return uiClassID;
 894     }
 895 
 896     /**
 897      * Creates the default editor kit (<code>PlainEditorKit</code>) for when
 898      * the component is first created.
 899      *
 900      * @return the editor kit
 901      */
 902     protected EditorKit createDefaultEditorKit() {
 903         return new PlainEditorKit();
 904     }
 905 
 906     /**
 907      * Fetches the currently installed kit for handling content.
 908      * <code>createDefaultEditorKit</code> is called to set up a default
 909      * if necessary.
 910      *
 911      * @return the editor kit
 912      */
 913     public EditorKit getEditorKit() {
 914         if (kit == null) {
 915             kit = createDefaultEditorKit();
 916             isUserSetEditorKit = false;
 917         }
 918         return kit;
 919     }
 920 
 921     /**
 922      * Gets the type of content that this editor
 923      * is currently set to deal with.  This is
 924      * defined to be the type associated with the
 925      * currently installed <code>EditorKit</code>.
 926      *
 927      * @return the content type, <code>null</code> if no editor kit set
 928      */
 929     public final String getContentType() {
 930         return (kit != null) ? kit.getContentType() : null;
 931     }
 932 
 933     /**
 934      * Sets the type of content that this editor
 935      * handles.  This calls <code>getEditorKitForContentType</code>,
 936      * and then <code>setEditorKit</code> if an editor kit can
 937      * be successfully located.  This is mostly convenience method
 938      * that can be used as an alternative to calling
 939      * <code>setEditorKit</code> directly.
 940      * <p>
 941      * If there is a charset definition specified as a parameter
 942      * of the content type specification, it will be used when
 943      * loading input streams using the associated <code>EditorKit</code>.
 944      * For example if the type is specified as
 945      * <code>text/html; charset=EUC-JP</code> the content
 946      * will be loaded using the <code>EditorKit</code> registered for
 947      * <code>text/html</code> and the Reader provided to
 948      * the <code>EditorKit</code> to load unicode into the document will
 949      * use the <code>EUC-JP</code> charset for translating
 950      * to unicode.  If the type is not recognized, the content
 951      * will be loaded using the <code>EditorKit</code> registered
 952      * for plain text, <code>text/plain</code>.
 953      *
 954      * @param type the non-<code>null</code> mime type for the content editing
 955      *   support
 956      * @see #getContentType
 957      * @throws NullPointerException if the <code>type</code> parameter
 958      *          is <code>null</code>
 959      */
 960     @BeanProperty(bound = false, description
 961             = "the type of content")
 962     public final void setContentType(String type) {
 963         // The type could have optional info is part of it,
 964         // for example some charset info.  We need to strip that
 965         // of and save it.
 966         int parm = type.indexOf(';');
 967         if (parm > -1) {
 968             // Save the paramList.
 969             String paramList = type.substring(parm);
 970             // update the content type string.
 971             type = type.substring(0, parm).trim();
 972             if (type.toLowerCase().startsWith("text/")) {
 973                 setCharsetFromContentTypeParameters(paramList);
 974             }
 975         }
 976         if ((kit == null) || (! type.equals(kit.getContentType()))
 977                 || !isUserSetEditorKit) {
 978             EditorKit k = getEditorKitForContentType(type);
 979             if (k != null && k != kit) {
 980                 setEditorKit(k);
 981                 isUserSetEditorKit = false;
 982             }
 983         }
 984 
 985     }
 986 
 987     /**
 988      * This method gets the charset information specified as part
 989      * of the content type in the http header information.
 990      */
 991     private void setCharsetFromContentTypeParameters(String paramlist) {
 992         String charset;
 993         try {
 994             // paramlist is handed to us with a leading ';', strip it.
 995             int semi = paramlist.indexOf(';');
 996             if (semi > -1 && semi < paramlist.length()-1) {
 997                 paramlist = paramlist.substring(semi + 1);
 998             }
 999 
1000             if (paramlist.length() > 0) {
1001                 // parse the paramlist into attr-value pairs & get the
1002                 // charset pair's value
1003                 HeaderParser hdrParser = new HeaderParser(paramlist);
1004                 charset = hdrParser.findValue("charset");
1005                 if (charset != null) {
1006                     putClientProperty("charset", charset);
1007                 }
1008             }
1009         }
1010         catch (IndexOutOfBoundsException e) {
1011             // malformed parameter list, use charset we have
1012         }
1013         catch (NullPointerException e) {
1014             // malformed parameter list, use charset we have
1015         }
1016         catch (Exception e) {
1017             // malformed parameter list, use charset we have; but complain
1018             System.err.println("JEditorPane.getCharsetFromContentTypeParameters failed on: " + paramlist);
1019             e.printStackTrace();
1020         }
1021     }
1022 
1023 
1024     /**
1025      * Sets the currently installed kit for handling
1026      * content.  This is the bound property that
1027      * establishes the content type of the editor.
1028      * Any old kit is first deinstalled, then if kit is
1029      * non-<code>null</code>,
1030      * the new kit is installed, and a default document created for it.
1031      * A <code>PropertyChange</code> event ("editorKit") is always fired when
1032      * <code>setEditorKit</code> is called.
1033      * <p>
1034      * <em>NOTE: This has the side effect of changing the model,
1035      * because the <code>EditorKit</code> is the source of how a
1036      * particular type
1037      * of content is modeled.  This method will cause <code>setDocument</code>
1038      * to be called on behalf of the caller to ensure integrity
1039      * of the internal state.</em>
1040      *
1041      * @param kit the desired editor behavior
1042      * @see #getEditorKit
1043      */
1044     @BeanProperty(expert = true, description
1045             = "the currently installed kit for handling content")
1046     public void setEditorKit(EditorKit kit) {
1047         EditorKit old = this.kit;
1048         isUserSetEditorKit = true;
1049         if (old != null) {
1050             old.deinstall(this);
1051         }
1052         this.kit = kit;
1053         if (this.kit != null) {
1054             this.kit.install(this);
1055             setDocument(this.kit.createDefaultDocument());
1056         }
1057         firePropertyChange("editorKit", old, kit);
1058     }
1059 
1060     /**
1061      * Fetches the editor kit to use for the given type
1062      * of content.  This is called when a type is requested
1063      * that doesn't match the currently installed type.
1064      * If the component doesn't have an <code>EditorKit</code> registered
1065      * for the given type, it will try to create an
1066      * <code>EditorKit</code> from the default <code>EditorKit</code> registry.
1067      * If that fails, a <code>PlainEditorKit</code> is used on the
1068      * assumption that all text documents can be represented
1069      * as plain text.
1070      * <p>
1071      * This method can be reimplemented to use some
1072      * other kind of type registry.  This can
1073      * be reimplemented to use the Java Activation
1074      * Framework, for example.
1075      *
1076      * @param type the non-<code>null</code> content type
1077      * @return the editor kit
1078      */
1079     public EditorKit getEditorKitForContentType(String type) {
1080         if (typeHandlers == null) {
1081             typeHandlers = new Hashtable<String, EditorKit>(3);
1082         }
1083         EditorKit k = typeHandlers.get(type);
1084         if (k == null) {
1085             k = createEditorKitForContentType(type);
1086             if (k != null) {
1087                 setEditorKitForContentType(type, k);
1088             }
1089         }
1090         if (k == null) {
1091             k = createDefaultEditorKit();
1092         }
1093         return k;
1094     }
1095 
1096     /**
1097      * Directly sets the editor kit to use for the given type.  A
1098      * look-and-feel implementation might use this in conjunction
1099      * with <code>createEditorKitForContentType</code> to install handlers for
1100      * content types with a look-and-feel bias.
1101      *
1102      * @param type the non-<code>null</code> content type
1103      * @param k the editor kit to be set
1104      */
1105     public void setEditorKitForContentType(String type, EditorKit k) {
1106         if (typeHandlers == null) {
1107             typeHandlers = new Hashtable<String, EditorKit>(3);
1108         }
1109         typeHandlers.put(type, k);
1110     }
1111 
1112     /**
1113      * Replaces the currently selected content with new content
1114      * represented by the given string.  If there is no selection
1115      * this amounts to an insert of the given text.  If there
1116      * is no replacement text (i.e. the content string is empty
1117      * or <code>null</code>) this amounts to a removal of the
1118      * current selection.  The replacement text will have the
1119      * attributes currently defined for input.  If the component is not
1120      * editable, beep and return.
1121      *
1122      * @param content  the content to replace the selection with.  This
1123      *   value can be <code>null</code>
1124      */
1125     @Override
1126     public void replaceSelection(String content) {
1127         if (! isEditable()) {
1128             UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1129             return;
1130         }
1131         EditorKit kit = getEditorKit();
1132         if(kit instanceof StyledEditorKit) {
1133             try {
1134                 Document doc = getDocument();
1135                 Caret caret = getCaret();
1136                 boolean composedTextSaved = saveComposedText(caret.getDot());
1137                 int p0 = Math.min(caret.getDot(), caret.getMark());
1138                 int p1 = Math.max(caret.getDot(), caret.getMark());
1139                 if (doc instanceof AbstractDocument) {
1140                     ((AbstractDocument)doc).replace(p0, p1 - p0, content,
1141                               ((StyledEditorKit)kit).getInputAttributes());
1142                 }
1143                 else {
1144                     if (p0 != p1) {
1145                         doc.remove(p0, p1 - p0);
1146                     }
1147                     if (content != null && content.length() > 0) {
1148                         doc.insertString(p0, content, ((StyledEditorKit)kit).
1149                                          getInputAttributes());
1150                     }
1151                 }
1152                 if (composedTextSaved) {
1153                     restoreComposedText();
1154                 }
1155             } catch (BadLocationException e) {
1156                 UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1157             }
1158         }
1159         else {
1160             super.replaceSelection(content);
1161         }
1162     }
1163 
1164     /**
1165      * Creates a handler for the given type from the default registry
1166      * of editor kits.  The registry is created if necessary.  If the
1167      * registered class has not yet been loaded, an attempt
1168      * is made to dynamically load the prototype of the kit for the
1169      * given type.  If the type was registered with a <code>ClassLoader</code>,
1170      * that <code>ClassLoader</code> will be used to load the prototype.
1171      * If there was no registered <code>ClassLoader</code>,
1172      * <code>Class.forName</code> will be used to load the prototype.
1173      * <p>
1174      * Once a prototype <code>EditorKit</code> instance is successfully
1175      * located, it is cloned and the clone is returned.
1176      *
1177      * @param type the content type
1178      * @return the editor kit, or <code>null</code> if there is nothing
1179      *   registered for the given type
1180      */
1181     public static EditorKit createEditorKitForContentType(String type) {
1182         Hashtable<String, EditorKit> kitRegistry = getKitRegisty();
1183         EditorKit k = kitRegistry.get(type);
1184         if (k == null) {
1185             // try to dynamically load the support
1186             String classname = getKitTypeRegistry().get(type);
1187             ClassLoader loader = getKitLoaderRegistry().get(type);
1188             try {
1189                 Class<?> c;
1190                 if (loader != null) {
1191                     ReflectUtil.checkPackageAccess(classname);
1192                     c = loader.loadClass(classname);
1193                 } else {
1194                     // Will only happen if developer has invoked
1195                     // registerEditorKitForContentType(type, class, null).
1196                     c = SwingUtilities.loadSystemClass(classname);
1197                 }
1198                 k = (EditorKit) c.newInstance();
1199                 kitRegistry.put(type, k);
1200             } catch (Throwable e) {
1201                 k = null;
1202             }
1203         }
1204 
1205         // create a copy of the prototype or null if there
1206         // is no prototype.
1207         if (k != null) {
1208             return (EditorKit) k.clone();
1209         }
1210         return null;
1211     }
1212 
1213     /**
1214      * Establishes the default bindings of <code>type</code> to
1215      * <code>classname</code>.
1216      * The class will be dynamically loaded later when actually
1217      * needed, and can be safely changed before attempted uses
1218      * to avoid loading unwanted classes.  The prototype
1219      * <code>EditorKit</code> will be loaded with <code>Class.forName</code>
1220      * when registered with this method.
1221      *
1222      * @param type the non-<code>null</code> content type
1223      * @param classname the class to load later
1224      */
1225     public static void registerEditorKitForContentType(String type, String classname) {
1226         registerEditorKitForContentType(type, classname,Thread.currentThread().
1227                                         getContextClassLoader());
1228     }
1229 
1230     /**
1231      * Establishes the default bindings of <code>type</code> to
1232      * <code>classname</code>.
1233      * The class will be dynamically loaded later when actually
1234      * needed using the given <code>ClassLoader</code>,
1235      * and can be safely changed
1236      * before attempted uses to avoid loading unwanted classes.
1237      *
1238      * @param type the non-<code>null</code> content type
1239      * @param classname the class to load later
1240      * @param loader the <code>ClassLoader</code> to use to load the name
1241      */
1242     public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) {
1243         getKitTypeRegistry().put(type, classname);
1244         getKitLoaderRegistry().put(type, loader);
1245         getKitRegisty().remove(type);
1246     }
1247 
1248     /**
1249      * Returns the currently registered {@code EditorKit} class name for the
1250      * type {@code type}.
1251      *
1252      * @param type  the non-{@code null} content type
1253      * @return a {@code String} containing the {@code EditorKit} class name
1254      *         for {@code type}
1255      * @since 1.3
1256      */
1257     public static String getEditorKitClassNameForContentType(String type) {
1258         return getKitTypeRegistry().get(type);
1259     }
1260 
1261     private static Hashtable<String, String> getKitTypeRegistry() {
1262         loadDefaultKitsIfNecessary();
1263         @SuppressWarnings("unchecked")
1264         Hashtable<String, String> tmp =
1265             (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
1266         return tmp;
1267     }
1268 
1269     private static Hashtable<String, ClassLoader> getKitLoaderRegistry() {
1270         loadDefaultKitsIfNecessary();
1271         @SuppressWarnings("unchecked")
1272         Hashtable<String, ClassLoader> tmp =
1273             (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
1274         return tmp;
1275     }
1276 
1277     private static Hashtable<String, EditorKit> getKitRegisty() {
1278         @SuppressWarnings("unchecked")
1279         Hashtable<String, EditorKit> ht =
1280             (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
1281         if (ht == null) {
1282             ht = new Hashtable<>(3);
1283             SwingUtilities.appContextPut(kitRegistryKey, ht);
1284         }
1285         return ht;
1286     }
1287 
1288     /**
1289      * This is invoked every time the registries are accessed. Loading
1290      * is done this way instead of via a static as the static is only
1291      * called once when running in plugin resulting in the entries only
1292      * appearing in the first applet.
1293      */
1294     private static void loadDefaultKitsIfNecessary() {
1295         if (SwingUtilities.appContextGet(kitTypeRegistryKey) == null) {
1296             synchronized(defaultEditorKitMap) {
1297                 if (defaultEditorKitMap.size() == 0) {
1298                     defaultEditorKitMap.put("text/plain",
1299                                             "javax.swing.JEditorPane$PlainEditorKit");
1300                     defaultEditorKitMap.put("text/html",
1301                                             "javax.swing.text.html.HTMLEditorKit");
1302                     defaultEditorKitMap.put("text/rtf",
1303                                             "javax.swing.text.rtf.RTFEditorKit");
1304                     defaultEditorKitMap.put("application/rtf",
1305                                             "javax.swing.text.rtf.RTFEditorKit");
1306                 }
1307             }
1308             Hashtable<Object, Object> ht = new Hashtable<>();
1309             SwingUtilities.appContextPut(kitTypeRegistryKey, ht);
1310             ht = new Hashtable<>();
1311             SwingUtilities.appContextPut(kitLoaderRegistryKey, ht);
1312             for (String key : defaultEditorKitMap.keySet()) {
1313                 registerEditorKitForContentType(key,defaultEditorKitMap.get(key));
1314             }
1315 
1316         }
1317     }
1318 
1319     // --- java.awt.Component methods --------------------------
1320 
1321     /**
1322      * Returns the preferred size for the <code>JEditorPane</code>.
1323      * The preferred size for <code>JEditorPane</code> is slightly altered
1324      * from the preferred size of the superclass.  If the size
1325      * of the viewport has become smaller than the minimum size
1326      * of the component, the scrollable definition for tracking
1327      * width or height will turn to false.  The default viewport
1328      * layout will give the preferred size, and that is not desired
1329      * in the case where the scrollable is tracking.  In that case
1330      * the <em>normal</em> preferred size is adjusted to the
1331      * minimum size.  This allows things like HTML tables to
1332      * shrink down to their minimum size and then be laid out at
1333      * their minimum size, refusing to shrink any further.
1334      *
1335      * @return a <code>Dimension</code> containing the preferred size
1336      */
1337     public Dimension getPreferredSize() {
1338         Dimension d = super.getPreferredSize();
1339         Container parent = SwingUtilities.getUnwrappedParent(this);
1340         if (parent instanceof JViewport) {
1341             JViewport port = (JViewport) parent;
1342             TextUI ui = getUI();
1343             int prefWidth = d.width;
1344             int prefHeight = d.height;
1345             if (! getScrollableTracksViewportWidth()) {
1346                 int w = port.getWidth();
1347                 Dimension min = ui.getMinimumSize(this);
1348                 if (w != 0 && w < min.width) {
1349                     // Only adjust to min if we have a valid size
1350                     prefWidth = min.width;
1351                 }
1352             }
1353             if (! getScrollableTracksViewportHeight()) {
1354                 int h = port.getHeight();
1355                 Dimension min = ui.getMinimumSize(this);
1356                 if (h != 0 && h < min.height) {
1357                     // Only adjust to min if we have a valid size
1358                     prefHeight = min.height;
1359                 }
1360             }
1361             if (prefWidth != d.width || prefHeight != d.height) {
1362                 d = new Dimension(prefWidth, prefHeight);
1363             }
1364         }
1365         return d;
1366     }
1367 
1368     // --- JTextComponent methods -----------------------------
1369 
1370     /**
1371      * Sets the text of this <code>TextComponent</code> to the specified
1372      * content,
1373      * which is expected to be in the format of the content type of
1374      * this editor.  For example, if the type is set to <code>text/html</code>
1375      * the string should be specified in terms of HTML.
1376      * <p>
1377      * This is implemented to remove the contents of the current document,
1378      * and replace them by parsing the given string using the current
1379      * <code>EditorKit</code>.  This gives the semantics of the
1380      * superclass by not changing
1381      * out the model, while supporting the content type currently set on
1382      * this component.  The assumption is that the previous content is
1383      * relatively
1384      * small, and that the previous content doesn't have side effects.
1385      * Both of those assumptions can be violated and cause undesirable results.
1386      * To avoid this, create a new document,
1387      * <code>getEditorKit().createDefaultDocument()</code>, and replace the
1388      * existing <code>Document</code> with the new one. You are then assured the
1389      * previous <code>Document</code> won't have any lingering state.
1390      * <ol>
1391      * <li>
1392      * Leaving the existing model in place means that the old view will be
1393      * torn down, and a new view created, where replacing the document would
1394      * avoid the tear down of the old view.
1395      * <li>
1396      * Some formats (such as HTML) can install things into the document that
1397      * can influence future contents.  HTML can have style information embedded
1398      * that would influence the next content installed unexpectedly.
1399      * </ol>
1400      * <p>
1401      * An alternative way to load this component with a string would be to
1402      * create a StringReader and call the read method.  In this case the model
1403      * would be replaced after it was initialized with the contents of the
1404      * string.
1405      *
1406      * @param t the new text to be set; if <code>null</code> the old
1407      *    text will be deleted
1408      * @see #getText
1409      */
1410     @BeanProperty(bound = false, description
1411             = "the text of this component")
1412     public void setText(String t) {
1413         try {
1414             Document doc = getDocument();
1415             doc.remove(0, doc.getLength());
1416             if (t == null || t.equals("")) {
1417                 return;
1418             }
1419             Reader r = new StringReader(t);
1420             EditorKit kit = getEditorKit();
1421             kit.read(r, doc, 0);
1422         } catch (IOException ioe) {
1423             UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1424         } catch (BadLocationException ble) {
1425             UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1426         }
1427     }
1428 
1429     /**
1430      * Returns the text contained in this <code>TextComponent</code>
1431      * in terms of the
1432      * content type of this editor.  If an exception is thrown while
1433      * attempting to retrieve the text, <code>null</code> will be returned.
1434      * This is implemented to call <code>JTextComponent.write</code> with
1435      * a <code>StringWriter</code>.
1436      *
1437      * @return the text
1438      * @see #setText
1439      */
1440     public String getText() {
1441         String txt;
1442         try {
1443             StringWriter buf = new StringWriter();
1444             write(buf);
1445             txt = buf.toString();
1446         } catch (IOException ioe) {
1447             txt = null;
1448         }
1449         return txt;
1450     }
1451 
1452     // --- Scrollable  ----------------------------------------
1453 
1454     /**
1455      * Returns true if a viewport should always force the width of this
1456      * <code>Scrollable</code> to match the width of the viewport.
1457      *
1458      * @return true if a viewport should force the Scrollables width to
1459      * match its own, false otherwise
1460      */
1461     @BeanProperty(bound = false)
1462     public boolean getScrollableTracksViewportWidth() {
1463         Container parent = SwingUtilities.getUnwrappedParent(this);
1464         if (parent instanceof JViewport) {
1465             JViewport port = (JViewport) parent;
1466             TextUI ui = getUI();
1467             int w = port.getWidth();
1468             Dimension min = ui.getMinimumSize(this);
1469             Dimension max = ui.getMaximumSize(this);
1470             if ((w >= min.width) && (w <= max.width)) {
1471                 return true;
1472             }
1473         }
1474         return false;
1475     }
1476 
1477     /**
1478      * Returns true if a viewport should always force the height of this
1479      * <code>Scrollable</code> to match the height of the viewport.
1480      *
1481      * @return true if a viewport should force the
1482      *          <code>Scrollable</code>'s height to match its own,
1483      *          false otherwise
1484      */
1485     @BeanProperty(bound = false)
1486     public boolean getScrollableTracksViewportHeight() {
1487         Container parent = SwingUtilities.getUnwrappedParent(this);
1488         if (parent instanceof JViewport) {
1489             JViewport port = (JViewport) parent;
1490             TextUI ui = getUI();
1491             int h = port.getHeight();
1492             Dimension min = ui.getMinimumSize(this);
1493             if (h >= min.height) {
1494                 Dimension max = ui.getMaximumSize(this);
1495                 if (h <= max.height) {
1496                     return true;
1497                 }
1498             }
1499         }
1500         return false;
1501     }
1502 
1503     // --- Serialization ------------------------------------
1504 
1505     /**
1506      * See <code>readObject</code> and <code>writeObject</code> in
1507      * <code>JComponent</code> for more
1508      * information about serialization in Swing.
1509      */
1510     private void writeObject(ObjectOutputStream s) throws IOException {
1511         s.defaultWriteObject();
1512         if (getUIClassID().equals(uiClassID)) {
1513             byte count = JComponent.getWriteObjCounter(this);
1514             JComponent.setWriteObjCounter(this, --count);
1515             if (count == 0 && ui != null) {
1516                 ui.installUI(this);
1517             }
1518         }
1519     }
1520 
1521     // --- variables ---------------------------------------
1522 
1523     private SwingWorker<URL, Object> pageLoader;
1524 
1525     /**
1526      * Current content binding of the editor.
1527      */
1528     private EditorKit kit;
1529     private boolean isUserSetEditorKit;
1530 
1531     private Hashtable<String, Object> pageProperties;
1532 
1533     /** Should be kept in sync with javax.swing.text.html.FormView counterpart. */
1534     final static String PostDataProperty = "javax.swing.JEditorPane.postdata";
1535 
1536     /**
1537      * Table of registered type handlers for this editor.
1538      */
1539     private Hashtable<String, EditorKit> typeHandlers;
1540 
1541     /*
1542      * Private AppContext keys for this class's static variables.
1543      */
1544     private static final Object kitRegistryKey =
1545         new StringBuffer("JEditorPane.kitRegistry");
1546     private static final Object kitTypeRegistryKey =
1547         new StringBuffer("JEditorPane.kitTypeRegistry");
1548     private static final Object kitLoaderRegistryKey =
1549         new StringBuffer("JEditorPane.kitLoaderRegistry");
1550 
1551     /**
1552      * @see #getUIClassID
1553      * @see #readObject
1554      */
1555     private static final String uiClassID = "EditorPaneUI";
1556 
1557 
1558     /**
1559      * Key for a client property used to indicate whether
1560      * <a href="http://www.w3.org/TR/CSS21/syndata.html#length-units">
1561      * w3c compliant</a> length units are used for html rendering.
1562      * <p>
1563      * By default this is not enabled; to enable
1564      * it set the client {@link #putClientProperty property} with this name
1565      * to <code>Boolean.TRUE</code>.
1566      *
1567      * @since 1.5
1568      */
1569     public static final String W3C_LENGTH_UNITS = "JEditorPane.w3cLengthUnits";
1570 
1571     /**
1572      * Key for a client property used to indicate whether
1573      * the default font and foreground color from the component are
1574      * used if a font or foreground color is not specified in the styled
1575      * text.
1576      * <p>
1577      * The default varies based on the look and feel;
1578      * to enable it set the client {@link #putClientProperty property} with
1579      * this name to <code>Boolean.TRUE</code>.
1580      *
1581      * @since 1.5
1582      */
1583     public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties";
1584 
1585     static final Map<String, String> defaultEditorKitMap = new HashMap<String, String>(0);
1586 
1587     /**
1588      * Returns a string representation of this <code>JEditorPane</code>.
1589      * This method
1590      * is intended to be used only for debugging purposes, and the
1591      * content and format of the returned string may vary between
1592      * implementations. The returned string may be empty but may not
1593      * be <code>null</code>.
1594      *
1595      * @return  a string representation of this <code>JEditorPane</code>
1596      */
1597     protected String paramString() {
1598         String kitString = (kit != null ?
1599                             kit.toString() : "");
1600         String typeHandlersString = (typeHandlers != null ?
1601                                      typeHandlers.toString() : "");
1602 
1603         return super.paramString() +
1604         ",kit=" + kitString +
1605         ",typeHandlers=" + typeHandlersString;
1606     }
1607 
1608 
1609 /////////////////
1610 // Accessibility support
1611 ////////////////
1612 
1613 
1614     /**
1615      * Gets the AccessibleContext associated with this JEditorPane.
1616      * For editor panes, the AccessibleContext takes the form of an
1617      * AccessibleJEditorPane.
1618      * A new AccessibleJEditorPane instance is created if necessary.
1619      *
1620      * @return an AccessibleJEditorPane that serves as the
1621      *         AccessibleContext of this JEditorPane
1622      */
1623     @BeanProperty(bound = false)
1624     public AccessibleContext getAccessibleContext() {
1625         if (getEditorKit() instanceof HTMLEditorKit) {
1626             if (accessibleContext == null || accessibleContext.getClass() !=
1627                     AccessibleJEditorPaneHTML.class) {
1628                 accessibleContext = new AccessibleJEditorPaneHTML();
1629             }
1630         } else if (accessibleContext == null || accessibleContext.getClass() !=
1631                        AccessibleJEditorPane.class) {
1632             accessibleContext = new AccessibleJEditorPane();
1633         }
1634         return accessibleContext;
1635     }
1636 
1637     /**
1638      * This class implements accessibility support for the
1639      * <code>JEditorPane</code> class.  It provides an implementation of the
1640      * Java Accessibility API appropriate to editor pane user-interface
1641      * elements.
1642      * <p>
1643      * <strong>Warning:</strong>
1644      * Serialized objects of this class will not be compatible with
1645      * future Swing releases. The current serialization support is
1646      * appropriate for short term storage or RMI between applications running
1647      * the same version of Swing.  As of 1.4, support for long term storage
1648      * of all JavaBeans&trade;
1649      * has been added to the <code>java.beans</code> package.
1650      * Please see {@link java.beans.XMLEncoder}.
1651      */
1652     @SuppressWarnings("serial") // Same-version serialization only
1653     protected class AccessibleJEditorPane extends AccessibleJTextComponent {
1654 
1655         /**
1656          * Gets the accessibleDescription property of this object.  If this
1657          * property isn't set, returns the content type of this
1658          * <code>JEditorPane</code> instead (e.g. "plain/text", "html/text").
1659          *
1660          * @return the localized description of the object; <code>null</code>
1661          *      if this object does not have a description
1662          *
1663          * @see #setAccessibleName
1664          */
1665         public String getAccessibleDescription() {
1666             String description = accessibleDescription;
1667 
1668             // fallback to client property
1669             if (description == null) {
1670                 description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
1671             }
1672             if (description == null) {
1673                 description = JEditorPane.this.getContentType();
1674             }
1675             return description;
1676         }
1677 
1678         /**
1679          * Gets the state set of this object.
1680          *
1681          * @return an instance of AccessibleStateSet describing the states
1682          * of the object
1683          * @see AccessibleStateSet
1684          */
1685         public AccessibleStateSet getAccessibleStateSet() {
1686             AccessibleStateSet states = super.getAccessibleStateSet();
1687             states.add(AccessibleState.MULTI_LINE);
1688             return states;
1689         }
1690     }
1691 
1692     /**
1693      * This class provides support for <code>AccessibleHypertext</code>,
1694      * and is used in instances where the <code>EditorKit</code>
1695      * installed in this <code>JEditorPane</code> is an instance of
1696      * <code>HTMLEditorKit</code>.
1697      * <p>
1698      * <strong>Warning:</strong>
1699      * Serialized objects of this class will not be compatible with
1700      * future Swing releases. The current serialization support is
1701      * appropriate for short term storage or RMI between applications running
1702      * the same version of Swing.  As of 1.4, support for long term storage
1703      * of all JavaBeans&trade;
1704      * has been added to the <code>java.beans</code> package.
1705      * Please see {@link java.beans.XMLEncoder}.
1706      */
1707     @SuppressWarnings("serial") // Same-version serialization only
1708     protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane {
1709 
1710         private AccessibleContext accessibleContext;
1711 
1712         public AccessibleText getAccessibleText() {
1713             return new JEditorPaneAccessibleHypertextSupport();
1714         }
1715 
1716         protected AccessibleJEditorPaneHTML () {
1717             HTMLEditorKit kit = (HTMLEditorKit)JEditorPane.this.getEditorKit();
1718             accessibleContext = kit.getAccessibleContext();
1719         }
1720 
1721         /**
1722          * Returns the number of accessible children of the object.
1723          *
1724          * @return the number of accessible children of the object.
1725          */
1726         public int getAccessibleChildrenCount() {
1727             if (accessibleContext != null) {
1728                 return accessibleContext.getAccessibleChildrenCount();
1729             } else {
1730                 return 0;
1731             }
1732         }
1733 
1734         /**
1735          * Returns the specified Accessible child of the object.  The Accessible
1736          * children of an Accessible object are zero-based, so the first child
1737          * of an Accessible child is at index 0, the second child is at index 1,
1738          * and so on.
1739          *
1740          * @param i zero-based index of child
1741          * @return the Accessible child of the object
1742          * @see #getAccessibleChildrenCount
1743          */
1744         public Accessible getAccessibleChild(int i) {
1745             if (accessibleContext != null) {
1746                 return accessibleContext.getAccessibleChild(i);
1747             } else {
1748                 return null;
1749             }
1750         }
1751 
1752         /**
1753          * Returns the Accessible child, if one exists, contained at the local
1754          * coordinate Point.
1755          *
1756          * @param p The point relative to the coordinate system of this object.
1757          * @return the Accessible, if it exists, at the specified location;
1758          * otherwise null
1759          */
1760         public Accessible getAccessibleAt(Point p) {
1761             if (accessibleContext != null && p != null) {
1762                 try {
1763                     AccessibleComponent acomp =
1764                         accessibleContext.getAccessibleComponent();
1765                     if (acomp != null) {
1766                         return acomp.getAccessibleAt(p);
1767                     } else {
1768                         return null;
1769                     }
1770                 } catch (IllegalComponentStateException e) {
1771                     return null;
1772                 }
1773             } else {
1774                 return null;
1775             }
1776         }
1777     }
1778 
1779     /**
1780      * What's returned by
1781      * <code>AccessibleJEditorPaneHTML.getAccessibleText</code>.
1782      *
1783      * Provides support for <code>AccessibleHypertext</code> in case
1784      * there is an HTML document being displayed in this
1785      * <code>JEditorPane</code>.
1786      *
1787      */
1788     protected class JEditorPaneAccessibleHypertextSupport
1789     extends AccessibleJEditorPane implements AccessibleHypertext {
1790 
1791         public class HTMLLink extends AccessibleHyperlink {
1792             Element element;
1793 
1794             public HTMLLink(Element e) {
1795                 element = e;
1796             }
1797 
1798             /**
1799              * Since the document a link is associated with may have
1800              * changed, this method returns whether this Link is valid
1801              * anymore (with respect to the document it references).
1802              *
1803              * @return a flag indicating whether this link is still valid with
1804              *         respect to the AccessibleHypertext it belongs to
1805              */
1806             public boolean isValid() {
1807                 return JEditorPaneAccessibleHypertextSupport.this.linksValid;
1808             }
1809 
1810             /**
1811              * Returns the number of accessible actions available in this Link
1812              * If there are more than one, the first one is NOT considered the
1813              * "default" action of this LINK object (e.g. in an HTML imagemap).
1814              * In general, links will have only one AccessibleAction in them.
1815              *
1816              * @return the zero-based number of Actions in this object
1817              */
1818             public int getAccessibleActionCount() {
1819                 return 1;
1820             }
1821 
1822             /**
1823              * Perform the specified Action on the object
1824              *
1825              * @param i zero-based index of actions
1826              * @return true if the the action was performed; else false.
1827              * @see #getAccessibleActionCount
1828              */
1829             public boolean doAccessibleAction(int i) {
1830                 if (i == 0 && isValid() == true) {
1831                     URL u = (URL) getAccessibleActionObject(i);
1832                     if (u != null) {
1833                         HyperlinkEvent linkEvent =
1834                             new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u);
1835                         JEditorPane.this.fireHyperlinkUpdate(linkEvent);
1836                         return true;
1837                     }
1838                 }
1839                 return false;  // link invalid or i != 0
1840             }
1841 
1842             /**
1843              * Return a String description of this particular
1844              * link action.  The string returned is the text
1845              * within the document associated with the element
1846              * which contains this link.
1847              *
1848              * @param i zero-based index of the actions
1849              * @return a String description of the action
1850              * @see #getAccessibleActionCount
1851              */
1852             public String getAccessibleActionDescription(int i) {
1853                 if (i == 0 && isValid() == true) {
1854                     Document d = JEditorPane.this.getDocument();
1855                     if (d != null) {
1856                         try {
1857                             return d.getText(getStartIndex(),
1858                                              getEndIndex() - getStartIndex());
1859                         } catch (BadLocationException exception) {
1860                             return null;
1861                         }
1862                     }
1863                 }
1864                 return null;
1865             }
1866 
1867             /**
1868              * Returns a URL object that represents the link.
1869              *
1870              * @param i zero-based index of the actions
1871              * @return an URL representing the HTML link itself
1872              * @see #getAccessibleActionCount
1873              */
1874             public Object getAccessibleActionObject(int i) {
1875                 if (i == 0 && isValid() == true) {
1876                     AttributeSet as = element.getAttributes();
1877                     AttributeSet anchor =
1878                         (AttributeSet) as.getAttribute(HTML.Tag.A);
1879                     String href = (anchor != null) ?
1880                         (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
1881                     if (href != null) {
1882                         URL u;
1883                         try {
1884                             u = new URL(JEditorPane.this.getPage(), href);
1885                         } catch (MalformedURLException m) {
1886                             u = null;
1887                         }
1888                         return u;
1889                     }
1890                 }
1891                 return null;  // link invalid or i != 0
1892             }
1893 
1894             /**
1895              * Return an object that represents the link anchor,
1896              * as appropriate for that link.  E.g. from HTML:
1897              *   <a href="http://www.sun.com/access">Accessibility</a>
1898              * this method would return a String containing the text:
1899              * 'Accessibility'.
1900              *
1901              * Similarly, from this HTML:
1902              *   &lt;a HREF="#top"&gt;&lt;img src="top-hat.gif" alt="top hat"&gt;&lt;/a&gt;
1903              * this might return the object ImageIcon("top-hat.gif", "top hat");
1904              *
1905              * @param i zero-based index of the actions
1906              * @return an Object representing the hypertext anchor
1907              * @see #getAccessibleActionCount
1908              */
1909             public Object getAccessibleActionAnchor(int i) {
1910                 return getAccessibleActionDescription(i);
1911             }
1912 
1913 
1914             /**
1915              * Get the index with the hypertext document at which this
1916              * link begins
1917              *
1918              * @return index of start of link
1919              */
1920             public int getStartIndex() {
1921                 return element.getStartOffset();
1922             }
1923 
1924             /**
1925              * Get the index with the hypertext document at which this
1926              * link ends
1927              *
1928              * @return index of end of link
1929              */
1930             public int getEndIndex() {
1931                 return element.getEndOffset();
1932             }
1933         }
1934 
1935         private class LinkVector extends Vector<HTMLLink> {
1936             public int baseElementIndex(Element e) {
1937                 HTMLLink l;
1938                 for (int i = 0; i < elementCount; i++) {
1939                     l = elementAt(i);
1940                     if (l.element == e) {
1941                         return i;
1942                     }
1943                 }
1944                 return -1;
1945             }
1946         }
1947 
1948         LinkVector hyperlinks;
1949         boolean linksValid = false;
1950 
1951         /**
1952          * Build the private table mapping links to locations in the text
1953          */
1954         private void buildLinkTable() {
1955             hyperlinks.removeAllElements();
1956             Document d = JEditorPane.this.getDocument();
1957             if (d != null) {
1958                 ElementIterator ei = new ElementIterator(d);
1959                 Element e;
1960                 AttributeSet as;
1961                 AttributeSet anchor;
1962                 String href;
1963                 while ((e = ei.next()) != null) {
1964                     if (e.isLeaf()) {
1965                         as = e.getAttributes();
1966                     anchor = (AttributeSet) as.getAttribute(HTML.Tag.A);
1967                     href = (anchor != null) ?
1968                         (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
1969                         if (href != null) {
1970                             hyperlinks.addElement(new HTMLLink(e));
1971                         }
1972                     }
1973                 }
1974             }
1975             linksValid = true;
1976         }
1977 
1978         /**
1979          * Make one of these puppies
1980          */
1981         public JEditorPaneAccessibleHypertextSupport() {
1982             hyperlinks = new LinkVector();
1983             Document d = JEditorPane.this.getDocument();
1984             if (d != null) {
1985                 d.addDocumentListener(new DocumentListener() {
1986                     public void changedUpdate(DocumentEvent theEvent) {
1987                         linksValid = false;
1988                     }
1989                     public void insertUpdate(DocumentEvent theEvent) {
1990                         linksValid = false;
1991                     }
1992                     public void removeUpdate(DocumentEvent theEvent) {
1993                         linksValid = false;
1994                     }
1995                 });
1996             }
1997         }
1998 
1999         /**
2000          * Returns the number of links within this hypertext doc.
2001          *
2002          * @return number of links in this hypertext doc.
2003          */
2004         public int getLinkCount() {
2005             if (linksValid == false) {
2006                 buildLinkTable();
2007             }
2008             return hyperlinks.size();
2009         }
2010 
2011         /**
2012          * Returns the index into an array of hyperlinks that
2013          * is associated with this character index, or -1 if there
2014          * is no hyperlink associated with this index.
2015          *
2016          * @param  charIndex index within the text
2017          * @return index into the set of hyperlinks for this hypertext doc.
2018          */
2019         public int getLinkIndex(int charIndex) {
2020             if (linksValid == false) {
2021                 buildLinkTable();
2022             }
2023             Element e = null;
2024             Document doc = JEditorPane.this.getDocument();
2025             if (doc != null) {
2026                 for (e = doc.getDefaultRootElement(); ! e.isLeaf(); ) {
2027                     int index = e.getElementIndex(charIndex);
2028                     e = e.getElement(index);
2029                 }
2030             }
2031 
2032             // don't need to verify that it's an HREF element; if
2033             // not, then it won't be in the hyperlinks Vector, and
2034             // so indexOf will return -1 in any case
2035             return hyperlinks.baseElementIndex(e);
2036         }
2037 
2038         /**
2039          * Returns the index into an array of hyperlinks that
2040          * index.  If there is no hyperlink at this index, it returns
2041          * null.
2042          *
2043          * @param linkIndex into the set of hyperlinks for this hypertext doc.
2044          * @return string representation of the hyperlink
2045          */
2046         public AccessibleHyperlink getLink(int linkIndex) {
2047             if (linksValid == false) {
2048                 buildLinkTable();
2049             }
2050             if (linkIndex >= 0 && linkIndex < hyperlinks.size()) {
2051                 return hyperlinks.elementAt(linkIndex);
2052             } else {
2053                 return null;
2054             }
2055         }
2056 
2057         /**
2058          * Returns the contiguous text within the document that
2059          * is associated with this hyperlink.
2060          *
2061          * @param linkIndex into the set of hyperlinks for this hypertext doc.
2062          * @return the contiguous text sharing the link at this index
2063          */
2064         public String getLinkText(int linkIndex) {
2065             if (linksValid == false) {
2066                 buildLinkTable();
2067             }
2068             Element e = (Element) hyperlinks.elementAt(linkIndex);
2069             if (e != null) {
2070                 Document d = JEditorPane.this.getDocument();
2071                 if (d != null) {
2072                     try {
2073                         return d.getText(e.getStartOffset(),
2074                                          e.getEndOffset() - e.getStartOffset());
2075                     } catch (BadLocationException exception) {
2076                         return null;
2077                     }
2078                 }
2079             }
2080             return null;
2081         }
2082     }
2083 
2084     static class PlainEditorKit extends DefaultEditorKit implements ViewFactory {
2085 
2086         /**
2087          * Fetches a factory that is suitable for producing
2088          * views of any models that are produced by this
2089          * kit.  The default is to have the UI produce the
2090          * factory, so this method has no implementation.
2091          *
2092          * @return the view factory
2093          */
2094         public ViewFactory getViewFactory() {
2095             return this;
2096         }
2097 
2098         /**
2099          * Creates a view from the given structural element of a
2100          * document.
2101          *
2102          * @param elem  the piece of the document to build a view of
2103          * @return the view
2104          * @see View
2105          */
2106         public View create(Element elem) {
2107             Document doc = elem.getDocument();
2108             Object i18nFlag
2109                 = doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/);
2110             if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) {
2111                 // build a view that support bidi
2112                 return createI18N(elem);
2113             } else {
2114                 return new WrappedPlainView(elem);
2115             }
2116         }
2117 
2118         View createI18N(Element elem) {
2119             String kind = elem.getName();
2120             if (kind != null) {
2121                 if (kind.equals(AbstractDocument.ContentElementName)) {
2122                     return new PlainParagraph(elem);
2123                 } else if (kind.equals(AbstractDocument.ParagraphElementName)){
2124                     return new BoxView(elem, View.Y_AXIS);
2125                 }
2126             }
2127             return null;
2128         }
2129 
2130         /**
2131          * Paragraph for representing plain-text lines that support
2132          * bidirectional text.
2133          */
2134         static class PlainParagraph extends javax.swing.text.ParagraphView {
2135 
2136             PlainParagraph(Element elem) {
2137                 super(elem);
2138                 layoutPool = new LogicalView(elem);
2139                 layoutPool.setParent(this);
2140             }
2141 
2142             protected void setPropertiesFromAttributes() {
2143                 Component c = getContainer();
2144                 if ((c != null)
2145                     && (! c.getComponentOrientation().isLeftToRight()))
2146                 {
2147                     setJustification(StyleConstants.ALIGN_RIGHT);
2148                 } else {
2149                     setJustification(StyleConstants.ALIGN_LEFT);
2150                 }
2151             }
2152 
2153             /**
2154              * Fetch the constraining span to flow against for
2155              * the given child index.
2156              */
2157             public int getFlowSpan(int index) {
2158                 Component c = getContainer();
2159                 if (c instanceof JTextArea) {
2160                     JTextArea area = (JTextArea) c;
2161                     if (! area.getLineWrap()) {
2162                         // no limit if unwrapped
2163                         return Integer.MAX_VALUE;
2164                     }
2165                 }
2166                 return super.getFlowSpan(index);
2167             }
2168 
2169             protected SizeRequirements calculateMinorAxisRequirements(int axis,
2170                                                             SizeRequirements r)
2171             {
2172                 SizeRequirements req
2173                     = super.calculateMinorAxisRequirements(axis, r);
2174                 Component c = getContainer();
2175                 if (c instanceof JTextArea) {
2176                     JTextArea area = (JTextArea) c;
2177                     if (! area.getLineWrap()) {
2178                         // min is pref if unwrapped
2179                         req.minimum = req.preferred;
2180                     }
2181                 }
2182                 return req;
2183             }
2184 
2185             /**
2186              * This class can be used to represent a logical view for
2187              * a flow.  It keeps the children updated to reflect the state
2188              * of the model, gives the logical child views access to the
2189              * view hierarchy, and calculates a preferred span.  It doesn't
2190              * do any rendering, layout, or model/view translation.
2191              */
2192             static class LogicalView extends CompositeView {
2193 
2194                 LogicalView(Element elem) {
2195                     super(elem);
2196                 }
2197 
2198                 protected int getViewIndexAtPosition(int pos) {
2199                     Element elem = getElement();
2200                     if (elem.getElementCount() > 0) {
2201                         return elem.getElementIndex(pos);
2202                     }
2203                     return 0;
2204                 }
2205 
2206                 protected boolean
2207                 updateChildren(DocumentEvent.ElementChange ec,
2208                                DocumentEvent e, ViewFactory f)
2209                 {
2210                     return false;
2211                 }
2212 
2213                 protected void loadChildren(ViewFactory f) {
2214                     Element elem = getElement();
2215                     if (elem.getElementCount() > 0) {
2216                         super.loadChildren(f);
2217                     } else {
2218                         View v = new GlyphView(elem);
2219                         append(v);
2220                     }
2221                 }
2222 
2223                 public float getPreferredSpan(int axis) {
2224                     if( getViewCount() != 1 )
2225                         throw new Error("One child view is assumed.");
2226 
2227                     View v = getView(0);
2228                     //((GlyphView)v).setGlyphPainter(null);
2229                     return v.getPreferredSpan(axis);
2230                 }
2231 
2232                 /**
2233                  * Forward the DocumentEvent to the given child view.  This
2234                  * is implemented to reparent the child to the logical view
2235                  * (the children may have been parented by a row in the flow
2236                  * if they fit without breaking) and then execute the
2237                  * superclass behavior.
2238                  *
2239                  * @param v the child view to forward the event to.
2240                  * @param e the change information from the associated document
2241                  * @param a the current allocation of the view
2242                  * @param f the factory to use to rebuild if the view has
2243                  *          children
2244                  * @see #forwardUpdate
2245                  * @since 1.3
2246                  */
2247                 protected void forwardUpdateToView(View v, DocumentEvent e,
2248                                                    Shape a, ViewFactory f) {
2249                     v.setParent(this);
2250                     super.forwardUpdateToView(v, e, a, f);
2251                 }
2252 
2253                 // The following methods don't do anything useful, they
2254                 // simply keep the class from being abstract.
2255 
2256                 public void paint(Graphics g, Shape allocation) {
2257                 }
2258 
2259                 protected boolean isBefore(int x, int y, Rectangle alloc) {
2260                     return false;
2261                 }
2262 
2263                 protected boolean isAfter(int x, int y, Rectangle alloc) {
2264                     return false;
2265                 }
2266 
2267                 protected View getViewAtPoint(int x, int y, Rectangle alloc) {
2268                     return null;
2269                 }
2270 
2271                 protected void childAllocation(int index, Rectangle a) {
2272                 }
2273             }
2274         }
2275     }
2276 
2277 /* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers
2278  * sensibly:
2279  * From a String like: 'timeout=15, max=5'
2280  * create an array of Strings:
2281  * { {"timeout", "15"},
2282  *   {"max", "5"}
2283  * }
2284  * From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"'
2285  * create one like (no quotes in literal):
2286  * { {"basic", null},
2287  *   {"realm", "FuzzFace"}
2288  *   {"foo", "Biz Bar Baz"}
2289  * }
2290  * keys are converted to lower case, vals are left as is....
2291  *
2292  * author Dave Brown
2293  */
2294 
2295 
2296 static class HeaderParser {
2297 
2298     /* table of key/val pairs - maxes out at 10!!!!*/
2299     String raw;
2300     String[][] tab;
2301 
2302     public HeaderParser(String raw) {
2303         this.raw = raw;
2304         tab = new String[10][2];
2305         parse();
2306     }
2307 
2308     private void parse() {
2309 
2310         if (raw != null) {
2311             raw = raw.trim();
2312             char[] ca = raw.toCharArray();
2313             int beg = 0, end = 0, i = 0;
2314             boolean inKey = true;
2315             boolean inQuote = false;
2316             int len = ca.length;
2317             while (end < len) {
2318                 char c = ca[end];
2319                 if (c == '=') { // end of a key
2320                     tab[i][0] = new String(ca, beg, end-beg).toLowerCase();
2321                     inKey = false;
2322                     end++;
2323                     beg = end;
2324                 } else if (c == '\"') {
2325                     if (inQuote) {
2326                         tab[i++][1]= new String(ca, beg, end-beg);
2327                         inQuote=false;
2328                         do {
2329                             end++;
2330                         } while (end < len && (ca[end] == ' ' || ca[end] == ','));
2331                         inKey=true;
2332                         beg=end;
2333                     } else {
2334                         inQuote=true;
2335                         end++;
2336                         beg=end;
2337                     }
2338                 } else if (c == ' ' || c == ',') { // end key/val, of whatever we're in
2339                     if (inQuote) {
2340                         end++;
2341                         continue;
2342                     } else if (inKey) {
2343                         tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase();
2344                     } else {
2345                         tab[i++][1] = (new String(ca, beg, end-beg));
2346                     }
2347                     while (end < len && (ca[end] == ' ' || ca[end] == ',')) {
2348                         end++;
2349                     }
2350                     inKey = true;
2351                     beg = end;
2352                 } else {
2353                     end++;
2354                 }
2355             }
2356             // get last key/val, if any
2357             if (--end > beg) {
2358                 if (!inKey) {
2359                     if (ca[end] == '\"') {
2360                         tab[i++][1] = (new String(ca, beg, end-beg));
2361                     } else {
2362                         tab[i++][1] = (new String(ca, beg, end-beg+1));
2363                     }
2364                 } else {
2365                     tab[i][0] = (new String(ca, beg, end-beg+1)).toLowerCase();
2366                 }
2367             } else if (end == beg) {
2368                 if (!inKey) {
2369                     if (ca[end] == '\"') {
2370                         tab[i++][1] = String.valueOf(ca[end-1]);
2371                     } else {
2372                         tab[i++][1] = String.valueOf(ca[end]);
2373                     }
2374                 } else {
2375                     tab[i][0] = String.valueOf(ca[end]).toLowerCase();
2376                 }
2377             }
2378         }
2379 
2380     }
2381 
2382     public String findKey(int i) {
2383         if (i < 0 || i > 10)
2384             return null;
2385         return tab[i][0];
2386     }
2387 
2388     public String findValue(int i) {
2389         if (i < 0 || i > 10)
2390             return null;
2391         return tab[i][1];
2392     }
2393 
2394     public String findValue(String key) {
2395         return findValue(key, null);
2396     }
2397 
2398     public String findValue(String k, String Default) {
2399         if (k == null)
2400             return Default;
2401         k = k.toLowerCase();
2402         for (int i = 0; i < 10; ++i) {
2403             if (tab[i][0] == null) {
2404                 return Default;
2405             } else if (k.equals(tab[i][0])) {
2406                 return tab[i][1];
2407             }
2408         }
2409         return Default;
2410     }
2411 
2412     public int findInt(String k, int Default) {
2413         try {
2414             return Integer.parseInt(findValue(k, String.valueOf(Default)));
2415         } catch (Throwable t) {
2416             return Default;
2417         }
2418     }
2419  }
2420 
2421 }