1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package javax.swing;
  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         String charset = (String) getClientProperty("charset");
 563         try(Reader r = (charset != null) ? new InputStreamReader(in, charset) :
 564                 new InputStreamReader(in)) {
 565             kit.read(r, doc, 0);
 566         } catch (BadLocationException e) {
 567             throw new IOException(e.getMessage());
 568         } catch (ChangedCharSetException changedCharSetException) {
 569             String charSetSpec = changedCharSetException.getCharSetSpec();
 570             if (changedCharSetException.keyEqualsCharSet()) {
 571                 putClientProperty("charset", charSetSpec);
 572             } else {
 573                 setCharsetFromContentTypeParameters(charSetSpec);
 574             }
 575             try {
 576                 in.reset();
 577             } catch (IOException exception) {
 578                 //mark was invalidated
 579                 in.close();
 580                 URL url = (URL)doc.getProperty(Document.StreamDescriptionProperty);
 581                 if (url != null) {
 582                     URLConnection conn = url.openConnection();
 583                     in = conn.getInputStream();
 584                 } else {
 585                     //there is nothing we can do to recover stream
 586                     throw changedCharSetException;
 587                 }
 588             }
 589             try {
 590                 doc.remove(0, doc.getLength());
 591             } catch (BadLocationException e) {}
 592             doc.putProperty("IgnoreCharsetDirective", Boolean.valueOf(true));
 593             read(in, doc);
 594         }
 595     }
 596 
 597 
 598     /**
 599      * Loads a stream into the text document model.
 600      */
 601     class PageLoader extends SwingWorker<URL, Object> {
 602 
 603         /**
 604          * Construct an asynchronous page loader.
 605          */
 606         PageLoader(Document doc, InputStream in, URL old, URL page) {
 607             this.in = in;
 608             this.old = old;
 609             this.page = page;
 610             this.doc = doc;
 611         }
 612 
 613         /**
 614          * Try to load the document, then scroll the view
 615          * to the reference (if specified).  When done, fire
 616          * a page property change event.
 617          */
 618         protected URL doInBackground() {
 619             boolean pageLoaded = false;
 620             try {
 621                 if (in == null) {
 622                     in = getStream(page);
 623                     if (kit == null) {
 624                         // We received document of unknown content type.
 625                         UIManager.getLookAndFeel().
 626                                 provideErrorFeedback(JEditorPane.this);
 627                         return old;
 628                     }
 629                 }
 630 
 631                 if (doc == null) {
 632                     try {
 633                         SwingUtilities.invokeAndWait(new Runnable() {
 634                             public void run() {
 635                                 doc = initializeModel(kit, page);
 636                                 setDocument(doc);
 637                             }
 638                         });
 639                     } catch (InvocationTargetException ex) {
 640                         UIManager.getLookAndFeel().provideErrorFeedback(
 641                                                             JEditorPane.this);
 642                         return old;
 643                     } catch (InterruptedException ex) {
 644                         UIManager.getLookAndFeel().provideErrorFeedback(
 645                                                             JEditorPane.this);
 646                         return old;
 647                     }
 648                 }
 649 
 650                 read(in, doc);
 651                 URL page = (URL) doc.getProperty(Document.StreamDescriptionProperty);
 652                 String reference = page.getRef();
 653                 if (reference != null) {
 654                     // scroll the page if necessary, but do it on the
 655                     // event thread... that is the only guarantee that
 656                     // modelToView can be safely called.
 657                     Runnable callScrollToReference = new Runnable() {
 658                         public void run() {
 659                             URL u = (URL) getDocument().getProperty
 660                                 (Document.StreamDescriptionProperty);
 661                             String ref = u.getRef();
 662                             scrollToReference(ref);
 663                         }
 664                     };
 665                     SwingUtilities.invokeLater(callScrollToReference);
 666                 }
 667                 pageLoaded = true;
 668             } catch (IOException ioe) {
 669                 UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
 670             } finally {
 671                 if (pageLoaded) {
 672                     SwingUtilities.invokeLater(new Runnable() {
 673                         public void run() {
 674                             JEditorPane.this.firePropertyChange("page", old, page);
 675                         }
 676                     });
 677                 }
 678             }
 679             return (pageLoaded ? page : old);
 680         }
 681 
 682         /**
 683          * The stream to load the document with
 684          */
 685         InputStream in;
 686 
 687         /**
 688          * URL of the old page that was replaced (for the property change event)
 689          */
 690         URL old;
 691 
 692         /**
 693          * URL of the page being loaded (for the property change event)
 694          */
 695         URL page;
 696 
 697         /**
 698          * The Document instance to load into. This is cached in case a
 699          * new Document is created between the time the thread this is created
 700          * and run.
 701          */
 702         Document doc;
 703     }
 704 
 705     /**
 706      * Fetches a stream for the given URL, which is about to
 707      * be loaded by the <code>setPage</code> method.  By
 708      * default, this simply opens the URL and returns the
 709      * stream.  This can be reimplemented to do useful things
 710      * like fetch the stream from a cache, monitor the progress
 711      * of the stream, etc.
 712      * <p>
 713      * This method is expected to have the side effect of
 714      * establishing the content type, and therefore setting the
 715      * appropriate <code>EditorKit</code> to use for loading the stream.
 716      * <p>
 717      * If this the stream was an http connection, redirects
 718      * will be followed and the resulting URL will be set as
 719      * the <code>Document.StreamDescriptionProperty</code> so that relative
 720      * URL's can be properly resolved.
 721      *
 722      * @param page  the URL of the page
 723      * @return a stream for the URL which is about to be loaded
 724      * @throws IOException if an I/O problem occurs
 725      */
 726     protected InputStream getStream(URL page) throws IOException {
 727         final URLConnection conn = page.openConnection();
 728         if (conn instanceof HttpURLConnection) {
 729             HttpURLConnection hconn = (HttpURLConnection) conn;
 730             hconn.setInstanceFollowRedirects(false);
 731             Object postData = getPostData();
 732             if (postData != null) {
 733                 handlePostData(hconn, postData);
 734             }
 735             int response = hconn.getResponseCode();
 736             boolean redirect = (response >= 300 && response <= 399);
 737 
 738             /*
 739              * In the case of a redirect, we want to actually change the URL
 740              * that was input to the new, redirected URL
 741              */
 742             if (redirect) {
 743                 String loc = conn.getHeaderField("Location");
 744                 if (loc.startsWith("http", 0)) {
 745                     page = new URL(loc);
 746                 } else {
 747                     page = new URL(page, loc);
 748                 }
 749                 return getStream(page);
 750             }
 751         }
 752 
 753         // Connection properties handler should be forced to run on EDT,
 754         // as it instantiates the EditorKit.
 755         if (SwingUtilities.isEventDispatchThread()) {
 756             handleConnectionProperties(conn);
 757         } else {
 758             try {
 759                 SwingUtilities.invokeAndWait(new Runnable() {
 760                     public void run() {
 761                         handleConnectionProperties(conn);
 762                     }
 763                 });
 764             } catch (InterruptedException e) {
 765                 throw new RuntimeException(e);
 766             } catch (InvocationTargetException e) {
 767                 throw new RuntimeException(e);
 768             }
 769         }
 770         return conn.getInputStream();
 771     }
 772 
 773     /**
 774      * Handle URL connection properties (most notably, content type).
 775      */
 776     private void handleConnectionProperties(URLConnection conn) {
 777         if (pageProperties == null) {
 778             pageProperties = new Hashtable<String, Object>();
 779         }
 780         String type = conn.getContentType();
 781         if (type != null) {
 782             setContentType(type);
 783             pageProperties.put("content-type", type);
 784         }
 785         pageProperties.put(Document.StreamDescriptionProperty, conn.getURL());
 786         String enc = conn.getContentEncoding();
 787         if (enc != null) {
 788             pageProperties.put("content-encoding", enc);
 789         }
 790     }
 791 
 792     private Object getPostData() {
 793         return getDocument().getProperty(PostDataProperty);
 794     }
 795 
 796     private void handlePostData(HttpURLConnection conn, Object postData)
 797                                                             throws IOException {
 798         conn.setDoOutput(true);
 799         DataOutputStream os = null;
 800         try {
 801             conn.setRequestProperty("Content-Type",
 802                     "application/x-www-form-urlencoded");
 803             os = new DataOutputStream(conn.getOutputStream());
 804             os.writeBytes((String) postData);
 805         } finally {
 806             if (os != null) {
 807                 os.close();
 808             }
 809         }
 810     }
 811 
 812 
 813     /**
 814      * Scrolls the view to the given reference location
 815      * (that is, the value returned by the <code>UL.getRef</code>
 816      * method for the URL being displayed).  By default, this
 817      * method only knows how to locate a reference in an
 818      * HTMLDocument.  The implementation calls the
 819      * <code>scrollRectToVisible</code> method to
 820      * accomplish the actual scrolling.  If scrolling to a
 821      * reference location is needed for document types other
 822      * than HTML, this method should be reimplemented.
 823      * This method will have no effect if the component
 824      * is not visible.
 825      *
 826      * @param reference the named location to scroll to
 827      */
 828     public void scrollToReference(String reference) {
 829         Document d = getDocument();
 830         if (d instanceof HTMLDocument) {
 831             HTMLDocument doc = (HTMLDocument) d;
 832             HTMLDocument.Iterator iter = doc.getIterator(HTML.Tag.A);
 833             for (; iter.isValid(); iter.next()) {
 834                 AttributeSet a = iter.getAttributes();
 835                 String nm = (String) a.getAttribute(HTML.Attribute.NAME);
 836                 if ((nm != null) && nm.equals(reference)) {
 837                     // found a matching reference in the document.
 838                     try {
 839                         int pos = iter.getStartOffset();
 840                         Rectangle r = modelToView(pos);
 841                         if (r != null) {
 842                             // the view is visible, scroll it to the
 843                             // center of the current visible area.
 844                             Rectangle vis = getVisibleRect();
 845                             //r.y -= (vis.height / 2);
 846                             r.height = vis.height;
 847                             scrollRectToVisible(r);
 848                             setCaretPosition(pos);
 849                         }
 850                     } catch (BadLocationException ble) {
 851                         UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
 852                     }
 853                 }
 854             }
 855         }
 856     }
 857 
 858     /**
 859      * Gets the current URL being displayed.  If a URL was
 860      * not specified in the creation of the document, this
 861      * will return <code>null</code>, and relative URL's will not be
 862      * resolved.
 863      *
 864      * @return the URL, or <code>null</code> if none
 865      */
 866     public URL getPage() {
 867         return (URL) getDocument().getProperty(Document.StreamDescriptionProperty);
 868     }
 869 
 870     /**
 871      * Sets the current URL being displayed.
 872      *
 873      * @param url the URL for display
 874      * @exception IOException for a <code>null</code> or invalid URL
 875      *          specification
 876      */
 877     public void setPage(String url) throws IOException {
 878         if (url == null) {
 879             throw new IOException("invalid url");
 880         }
 881         URL page = new URL(url);
 882         setPage(page);
 883     }
 884 
 885     /**
 886      * Gets the class ID for the UI.
 887      *
 888      * @return the string "EditorPaneUI"
 889      * @see JComponent#getUIClassID
 890      * @see UIDefaults#getUI
 891      */
 892     @BeanProperty(bound = false)
 893     public String getUIClassID() {
 894         return uiClassID;
 895     }
 896 
 897     /**
 898      * Creates the default editor kit (<code>PlainEditorKit</code>) for when
 899      * the component is first created.
 900      *
 901      * @return the editor kit
 902      */
 903     protected EditorKit createDefaultEditorKit() {
 904         return new PlainEditorKit();
 905     }
 906 
 907     /**
 908      * Fetches the currently installed kit for handling content.
 909      * <code>createDefaultEditorKit</code> is called to set up a default
 910      * if necessary.
 911      *
 912      * @return the editor kit
 913      */
 914     public EditorKit getEditorKit() {
 915         if (kit == null) {
 916             kit = createDefaultEditorKit();
 917             isUserSetEditorKit = false;
 918         }
 919         return kit;
 920     }
 921 
 922     /**
 923      * Gets the type of content that this editor
 924      * is currently set to deal with.  This is
 925      * defined to be the type associated with the
 926      * currently installed <code>EditorKit</code>.
 927      *
 928      * @return the content type, <code>null</code> if no editor kit set
 929      */
 930     public final String getContentType() {
 931         return (kit != null) ? kit.getContentType() : null;
 932     }
 933 
 934     /**
 935      * Sets the type of content that this editor
 936      * handles.  This calls <code>getEditorKitForContentType</code>,
 937      * and then <code>setEditorKit</code> if an editor kit can
 938      * be successfully located.  This is mostly convenience method
 939      * that can be used as an alternative to calling
 940      * <code>setEditorKit</code> directly.
 941      * <p>
 942      * If there is a charset definition specified as a parameter
 943      * of the content type specification, it will be used when
 944      * loading input streams using the associated <code>EditorKit</code>.
 945      * For example if the type is specified as
 946      * <code>text/html; charset=EUC-JP</code> the content
 947      * will be loaded using the <code>EditorKit</code> registered for
 948      * <code>text/html</code> and the Reader provided to
 949      * the <code>EditorKit</code> to load unicode into the document will
 950      * use the <code>EUC-JP</code> charset for translating
 951      * to unicode.  If the type is not recognized, the content
 952      * will be loaded using the <code>EditorKit</code> registered
 953      * for plain text, <code>text/plain</code>.
 954      *
 955      * @param type the non-<code>null</code> mime type for the content editing
 956      *   support
 957      * @see #getContentType
 958      * @throws NullPointerException if the <code>type</code> parameter
 959      *          is <code>null</code>
 960      */
 961     @BeanProperty(bound = false, description
 962             = "the type of content")
 963     public final void setContentType(String type) {
 964         // The type could have optional info is part of it,
 965         // for example some charset info.  We need to strip that
 966         // of and save it.
 967         int parm = type.indexOf(';');
 968         if (parm > -1) {
 969             // Save the paramList.
 970             String paramList = type.substring(parm);
 971             // update the content type string.
 972             type = type.substring(0, parm).trim();
 973             if (type.toLowerCase().startsWith("text/")) {
 974                 setCharsetFromContentTypeParameters(paramList);
 975             }
 976         }
 977         if ((kit == null) || (! type.equals(kit.getContentType()))
 978                 || !isUserSetEditorKit) {
 979             EditorKit k = getEditorKitForContentType(type);
 980             if (k != null && k != kit) {
 981                 setEditorKit(k);
 982                 isUserSetEditorKit = false;
 983             }
 984         }
 985 
 986     }
 987 
 988     /**
 989      * This method gets the charset information specified as part
 990      * of the content type in the http header information.
 991      */
 992     private void setCharsetFromContentTypeParameters(String paramlist) {
 993         String charset;
 994         try {
 995             // paramlist is handed to us with a leading ';', strip it.
 996             int semi = paramlist.indexOf(';');
 997             if (semi > -1 && semi < paramlist.length()-1) {
 998                 paramlist = paramlist.substring(semi + 1);
 999             }
1000 
1001             if (paramlist.length() > 0) {
1002                 // parse the paramlist into attr-value pairs & get the
1003                 // charset pair's value
1004                 HeaderParser hdrParser = new HeaderParser(paramlist);
1005                 charset = hdrParser.findValue("charset");
1006                 if (charset != null) {
1007                     putClientProperty("charset", charset);
1008                 }
1009             }
1010         }
1011         catch (IndexOutOfBoundsException e) {
1012             // malformed parameter list, use charset we have
1013         }
1014         catch (NullPointerException e) {
1015             // malformed parameter list, use charset we have
1016         }
1017         catch (Exception e) {
1018             // malformed parameter list, use charset we have; but complain
1019             System.err.println("JEditorPane.getCharsetFromContentTypeParameters failed on: " + paramlist);
1020             e.printStackTrace();
1021         }
1022     }
1023 
1024 
1025     /**
1026      * Sets the currently installed kit for handling
1027      * content.  This is the bound property that
1028      * establishes the content type of the editor.
1029      * Any old kit is first deinstalled, then if kit is
1030      * non-<code>null</code>,
1031      * the new kit is installed, and a default document created for it.
1032      * A <code>PropertyChange</code> event ("editorKit") is always fired when
1033      * <code>setEditorKit</code> is called.
1034      * <p>
1035      * <em>NOTE: This has the side effect of changing the model,
1036      * because the <code>EditorKit</code> is the source of how a
1037      * particular type
1038      * of content is modeled.  This method will cause <code>setDocument</code>
1039      * to be called on behalf of the caller to ensure integrity
1040      * of the internal state.</em>
1041      *
1042      * @param kit the desired editor behavior
1043      * @see #getEditorKit
1044      */
1045     @BeanProperty(expert = true, description
1046             = "the currently installed kit for handling content")
1047     public void setEditorKit(EditorKit kit) {
1048         EditorKit old = this.kit;
1049         isUserSetEditorKit = true;
1050         if (old != null) {
1051             old.deinstall(this);
1052         }
1053         this.kit = kit;
1054         if (this.kit != null) {
1055             this.kit.install(this);
1056             setDocument(this.kit.createDefaultDocument());
1057         }
1058         firePropertyChange("editorKit", old, kit);
1059     }
1060 
1061     /**
1062      * Fetches the editor kit to use for the given type
1063      * of content.  This is called when a type is requested
1064      * that doesn't match the currently installed type.
1065      * If the component doesn't have an <code>EditorKit</code> registered
1066      * for the given type, it will try to create an
1067      * <code>EditorKit</code> from the default <code>EditorKit</code> registry.
1068      * If that fails, a <code>PlainEditorKit</code> is used on the
1069      * assumption that all text documents can be represented
1070      * as plain text.
1071      * <p>
1072      * This method can be reimplemented to use some
1073      * other kind of type registry.  This can
1074      * be reimplemented to use the Java Activation
1075      * Framework, for example.
1076      *
1077      * @param type the non-<code>null</code> content type
1078      * @return the editor kit
1079      */
1080     public EditorKit getEditorKitForContentType(String type) {
1081         if (typeHandlers == null) {
1082             typeHandlers = new Hashtable<String, EditorKit>(3);
1083         }
1084         EditorKit k = typeHandlers.get(type);
1085         if (k == null) {
1086             k = createEditorKitForContentType(type);
1087             if (k != null) {
1088                 setEditorKitForContentType(type, k);
1089             }
1090         }
1091         if (k == null) {
1092             k = createDefaultEditorKit();
1093         }
1094         return k;
1095     }
1096 
1097     /**
1098      * Directly sets the editor kit to use for the given type.  A
1099      * look-and-feel implementation might use this in conjunction
1100      * with <code>createEditorKitForContentType</code> to install handlers for
1101      * content types with a look-and-feel bias.
1102      *
1103      * @param type the non-<code>null</code> content type
1104      * @param k the editor kit to be set
1105      */
1106     public void setEditorKitForContentType(String type, EditorKit k) {
1107         if (typeHandlers == null) {
1108             typeHandlers = new Hashtable<String, EditorKit>(3);
1109         }
1110         typeHandlers.put(type, k);
1111     }
1112 
1113     /**
1114      * Replaces the currently selected content with new content
1115      * represented by the given string.  If there is no selection
1116      * this amounts to an insert of the given text.  If there
1117      * is no replacement text (i.e. the content string is empty
1118      * or <code>null</code>) this amounts to a removal of the
1119      * current selection.  The replacement text will have the
1120      * attributes currently defined for input.  If the component is not
1121      * editable, beep and return.
1122      *
1123      * @param content  the content to replace the selection with.  This
1124      *   value can be <code>null</code>
1125      */
1126     @Override
1127     public void replaceSelection(String content) {
1128         if (! isEditable()) {
1129             UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1130             return;
1131         }
1132         EditorKit kit = getEditorKit();
1133         if(kit instanceof StyledEditorKit) {
1134             try {
1135                 Document doc = getDocument();
1136                 Caret caret = getCaret();
1137                 boolean composedTextSaved = saveComposedText(caret.getDot());
1138                 int p0 = Math.min(caret.getDot(), caret.getMark());
1139                 int p1 = Math.max(caret.getDot(), caret.getMark());
1140                 if (doc instanceof AbstractDocument) {
1141                     ((AbstractDocument)doc).replace(p0, p1 - p0, content,
1142                               ((StyledEditorKit)kit).getInputAttributes());
1143                 }
1144                 else {
1145                     if (p0 != p1) {
1146                         doc.remove(p0, p1 - p0);
1147                     }
1148                     if (content != null && content.length() > 0) {
1149                         doc.insertString(p0, content, ((StyledEditorKit)kit).
1150                                          getInputAttributes());
1151                     }
1152                 }
1153                 if (composedTextSaved) {
1154                     restoreComposedText();
1155                 }
1156             } catch (BadLocationException e) {
1157                 UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1158             }
1159         }
1160         else {
1161             super.replaceSelection(content);
1162         }
1163     }
1164 
1165     /**
1166      * Creates a handler for the given type from the default registry
1167      * of editor kits.  The registry is created if necessary.  If the
1168      * registered class has not yet been loaded, an attempt
1169      * is made to dynamically load the prototype of the kit for the
1170      * given type.  If the type was registered with a <code>ClassLoader</code>,
1171      * that <code>ClassLoader</code> will be used to load the prototype.
1172      * If there was no registered <code>ClassLoader</code>,
1173      * <code>Class.forName</code> will be used to load the prototype.
1174      * <p>
1175      * Once a prototype <code>EditorKit</code> instance is successfully
1176      * located, it is cloned and the clone is returned.
1177      *
1178      * @param type the content type
1179      * @return the editor kit, or <code>null</code> if there is nothing
1180      *   registered for the given type
1181      */
1182     public static EditorKit createEditorKitForContentType(String type) {
1183         Hashtable<String, EditorKit> kitRegistry = getKitRegisty();
1184         EditorKit k = kitRegistry.get(type);
1185         if (k == null) {
1186             // try to dynamically load the support
1187             String classname = getKitTypeRegistry().get(type);
1188             ClassLoader loader = getKitLoaderRegistry().get(type);
1189             try {
1190                 Class<?> c;
1191                 if (loader != null) {
1192                     ReflectUtil.checkPackageAccess(classname);
1193                     c = loader.loadClass(classname);
1194                 } else {
1195                     // Will only happen if developer has invoked
1196                     // registerEditorKitForContentType(type, class, null).
1197                     c = SwingUtilities.loadSystemClass(classname);
1198                 }
1199                 k = (EditorKit) c.getDeclaredConstructor().newInstance();
1200                 kitRegistry.put(type, k);
1201             } catch (Throwable e) {
1202                 k = null;
1203             }
1204         }
1205 
1206         // create a copy of the prototype or null if there
1207         // is no prototype.
1208         if (k != null) {
1209             return (EditorKit) k.clone();
1210         }
1211         return null;
1212     }
1213 
1214     /**
1215      * Establishes the default bindings of <code>type</code> to
1216      * <code>classname</code>.
1217      * The class will be dynamically loaded later when actually
1218      * needed, and can be safely changed before attempted uses
1219      * to avoid loading unwanted classes.  The prototype
1220      * <code>EditorKit</code> will be loaded with <code>Class.forName</code>
1221      * when registered with this method.
1222      *
1223      * @param type the non-<code>null</code> content type
1224      * @param classname the class to load later
1225      */
1226     public static void registerEditorKitForContentType(String type, String classname) {
1227         registerEditorKitForContentType(type, classname,Thread.currentThread().
1228                                         getContextClassLoader());
1229     }
1230 
1231     /**
1232      * Establishes the default bindings of <code>type</code> to
1233      * <code>classname</code>.
1234      * The class will be dynamically loaded later when actually
1235      * needed using the given <code>ClassLoader</code>,
1236      * and can be safely changed
1237      * before attempted uses to avoid loading unwanted classes.
1238      *
1239      * @param type the non-<code>null</code> content type
1240      * @param classname the class to load later
1241      * @param loader the <code>ClassLoader</code> to use to load the name
1242      */
1243     public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) {
1244         getKitTypeRegistry().put(type, classname);
1245         if (loader != null) {
1246             getKitLoaderRegistry().put(type, loader);
1247         } else {
1248             getKitLoaderRegistry().remove(type);
1249         }
1250         getKitRegisty().remove(type);
1251     }
1252 
1253     /**
1254      * Returns the currently registered {@code EditorKit} class name for the
1255      * type {@code type}.
1256      *
1257      * @param type  the non-{@code null} content type
1258      * @return a {@code String} containing the {@code EditorKit} class name
1259      *         for {@code type}
1260      * @since 1.3
1261      */
1262     public static String getEditorKitClassNameForContentType(String type) {
1263         return getKitTypeRegistry().get(type);
1264     }
1265 
1266     private static Hashtable<String, String> getKitTypeRegistry() {
1267         loadDefaultKitsIfNecessary();
1268         @SuppressWarnings("unchecked")
1269         Hashtable<String, String> tmp =
1270             (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
1271         return tmp;
1272     }
1273 
1274     private static Hashtable<String, ClassLoader> getKitLoaderRegistry() {
1275         loadDefaultKitsIfNecessary();
1276         @SuppressWarnings("unchecked")
1277         Hashtable<String,  ClassLoader> tmp =
1278             (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
1279         return tmp;
1280     }
1281 
1282     private static Hashtable<String, EditorKit> getKitRegisty() {
1283         @SuppressWarnings("unchecked")
1284         Hashtable<String, EditorKit> ht =
1285             (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
1286         if (ht == null) {
1287             ht = new Hashtable<>(3);
1288             SwingUtilities.appContextPut(kitRegistryKey, ht);
1289         }
1290         return ht;
1291     }
1292 
1293     /**
1294      * This is invoked every time the registries are accessed. Loading
1295      * is done this way instead of via a static as the static is only
1296      * called once when running in plugin resulting in the entries only
1297      * appearing in the first applet.
1298      */
1299     private static void loadDefaultKitsIfNecessary() {
1300         if (SwingUtilities.appContextGet(kitTypeRegistryKey) == null) {
1301             synchronized(defaultEditorKitMap) {
1302                 if (defaultEditorKitMap.size() == 0) {
1303                     defaultEditorKitMap.put("text/plain",
1304                                             "javax.swing.JEditorPane$PlainEditorKit");
1305                     defaultEditorKitMap.put("text/html",
1306                                             "javax.swing.text.html.HTMLEditorKit");
1307                     defaultEditorKitMap.put("text/rtf",
1308                                             "javax.swing.text.rtf.RTFEditorKit");
1309                     defaultEditorKitMap.put("application/rtf",
1310                                             "javax.swing.text.rtf.RTFEditorKit");
1311                 }
1312             }
1313             Hashtable<Object, Object> ht = new Hashtable<>();
1314             SwingUtilities.appContextPut(kitTypeRegistryKey, ht);
1315             ht = new Hashtable<>();
1316             SwingUtilities.appContextPut(kitLoaderRegistryKey, ht);
1317             for (String key : defaultEditorKitMap.keySet()) {
1318                 registerEditorKitForContentType(key,defaultEditorKitMap.get(key));
1319             }
1320 
1321         }
1322     }
1323 
1324     // --- java.awt.Component methods --------------------------
1325 
1326     /**
1327      * Returns the preferred size for the <code>JEditorPane</code>.
1328      * The preferred size for <code>JEditorPane</code> is slightly altered
1329      * from the preferred size of the superclass.  If the size
1330      * of the viewport has become smaller than the minimum size
1331      * of the component, the scrollable definition for tracking
1332      * width or height will turn to false.  The default viewport
1333      * layout will give the preferred size, and that is not desired
1334      * in the case where the scrollable is tracking.  In that case
1335      * the <em>normal</em> preferred size is adjusted to the
1336      * minimum size.  This allows things like HTML tables to
1337      * shrink down to their minimum size and then be laid out at
1338      * their minimum size, refusing to shrink any further.
1339      *
1340      * @return a <code>Dimension</code> containing the preferred size
1341      */
1342     public Dimension getPreferredSize() {
1343         Dimension d = super.getPreferredSize();
1344         Container parent = SwingUtilities.getUnwrappedParent(this);
1345         if (parent instanceof JViewport) {
1346             JViewport port = (JViewport) parent;
1347             TextUI ui = getUI();
1348             int prefWidth = d.width;
1349             int prefHeight = d.height;
1350             if (! getScrollableTracksViewportWidth()) {
1351                 int w = port.getWidth();
1352                 Dimension min = ui.getMinimumSize(this);
1353                 if (w != 0 && w < min.width) {
1354                     // Only adjust to min if we have a valid size
1355                     prefWidth = min.width;
1356                 }
1357             }
1358             if (! getScrollableTracksViewportHeight()) {
1359                 int h = port.getHeight();
1360                 Dimension min = ui.getMinimumSize(this);
1361                 if (h != 0 && h < min.height) {
1362                     // Only adjust to min if we have a valid size
1363                     prefHeight = min.height;
1364                 }
1365             }
1366             if (prefWidth != d.width || prefHeight != d.height) {
1367                 d = new Dimension(prefWidth, prefHeight);
1368             }
1369         }
1370         return d;
1371     }
1372 
1373     // --- JTextComponent methods -----------------------------
1374 
1375     /**
1376      * Sets the text of this <code>TextComponent</code> to the specified
1377      * content,
1378      * which is expected to be in the format of the content type of
1379      * this editor.  For example, if the type is set to <code>text/html</code>
1380      * the string should be specified in terms of HTML.
1381      * <p>
1382      * This is implemented to remove the contents of the current document,
1383      * and replace them by parsing the given string using the current
1384      * <code>EditorKit</code>.  This gives the semantics of the
1385      * superclass by not changing
1386      * out the model, while supporting the content type currently set on
1387      * this component.  The assumption is that the previous content is
1388      * relatively
1389      * small, and that the previous content doesn't have side effects.
1390      * Both of those assumptions can be violated and cause undesirable results.
1391      * To avoid this, create a new document,
1392      * <code>getEditorKit().createDefaultDocument()</code>, and replace the
1393      * existing <code>Document</code> with the new one. You are then assured the
1394      * previous <code>Document</code> won't have any lingering state.
1395      * <ol>
1396      * <li>
1397      * Leaving the existing model in place means that the old view will be
1398      * torn down, and a new view created, where replacing the document would
1399      * avoid the tear down of the old view.
1400      * <li>
1401      * Some formats (such as HTML) can install things into the document that
1402      * can influence future contents.  HTML can have style information embedded
1403      * that would influence the next content installed unexpectedly.
1404      * </ol>
1405      * <p>
1406      * An alternative way to load this component with a string would be to
1407      * create a StringReader and call the read method.  In this case the model
1408      * would be replaced after it was initialized with the contents of the
1409      * string.
1410      *
1411      * @param t the new text to be set; if <code>null</code> the old
1412      *    text will be deleted
1413      * @see #getText
1414      */
1415     @BeanProperty(bound = false, description
1416             = "the text of this component")
1417     public void setText(String t) {
1418         try {
1419             Document doc = getDocument();
1420             doc.remove(0, doc.getLength());
1421             if (t == null || t.equals("")) {
1422                 return;
1423             }
1424             Reader r = new StringReader(t);
1425             EditorKit kit = getEditorKit();
1426             kit.read(r, doc, 0);
1427         } catch (IOException ioe) {
1428             UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1429         } catch (BadLocationException ble) {
1430             UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
1431         }
1432     }
1433 
1434     /**
1435      * Returns the text contained in this <code>TextComponent</code>
1436      * in terms of the
1437      * content type of this editor.  If an exception is thrown while
1438      * attempting to retrieve the text, <code>null</code> will be returned.
1439      * This is implemented to call <code>JTextComponent.write</code> with
1440      * a <code>StringWriter</code>.
1441      *
1442      * @return the text
1443      * @see #setText
1444      */
1445     public String getText() {
1446         String txt;
1447         try {
1448             StringWriter buf = new StringWriter();
1449             write(buf);
1450             txt = buf.toString();
1451         } catch (IOException ioe) {
1452             txt = null;
1453         }
1454         return txt;
1455     }
1456 
1457     // --- Scrollable  ----------------------------------------
1458 
1459     /**
1460      * Returns true if a viewport should always force the width of this
1461      * <code>Scrollable</code> to match the width of the viewport.
1462      *
1463      * @return true if a viewport should force the Scrollables width to
1464      * match its own, false otherwise
1465      */
1466     @BeanProperty(bound = false)
1467     public boolean getScrollableTracksViewportWidth() {
1468         Container parent = SwingUtilities.getUnwrappedParent(this);
1469         if (parent instanceof JViewport) {
1470             JViewport port = (JViewport) parent;
1471             TextUI ui = getUI();
1472             int w = port.getWidth();
1473             Dimension min = ui.getMinimumSize(this);
1474             Dimension max = ui.getMaximumSize(this);
1475             if ((w >= min.width) && (w <= max.width)) {
1476                 return true;
1477             }
1478         }
1479         return false;
1480     }
1481 
1482     /**
1483      * Returns true if a viewport should always force the height of this
1484      * <code>Scrollable</code> to match the height of the viewport.
1485      *
1486      * @return true if a viewport should force the
1487      *          <code>Scrollable</code>'s height to match its own,
1488      *          false otherwise
1489      */
1490     @BeanProperty(bound = false)
1491     public boolean getScrollableTracksViewportHeight() {
1492         Container parent = SwingUtilities.getUnwrappedParent(this);
1493         if (parent instanceof JViewport) {
1494             JViewport port = (JViewport) parent;
1495             TextUI ui = getUI();
1496             int h = port.getHeight();
1497             Dimension min = ui.getMinimumSize(this);
1498             if (h >= min.height) {
1499                 Dimension max = ui.getMaximumSize(this);
1500                 if (h <= max.height) {
1501                     return true;
1502                 }
1503             }
1504         }
1505         return false;
1506     }
1507 
1508     // --- Serialization ------------------------------------
1509 
1510     /**
1511      * See <code>readObject</code> and <code>writeObject</code> in
1512      * <code>JComponent</code> for more
1513      * information about serialization in Swing.
1514      */
1515     private void writeObject(ObjectOutputStream s) throws IOException {
1516         s.defaultWriteObject();
1517         if (getUIClassID().equals(uiClassID)) {
1518             byte count = JComponent.getWriteObjCounter(this);
1519             JComponent.setWriteObjCounter(this, --count);
1520             if (count == 0 && ui != null) {
1521                 ui.installUI(this);
1522             }
1523         }
1524     }
1525 
1526     // --- variables ---------------------------------------
1527 
1528     private SwingWorker<URL, Object> pageLoader;
1529 
1530     /**
1531      * Current content binding of the editor.
1532      */
1533     private EditorKit kit;
1534     private boolean isUserSetEditorKit;
1535 
1536     private Hashtable<String, Object> pageProperties;
1537 
1538     /** Should be kept in sync with javax.swing.text.html.FormView counterpart. */
1539     static final String PostDataProperty = "javax.swing.JEditorPane.postdata";
1540 
1541     /**
1542      * Table of registered type handlers for this editor.
1543      */
1544     private Hashtable<String, EditorKit> typeHandlers;
1545 
1546     /*
1547      * Private AppContext keys for this class's static variables.
1548      */
1549     private static final Object kitRegistryKey =
1550         new StringBuffer("JEditorPane.kitRegistry");
1551     private static final Object kitTypeRegistryKey =
1552         new StringBuffer("JEditorPane.kitTypeRegistry");
1553     private static final Object kitLoaderRegistryKey =
1554         new StringBuffer("JEditorPane.kitLoaderRegistry");
1555 
1556     /**
1557      * @see #getUIClassID
1558      * @see #readObject
1559      */
1560     private static final String uiClassID = "EditorPaneUI";
1561 
1562 
1563     /**
1564      * Key for a client property used to indicate whether
1565      * <a href="http://www.w3.org/TR/CSS21/syndata.html#length-units">
1566      * w3c compliant</a> length units are used for html rendering.
1567      * <p>
1568      * By default this is not enabled; to enable
1569      * it set the client {@link #putClientProperty property} with this name
1570      * to <code>Boolean.TRUE</code>.
1571      *
1572      * @since 1.5
1573      */
1574     public static final String W3C_LENGTH_UNITS = "JEditorPane.w3cLengthUnits";
1575 
1576     /**
1577      * Key for a client property used to indicate whether
1578      * the default font and foreground color from the component are
1579      * used if a font or foreground color is not specified in the styled
1580      * text.
1581      * <p>
1582      * The default varies based on the look and feel;
1583      * to enable it set the client {@link #putClientProperty property} with
1584      * this name to <code>Boolean.TRUE</code>.
1585      *
1586      * @since 1.5
1587      */
1588     public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties";
1589 
1590     static final Map<String, String> defaultEditorKitMap = new HashMap<String, String>(0);
1591 
1592     /**
1593      * Returns a string representation of this <code>JEditorPane</code>.
1594      * This method
1595      * is intended to be used only for debugging purposes, and the
1596      * content and format of the returned string may vary between
1597      * implementations. The returned string may be empty but may not
1598      * be <code>null</code>.
1599      *
1600      * @return  a string representation of this <code>JEditorPane</code>
1601      */
1602     protected String paramString() {
1603         String kitString = (kit != null ?
1604                             kit.toString() : "");
1605         String typeHandlersString = (typeHandlers != null ?
1606                                      typeHandlers.toString() : "");
1607 
1608         return super.paramString() +
1609         ",kit=" + kitString +
1610         ",typeHandlers=" + typeHandlersString;
1611     }
1612 
1613 
1614 /////////////////
1615 // Accessibility support
1616 ////////////////
1617 
1618 
1619     /**
1620      * Gets the AccessibleContext associated with this JEditorPane.
1621      * For editor panes, the AccessibleContext takes the form of an
1622      * AccessibleJEditorPane.
1623      * A new AccessibleJEditorPane instance is created if necessary.
1624      *
1625      * @return an AccessibleJEditorPane that serves as the
1626      *         AccessibleContext of this JEditorPane
1627      */
1628     @BeanProperty(bound = false)
1629     public AccessibleContext getAccessibleContext() {
1630         if (getEditorKit() instanceof HTMLEditorKit) {
1631             if (accessibleContext == null || accessibleContext.getClass() !=
1632                     AccessibleJEditorPaneHTML.class) {
1633                 accessibleContext = new AccessibleJEditorPaneHTML();
1634             }
1635         } else if (accessibleContext == null || accessibleContext.getClass() !=
1636                        AccessibleJEditorPane.class) {
1637             accessibleContext = new AccessibleJEditorPane();
1638         }
1639         return accessibleContext;
1640     }
1641 
1642     /**
1643      * This class implements accessibility support for the
1644      * <code>JEditorPane</code> class.  It provides an implementation of the
1645      * Java Accessibility API appropriate to editor pane user-interface
1646      * elements.
1647      * <p>
1648      * <strong>Warning:</strong>
1649      * Serialized objects of this class will not be compatible with
1650      * future Swing releases. The current serialization support is
1651      * appropriate for short term storage or RMI between applications running
1652      * the same version of Swing.  As of 1.4, support for long term storage
1653      * of all JavaBeans&trade;
1654      * has been added to the <code>java.beans</code> package.
1655      * Please see {@link java.beans.XMLEncoder}.
1656      */
1657     @SuppressWarnings("serial") // Same-version serialization only
1658     protected class AccessibleJEditorPane extends AccessibleJTextComponent {
1659 
1660         /**
1661          * Gets the accessibleDescription property of this object.  If this
1662          * property isn't set, returns the content type of this
1663          * <code>JEditorPane</code> instead (e.g. "plain/text", "html/text").
1664          *
1665          * @return the localized description of the object; <code>null</code>
1666          *      if this object does not have a description
1667          *
1668          * @see #setAccessibleName
1669          */
1670         public String getAccessibleDescription() {
1671             String description = accessibleDescription;
1672 
1673             // fallback to client property
1674             if (description == null) {
1675                 description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
1676             }
1677             if (description == null) {
1678                 description = JEditorPane.this.getContentType();
1679             }
1680             return description;
1681         }
1682 
1683         /**
1684          * Gets the state set of this object.
1685          *
1686          * @return an instance of AccessibleStateSet describing the states
1687          * of the object
1688          * @see AccessibleStateSet
1689          */
1690         public AccessibleStateSet getAccessibleStateSet() {
1691             AccessibleStateSet states = super.getAccessibleStateSet();
1692             states.add(AccessibleState.MULTI_LINE);
1693             return states;
1694         }
1695     }
1696 
1697     /**
1698      * This class provides support for <code>AccessibleHypertext</code>,
1699      * and is used in instances where the <code>EditorKit</code>
1700      * installed in this <code>JEditorPane</code> is an instance of
1701      * <code>HTMLEditorKit</code>.
1702      * <p>
1703      * <strong>Warning:</strong>
1704      * Serialized objects of this class will not be compatible with
1705      * future Swing releases. The current serialization support is
1706      * appropriate for short term storage or RMI between applications running
1707      * the same version of Swing.  As of 1.4, support for long term storage
1708      * of all JavaBeans&trade;
1709      * has been added to the <code>java.beans</code> package.
1710      * Please see {@link java.beans.XMLEncoder}.
1711      */
1712     @SuppressWarnings("serial") // Same-version serialization only
1713     protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane {
1714 
1715         private AccessibleContext accessibleContext;
1716 
1717         /**
1718          * Returns the accessible text.
1719          * @return the accessible text
1720          */
1721         public AccessibleText getAccessibleText() {
1722             return new JEditorPaneAccessibleHypertextSupport();
1723         }
1724 
1725         /**
1726          * Constructs an {@code AccessibleJEditorPaneHTML}.
1727          */
1728         protected AccessibleJEditorPaneHTML () {
1729             HTMLEditorKit kit = (HTMLEditorKit)JEditorPane.this.getEditorKit();
1730             accessibleContext = kit.getAccessibleContext();
1731         }
1732 
1733         /**
1734          * Returns the number of accessible children of the object.
1735          *
1736          * @return the number of accessible children of the object.
1737          */
1738         public int getAccessibleChildrenCount() {
1739             if (accessibleContext != null) {
1740                 return accessibleContext.getAccessibleChildrenCount();
1741             } else {
1742                 return 0;
1743             }
1744         }
1745 
1746         /**
1747          * Returns the specified Accessible child of the object.  The Accessible
1748          * children of an Accessible object are zero-based, so the first child
1749          * of an Accessible child is at index 0, the second child is at index 1,
1750          * and so on.
1751          *
1752          * @param i zero-based index of child
1753          * @return the Accessible child of the object
1754          * @see #getAccessibleChildrenCount
1755          */
1756         public Accessible getAccessibleChild(int i) {
1757             if (accessibleContext != null) {
1758                 return accessibleContext.getAccessibleChild(i);
1759             } else {
1760                 return null;
1761             }
1762         }
1763 
1764         /**
1765          * Returns the Accessible child, if one exists, contained at the local
1766          * coordinate Point.
1767          *
1768          * @param p The point relative to the coordinate system of this object.
1769          * @return the Accessible, if it exists, at the specified location;
1770          * otherwise null
1771          */
1772         public Accessible getAccessibleAt(Point p) {
1773             if (accessibleContext != null && p != null) {
1774                 try {
1775                     AccessibleComponent acomp =
1776                         accessibleContext.getAccessibleComponent();
1777                     if (acomp != null) {
1778                         return acomp.getAccessibleAt(p);
1779                     } else {
1780                         return null;
1781                     }
1782                 } catch (IllegalComponentStateException e) {
1783                     return null;
1784                 }
1785             } else {
1786                 return null;
1787             }
1788         }
1789     }
1790 
1791     /**
1792      * What's returned by
1793      * <code>AccessibleJEditorPaneHTML.getAccessibleText</code>.
1794      *
1795      * Provides support for <code>AccessibleHypertext</code> in case
1796      * there is an HTML document being displayed in this
1797      * <code>JEditorPane</code>.
1798      *
1799      */
1800     protected class JEditorPaneAccessibleHypertextSupport
1801     extends AccessibleJEditorPane implements AccessibleHypertext {
1802 
1803         /**
1804          * An HTML link.
1805          */
1806         public class HTMLLink extends AccessibleHyperlink {
1807             Element element;
1808 
1809             /**
1810              * Constructs a {@code HTMLLink}.
1811              * @param e the element
1812              */
1813             public HTMLLink(Element e) {
1814                 element = e;
1815             }
1816 
1817             /**
1818              * Since the document a link is associated with may have
1819              * changed, this method returns whether this Link is valid
1820              * anymore (with respect to the document it references).
1821              *
1822              * @return a flag indicating whether this link is still valid with
1823              *         respect to the AccessibleHypertext it belongs to
1824              */
1825             public boolean isValid() {
1826                 return JEditorPaneAccessibleHypertextSupport.this.linksValid;
1827             }
1828 
1829             /**
1830              * Returns the number of accessible actions available in this Link
1831              * If there are more than one, the first one is NOT considered the
1832              * "default" action of this LINK object (e.g. in an HTML imagemap).
1833              * In general, links will have only one AccessibleAction in them.
1834              *
1835              * @return the zero-based number of Actions in this object
1836              */
1837             public int getAccessibleActionCount() {
1838                 return 1;
1839             }
1840 
1841             /**
1842              * Perform the specified Action on the object
1843              *
1844              * @param i zero-based index of actions
1845              * @return true if the action was performed; else false.
1846              * @see #getAccessibleActionCount
1847              */
1848             public boolean doAccessibleAction(int i) {
1849                 if (i == 0 && isValid() == true) {
1850                     URL u = (URL) getAccessibleActionObject(i);
1851                     if (u != null) {
1852                         HyperlinkEvent linkEvent =
1853                             new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u);
1854                         JEditorPane.this.fireHyperlinkUpdate(linkEvent);
1855                         return true;
1856                     }
1857                 }
1858                 return false;  // link invalid or i != 0
1859             }
1860 
1861             /**
1862              * Return a String description of this particular
1863              * link action.  The string returned is the text
1864              * within the document associated with the element
1865              * which contains this link.
1866              *
1867              * @param i zero-based index of the actions
1868              * @return a String description of the action
1869              * @see #getAccessibleActionCount
1870              */
1871             public String getAccessibleActionDescription(int i) {
1872                 if (i == 0 && isValid() == true) {
1873                     Document d = JEditorPane.this.getDocument();
1874                     if (d != null) {
1875                         try {
1876                             return d.getText(getStartIndex(),
1877                                              getEndIndex() - getStartIndex());
1878                         } catch (BadLocationException exception) {
1879                             return null;
1880                         }
1881                     }
1882                 }
1883                 return null;
1884             }
1885 
1886             /**
1887              * Returns a URL object that represents the link.
1888              *
1889              * @param i zero-based index of the actions
1890              * @return an URL representing the HTML link itself
1891              * @see #getAccessibleActionCount
1892              */
1893             public Object getAccessibleActionObject(int i) {
1894                 if (i == 0 && isValid() == true) {
1895                     AttributeSet as = element.getAttributes();
1896                     AttributeSet anchor =
1897                         (AttributeSet) as.getAttribute(HTML.Tag.A);
1898                     String href = (anchor != null) ?
1899                         (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
1900                     if (href != null) {
1901                         URL u;
1902                         try {
1903                             u = new URL(JEditorPane.this.getPage(), href);
1904                         } catch (MalformedURLException m) {
1905                             u = null;
1906                         }
1907                         return u;
1908                     }
1909                 }
1910                 return null;  // link invalid or i != 0
1911             }
1912 
1913             /**
1914              * Return an object that represents the link anchor,
1915              * as appropriate for that link.  E.g. from HTML:
1916              *   <a href="http://www.sun.com/access">Accessibility</a>
1917              * this method would return a String containing the text:
1918              * 'Accessibility'.
1919              *
1920              * Similarly, from this HTML:
1921              *   &lt;a HREF="#top"&gt;&lt;img src="top-hat.gif" alt="top hat"&gt;&lt;/a&gt;
1922              * this might return the object ImageIcon("top-hat.gif", "top hat");
1923              *
1924              * @param i zero-based index of the actions
1925              * @return an Object representing the hypertext anchor
1926              * @see #getAccessibleActionCount
1927              */
1928             public Object getAccessibleActionAnchor(int i) {
1929                 return getAccessibleActionDescription(i);
1930             }
1931 
1932 
1933             /**
1934              * Get the index with the hypertext document at which this
1935              * link begins
1936              *
1937              * @return index of start of link
1938              */
1939             public int getStartIndex() {
1940                 return element.getStartOffset();
1941             }
1942 
1943             /**
1944              * Get the index with the hypertext document at which this
1945              * link ends
1946              *
1947              * @return index of end of link
1948              */
1949             public int getEndIndex() {
1950                 return element.getEndOffset();
1951             }
1952         }
1953 
1954         private class LinkVector extends Vector<HTMLLink> {
1955             public int baseElementIndex(Element e) {
1956                 HTMLLink l;
1957                 for (int i = 0; i < elementCount; i++) {
1958                     l = elementAt(i);
1959                     if (l.element == e) {
1960                         return i;
1961                     }
1962                 }
1963                 return -1;
1964             }
1965         }
1966 
1967         LinkVector hyperlinks;
1968         boolean linksValid = false;
1969 
1970         /**
1971          * Build the private table mapping links to locations in the text
1972          */
1973         private void buildLinkTable() {
1974             hyperlinks.removeAllElements();
1975             Document d = JEditorPane.this.getDocument();
1976             if (d != null) {
1977                 ElementIterator ei = new ElementIterator(d);
1978                 Element e;
1979                 AttributeSet as;
1980                 AttributeSet anchor;
1981                 String href;
1982                 while ((e = ei.next()) != null) {
1983                     if (e.isLeaf()) {
1984                         as = e.getAttributes();
1985                     anchor = (AttributeSet) as.getAttribute(HTML.Tag.A);
1986                     href = (anchor != null) ?
1987                         (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
1988                         if (href != null) {
1989                             hyperlinks.addElement(new HTMLLink(e));
1990                         }
1991                     }
1992                 }
1993             }
1994             linksValid = true;
1995         }
1996 
1997         /**
1998          * Make one of these puppies
1999          */
2000         public JEditorPaneAccessibleHypertextSupport() {
2001             hyperlinks = new LinkVector();
2002             Document d = JEditorPane.this.getDocument();
2003             if (d != null) {
2004                 d.addDocumentListener(new DocumentListener() {
2005                     public void changedUpdate(DocumentEvent theEvent) {
2006                         linksValid = false;
2007                     }
2008                     public void insertUpdate(DocumentEvent theEvent) {
2009                         linksValid = false;
2010                     }
2011                     public void removeUpdate(DocumentEvent theEvent) {
2012                         linksValid = false;
2013                     }
2014                 });
2015             }
2016         }
2017 
2018         /**
2019          * Returns the number of links within this hypertext doc.
2020          *
2021          * @return number of links in this hypertext doc.
2022          */
2023         public int getLinkCount() {
2024             if (linksValid == false) {
2025                 buildLinkTable();
2026             }
2027             return hyperlinks.size();
2028         }
2029 
2030         /**
2031          * Returns the index into an array of hyperlinks that
2032          * is associated with this character index, or -1 if there
2033          * is no hyperlink associated with this index.
2034          *
2035          * @param  charIndex index within the text
2036          * @return index into the set of hyperlinks for this hypertext doc.
2037          */
2038         public int getLinkIndex(int charIndex) {
2039             if (linksValid == false) {
2040                 buildLinkTable();
2041             }
2042             Element e = null;
2043             Document doc = JEditorPane.this.getDocument();
2044             if (doc != null) {
2045                 for (e = doc.getDefaultRootElement(); ! e.isLeaf(); ) {
2046                     int index = e.getElementIndex(charIndex);
2047                     e = e.getElement(index);
2048                 }
2049             }
2050 
2051             // don't need to verify that it's an HREF element; if
2052             // not, then it won't be in the hyperlinks Vector, and
2053             // so indexOf will return -1 in any case
2054             return hyperlinks.baseElementIndex(e);
2055         }
2056 
2057         /**
2058          * Returns the index into an array of hyperlinks that
2059          * index.  If there is no hyperlink at this index, it returns
2060          * null.
2061          *
2062          * @param linkIndex into the set of hyperlinks for this hypertext doc.
2063          * @return string representation of the hyperlink
2064          */
2065         public AccessibleHyperlink getLink(int linkIndex) {
2066             if (linksValid == false) {
2067                 buildLinkTable();
2068             }
2069             if (linkIndex >= 0 && linkIndex < hyperlinks.size()) {
2070                 return hyperlinks.elementAt(linkIndex);
2071             } else {
2072                 return null;
2073             }
2074         }
2075 
2076         /**
2077          * Returns the contiguous text within the document that
2078          * is associated with this hyperlink.
2079          *
2080          * @param linkIndex into the set of hyperlinks for this hypertext doc.
2081          * @return the contiguous text sharing the link at this index
2082          */
2083         public String getLinkText(int linkIndex) {
2084             if (linksValid == false) {
2085                 buildLinkTable();
2086             }
2087             Element e = (Element) hyperlinks.elementAt(linkIndex);
2088             if (e != null) {
2089                 Document d = JEditorPane.this.getDocument();
2090                 if (d != null) {
2091                     try {
2092                         return d.getText(e.getStartOffset(),
2093                                          e.getEndOffset() - e.getStartOffset());
2094                     } catch (BadLocationException exception) {
2095                         return null;
2096                     }
2097                 }
2098             }
2099             return null;
2100         }
2101     }
2102 
2103     static class PlainEditorKit extends DefaultEditorKit implements ViewFactory {
2104 
2105         /**
2106          * Fetches a factory that is suitable for producing
2107          * views of any models that are produced by this
2108          * kit.  The default is to have the UI produce the
2109          * factory, so this method has no implementation.
2110          *
2111          * @return the view factory
2112          */
2113         public ViewFactory getViewFactory() {
2114             return this;
2115         }
2116 
2117         /**
2118          * Creates a view from the given structural element of a
2119          * document.
2120          *
2121          * @param elem  the piece of the document to build a view of
2122          * @return the view
2123          * @see View
2124          */
2125         public View create(Element elem) {
2126             Document doc = elem.getDocument();
2127             Object i18nFlag
2128                 = doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/);
2129             if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) {
2130                 // build a view that support bidi
2131                 return createI18N(elem);
2132             } else {
2133                 return new WrappedPlainView(elem);
2134             }
2135         }
2136 
2137         View createI18N(Element elem) {
2138             String kind = elem.getName();
2139             if (kind != null) {
2140                 if (kind.equals(AbstractDocument.ContentElementName)) {
2141                     return new PlainParagraph(elem);
2142                 } else if (kind.equals(AbstractDocument.ParagraphElementName)){
2143                     return new BoxView(elem, View.Y_AXIS);
2144                 }
2145             }
2146             return null;
2147         }
2148 
2149         /**
2150          * Paragraph for representing plain-text lines that support
2151          * bidirectional text.
2152          */
2153         static class PlainParagraph extends javax.swing.text.ParagraphView {
2154 
2155             PlainParagraph(Element elem) {
2156                 super(elem);
2157                 layoutPool = new LogicalView(elem);
2158                 layoutPool.setParent(this);
2159             }
2160 
2161             protected void setPropertiesFromAttributes() {
2162                 Component c = getContainer();
2163                 if ((c != null)
2164                     && (! c.getComponentOrientation().isLeftToRight()))
2165                 {
2166                     setJustification(StyleConstants.ALIGN_RIGHT);
2167                 } else {
2168                     setJustification(StyleConstants.ALIGN_LEFT);
2169                 }
2170             }
2171 
2172             /**
2173              * Fetch the constraining span to flow against for
2174              * the given child index.
2175              */
2176             public int getFlowSpan(int index) {
2177                 Component c = getContainer();
2178                 if (c instanceof JTextArea) {
2179                     JTextArea area = (JTextArea) c;
2180                     if (! area.getLineWrap()) {
2181                         // no limit if unwrapped
2182                         return Integer.MAX_VALUE;
2183                     }
2184                 }
2185                 return super.getFlowSpan(index);
2186             }
2187 
2188             protected SizeRequirements calculateMinorAxisRequirements(int axis,
2189                                                             SizeRequirements r)
2190             {
2191                 SizeRequirements req
2192                     = super.calculateMinorAxisRequirements(axis, r);
2193                 Component c = getContainer();
2194                 if (c instanceof JTextArea) {
2195                     JTextArea area = (JTextArea) c;
2196                     if (! area.getLineWrap()) {
2197                         // min is pref if unwrapped
2198                         req.minimum = req.preferred;
2199                     }
2200                 }
2201                 return req;
2202             }
2203 
2204             /**
2205              * This class can be used to represent a logical view for
2206              * a flow.  It keeps the children updated to reflect the state
2207              * of the model, gives the logical child views access to the
2208              * view hierarchy, and calculates a preferred span.  It doesn't
2209              * do any rendering, layout, or model/view translation.
2210              */
2211             static class LogicalView extends CompositeView {
2212 
2213                 LogicalView(Element elem) {
2214                     super(elem);
2215                 }
2216 
2217                 protected int getViewIndexAtPosition(int pos) {
2218                     Element elem = getElement();
2219                     if (elem.getElementCount() > 0) {
2220                         return elem.getElementIndex(pos);
2221                     }
2222                     return 0;
2223                 }
2224 
2225                 protected boolean
2226                 updateChildren(DocumentEvent.ElementChange ec,
2227                                DocumentEvent e, ViewFactory f)
2228                 {
2229                     return false;
2230                 }
2231 
2232                 protected void loadChildren(ViewFactory f) {
2233                     Element elem = getElement();
2234                     if (elem.getElementCount() > 0) {
2235                         super.loadChildren(f);
2236                     } else {
2237                         View v = new GlyphView(elem);
2238                         append(v);
2239                     }
2240                 }
2241 
2242                 public float getPreferredSpan(int axis) {
2243                     if( getViewCount() != 1 )
2244                         throw new Error("One child view is assumed.");
2245 
2246                     View v = getView(0);
2247                     //((GlyphView)v).setGlyphPainter(null);
2248                     return v.getPreferredSpan(axis);
2249                 }
2250 
2251                 /**
2252                  * Forward the DocumentEvent to the given child view.  This
2253                  * is implemented to reparent the child to the logical view
2254                  * (the children may have been parented by a row in the flow
2255                  * if they fit without breaking) and then execute the
2256                  * superclass behavior.
2257                  *
2258                  * @param v the child view to forward the event to.
2259                  * @param e the change information from the associated document
2260                  * @param a the current allocation of the view
2261                  * @param f the factory to use to rebuild if the view has
2262                  *          children
2263                  * @see #forwardUpdate
2264                  * @since 1.3
2265                  */
2266                 protected void forwardUpdateToView(View v, DocumentEvent e,
2267                                                    Shape a, ViewFactory f) {
2268                     v.setParent(this);
2269                     super.forwardUpdateToView(v, e, a, f);
2270                 }
2271 
2272                 // The following methods don't do anything useful, they
2273                 // simply keep the class from being abstract.
2274 
2275                 public void paint(Graphics g, Shape allocation) {
2276                 }
2277 
2278                 protected boolean isBefore(int x, int y, Rectangle alloc) {
2279                     return false;
2280                 }
2281 
2282                 protected boolean isAfter(int x, int y, Rectangle alloc) {
2283                     return false;
2284                 }
2285 
2286                 protected View getViewAtPoint(int x, int y, Rectangle alloc) {
2287                     return null;
2288                 }
2289 
2290                 protected void childAllocation(int index, Rectangle a) {
2291                 }
2292             }
2293         }
2294     }
2295 
2296 /* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers
2297  * sensibly:
2298  * From a String like: 'timeout=15, max=5'
2299  * create an array of Strings:
2300  * { {"timeout", "15"},
2301  *   {"max", "5"}
2302  * }
2303  * From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"'
2304  * create one like (no quotes in literal):
2305  * { {"basic", null},
2306  *   {"realm", "FuzzFace"}
2307  *   {"foo", "Biz Bar Baz"}
2308  * }
2309  * keys are converted to lower case, vals are left as is....
2310  *
2311  * author Dave Brown
2312  */
2313 
2314 
2315 static class HeaderParser {
2316 
2317     /* table of key/val pairs - maxes out at 10!!!!*/
2318     String raw;
2319     String[][] tab;
2320 
2321     public HeaderParser(String raw) {
2322         this.raw = raw;
2323         tab = new String[10][2];
2324         parse();
2325     }
2326 
2327     private void parse() {
2328 
2329         if (raw != null) {
2330             raw = raw.trim();
2331             char[] ca = raw.toCharArray();
2332             int beg = 0, end = 0, i = 0;
2333             boolean inKey = true;
2334             boolean inQuote = false;
2335             int len = ca.length;
2336             while (end < len) {
2337                 char c = ca[end];
2338                 if (c == '=') { // end of a key
2339                     tab[i][0] = new String(ca, beg, end-beg).toLowerCase();
2340                     inKey = false;
2341                     end++;
2342                     beg = end;
2343                 } else if (c == '\"') {
2344                     if (inQuote) {
2345                         tab[i++][1]= new String(ca, beg, end-beg);
2346                         inQuote=false;
2347                         do {
2348                             end++;
2349                         } while (end < len && (ca[end] == ' ' || ca[end] == ','));
2350                         inKey=true;
2351                         beg=end;
2352                     } else {
2353                         inQuote=true;
2354                         end++;
2355                         beg=end;
2356                     }
2357                 } else if (c == ' ' || c == ',') { // end key/val, of whatever we're in
2358                     if (inQuote) {
2359                         end++;
2360                         continue;
2361                     } else if (inKey) {
2362                         tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase();
2363                     } else {
2364                         tab[i++][1] = (new String(ca, beg, end-beg));
2365                     }
2366                     while (end < len && (ca[end] == ' ' || ca[end] == ',')) {
2367                         end++;
2368                     }
2369                     inKey = true;
2370                     beg = end;
2371                 } else {
2372                     end++;
2373                 }
2374             }
2375             // get last key/val, if any
2376             if (--end > beg) {
2377                 if (!inKey) {
2378                     if (ca[end] == '\"') {
2379                         tab[i++][1] = (new String(ca, beg, end-beg));
2380                     } else {
2381                         tab[i++][1] = (new String(ca, beg, end-beg+1));
2382                     }
2383                 } else {
2384                     tab[i][0] = (new String(ca, beg, end-beg+1)).toLowerCase();
2385                 }
2386             } else if (end == beg) {
2387                 if (!inKey) {
2388                     if (ca[end] == '\"') {
2389                         tab[i++][1] = String.valueOf(ca[end-1]);
2390                     } else {
2391                         tab[i++][1] = String.valueOf(ca[end]);
2392                     }
2393                 } else {
2394                     tab[i][0] = String.valueOf(ca[end]).toLowerCase();
2395                 }
2396             }
2397         }
2398 
2399     }
2400 
2401     public String findKey(int i) {
2402         if (i < 0 || i > 10)
2403             return null;
2404         return tab[i][0];
2405     }
2406 
2407     public String findValue(int i) {
2408         if (i < 0 || i > 10)
2409             return null;
2410         return tab[i][1];
2411     }
2412 
2413     public String findValue(String key) {
2414         return findValue(key, null);
2415     }
2416 
2417     public String findValue(String k, String Default) {
2418         if (k == null)
2419             return Default;
2420         k = k.toLowerCase();
2421         for (int i = 0; i < 10; ++i) {
2422             if (tab[i][0] == null) {
2423                 return Default;
2424             } else if (k.equals(tab[i][0])) {
2425                 return tab[i][1];
2426             }
2427         }
2428         return Default;
2429     }
2430 
2431     public int findInt(String k, int Default) {
2432         try {
2433             return Integer.parseInt(findValue(k, String.valueOf(Default)));
2434         } catch (Throwable t) {
2435             return Default;
2436         }
2437     }
2438  }
2439 
2440 }