1 /*
   2  * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package javax.swing.text.html;
  26 
  27 import java.awt.font.TextAttribute;
  28 import java.util.*;
  29 import java.net.URL;
  30 import java.net.MalformedURLException;
  31 import java.io.*;
  32 import javax.swing.*;
  33 import javax.swing.event.*;
  34 import javax.swing.text.*;
  35 import javax.swing.undo.*;
  36 import sun.swing.SwingUtilities2;
  37 import static sun.swing.SwingUtilities2.IMPLIED_CR;
  38 
  39 /**
  40  * A document that models HTML.  The purpose of this model is to
  41  * support both browsing and editing.  As a result, the structure
  42  * described by an HTML document is not exactly replicated by default.
  43  * The element structure that is modeled by default, is built by the
  44  * class <code>HTMLDocument.HTMLReader</code>, which implements the
  45  * <code>HTMLEditorKit.ParserCallback</code> protocol that the parser
  46  * expects.  To change the structure one can subclass
  47  * <code>HTMLReader</code>, and reimplement the method {@link
  48  * #getReader(int)} to return the new reader implementation.  The
  49  * documentation for <code>HTMLReader</code> should be consulted for
  50  * the details of the default structure created.  The intent is that
  51  * the document be non-lossy (although reproducing the HTML format may
  52  * result in a different format).
  53  *
  54  * <p>The document models only HTML, and makes no attempt to store
  55  * view attributes in it.  The elements are identified by the
  56  * <code>StyleContext.NameAttribute</code> attribute, which should
  57  * always have a value of type <code>HTML.Tag</code> that identifies
  58  * the kind of element.  Some of the elements (such as comments) are
  59  * synthesized.  The <code>HTMLFactory</code> uses this attribute to
  60  * determine what kind of view to build.</p>
  61  *
  62  * <p>This document supports incremental loading.  The
  63  * <code>TokenThreshold</code> property controls how much of the parse
  64  * is buffered before trying to update the element structure of the
  65  * document.  This property is set by the <code>EditorKit</code> so
  66  * that subclasses can disable it.</p>
  67  *
  68  * <p>The <code>Base</code> property determines the URL against which
  69  * relative URLs are resolved.  By default, this will be the
  70  * <code>Document.StreamDescriptionProperty</code> if the value of the
  71  * property is a URL.  If a &lt;BASE&gt; tag is encountered, the base
  72  * will become the URL specified by that tag.  Because the base URL is
  73  * a property, it can of course be set directly.</p>
  74  *
  75  * <p>The default content storage mechanism for this document is a gap
  76  * buffer (<code>GapContent</code>).  Alternatives can be supplied by
  77  * using the constructor that takes a <code>Content</code>
  78  * implementation.</p>
  79  *
  80  * <h2>Modifying HTMLDocument</h2>
  81  *
  82  * <p>In addition to the methods provided by Document and
  83  * StyledDocument for mutating an HTMLDocument, HTMLDocument provides
  84  * a number of convenience methods.  The following methods can be used
  85  * to insert HTML content into an existing document.</p>
  86  *
  87  * <ul>
  88  *   <li>{@link #setInnerHTML(Element, String)}</li>
  89  *   <li>{@link #setOuterHTML(Element, String)}</li>
  90  *   <li>{@link #insertBeforeStart(Element, String)}</li>
  91  *   <li>{@link #insertAfterStart(Element, String)}</li>
  92  *   <li>{@link #insertBeforeEnd(Element, String)}</li>
  93  *   <li>{@link #insertAfterEnd(Element, String)}</li>
  94  * </ul>
  95  *
  96  * <p>The following examples illustrate using these methods.  Each
  97  * example assumes the HTML document is initialized in the following
  98  * way:</p>
  99  *
 100  * <pre>
 101  * JEditorPane p = new JEditorPane();
 102  * p.setContentType("text/html");
 103  * p.setText("..."); // Document text is provided below.
 104  * HTMLDocument d = (HTMLDocument) p.getDocument();
 105  * </pre>
 106  *
 107  * <p>With the following HTML content:</p>
 108  *
 109  * <pre>
 110  * &lt;html&gt;
 111  *   &lt;head&gt;
 112  *     &lt;title&gt;An example HTMLDocument&lt;/title&gt;
 113  *     &lt;style type="text/css"&gt;
 114  *       div { background-color: silver; }
 115  *       ul { color: red; }
 116  *     &lt;/style&gt;
 117  *   &lt;/head&gt;
 118  *   &lt;body&gt;
 119  *     &lt;div id="BOX"&gt;
 120  *       &lt;p&gt;Paragraph 1&lt;/p&gt;
 121  *       &lt;p&gt;Paragraph 2&lt;/p&gt;
 122  *     &lt;/div&gt;
 123  *   &lt;/body&gt;
 124  * &lt;/html&gt;
 125  * </pre>
 126  *
 127  * <p>All the methods for modifying an HTML document require an {@link
 128  * Element}.  Elements can be obtained from an HTML document by using
 129  * the method {@link #getElement(Element e, Object attribute, Object
 130  * value)}.  It returns the first descendant element that contains the
 131  * specified attribute with the given value, in depth-first order.
 132  * For example, <code>d.getElement(d.getDefaultRootElement(),
 133  * StyleConstants.NameAttribute, HTML.Tag.P)</code> returns the first
 134  * paragraph element.</p>
 135  *
 136  * <p>A convenient shortcut for locating elements is the method {@link
 137  * #getElement(String)}; returns an element whose <code>ID</code>
 138  * attribute matches the specified value.  For example,
 139  * <code>d.getElement("BOX")</code> returns the <code>DIV</code>
 140  * element.</p>
 141  *
 142  * <p>The {@link #getIterator(HTML.Tag t)} method can also be used for
 143  * finding all occurrences of the specified HTML tag in the
 144  * document.</p>
 145  *
 146  * <h3>Inserting elements</h3>
 147  *
 148  * <p>Elements can be inserted before or after the existing children
 149  * of any non-leaf element by using the methods
 150  * <code>insertAfterStart</code> and <code>insertBeforeEnd</code>.
 151  * For example, if <code>e</code> is the <code>DIV</code> element,
 152  * <code>d.insertAfterStart(e, "&lt;ul&gt;&lt;li&gt;List
 153  * Item&lt;/li&gt;&lt;/ul&gt;")</code> inserts the list before the first
 154  * paragraph, and <code>d.insertBeforeEnd(e, "&lt;ul&gt;&lt;li&gt;List
 155  * Item&lt;/li&gt;&lt;/ul&gt;")</code> inserts the list after the last
 156  * paragraph.  The <code>DIV</code> block becomes the parent of the
 157  * newly inserted elements.</p>
 158  *
 159  * <p>Sibling elements can be inserted before or after any element by
 160  * using the methods <code>insertBeforeStart</code> and
 161  * <code>insertAfterEnd</code>.  For example, if <code>e</code> is the
 162  * <code>DIV</code> element, <code>d.insertBeforeStart(e,
 163  * "&lt;ul&gt;&lt;li&gt;List Item&lt;/li&gt;&lt;/ul&gt;")</code> inserts the list
 164  * before the <code>DIV</code> element, and <code>d.insertAfterEnd(e,
 165  * "&lt;ul&gt;&lt;li&gt;List Item&lt;/li&gt;&lt;/ul&gt;")</code> inserts the list
 166  * after the <code>DIV</code> element.  The newly inserted elements
 167  * become siblings of the <code>DIV</code> element.</p>
 168  *
 169  * <h3>Replacing elements</h3>
 170  *
 171  * <p>Elements and all their descendants can be replaced by using the
 172  * methods <code>setInnerHTML</code> and <code>setOuterHTML</code>.
 173  * For example, if <code>e</code> is the <code>DIV</code> element,
 174  * <code>d.setInnerHTML(e, "&lt;ul&gt;&lt;li&gt;List
 175  * Item&lt;/li&gt;&lt;/ul&gt;")</code> replaces all children paragraphs with
 176  * the list, and <code>d.setOuterHTML(e, "&lt;ul&gt;&lt;li&gt;List
 177  * Item&lt;/li&gt;&lt;/ul&gt;")</code> replaces the <code>DIV</code> element
 178  * itself.  In latter case the parent of the list is the
 179  * <code>BODY</code> element.
 180  *
 181  * <h3>Summary</h3>
 182  *
 183  * <p>The following table shows the example document and the results
 184  * of various methods described above.</p>
 185  *
 186  * <table border=1 cellspacing=0 summary="HTML Content of example above">
 187  *   <tr>
 188  *     <th>Example</th>
 189  *     <th><code>insertAfterStart</code></th>
 190  *     <th><code>insertBeforeEnd</code></th>
 191  *     <th><code>insertBeforeStart</code></th>
 192  *     <th><code>insertAfterEnd</code></th>
 193  *     <th><code>setInnerHTML</code></th>
 194  *     <th><code>setOuterHTML</code></th>
 195  *   </tr>
 196  *   <tr valign="top">
 197  *     <td style="white-space:nowrap">
 198  *       <div style="background-color: silver;">
 199  *         <p>Paragraph 1</p>
 200  *         <p>Paragraph 2</p>
 201  *       </div>
 202  *     </td>
 203  * <!--insertAfterStart-->
 204  *     <td style="white-space:nowrap">
 205  *       <div style="background-color: silver;">
 206  *         <ul style="color: red;">
 207  *           <li>List Item</li>
 208  *         </ul>
 209  *         <p>Paragraph 1</p>
 210  *         <p>Paragraph 2</p>
 211  *       </div>
 212  *     </td>
 213  * <!--insertBeforeEnd-->
 214  *     <td style="white-space:nowrap">
 215  *       <div style="background-color: silver;">
 216  *         <p>Paragraph 1</p>
 217  *         <p>Paragraph 2</p>
 218  *         <ul style="color: red;">
 219  *           <li>List Item</li>
 220  *         </ul>
 221  *       </div>
 222  *     </td>
 223  * <!--insertBeforeStart-->
 224  *     <td style="white-space:nowrap">
 225  *       <ul style="color: red;">
 226  *         <li>List Item</li>
 227  *       </ul>
 228  *       <div style="background-color: silver;">
 229  *         <p>Paragraph 1</p>
 230  *         <p>Paragraph 2</p>
 231  *       </div>
 232  *     </td>
 233  * <!--insertAfterEnd-->
 234  *     <td style="white-space:nowrap">
 235  *       <div style="background-color: silver;">
 236  *         <p>Paragraph 1</p>
 237  *         <p>Paragraph 2</p>
 238  *       </div>
 239  *       <ul style="color: red;">
 240  *         <li>List Item</li>
 241  *       </ul>
 242  *     </td>
 243  * <!--setInnerHTML-->
 244  *     <td style="white-space:nowrap">
 245  *       <div style="background-color: silver;">
 246  *         <ul style="color: red;">
 247  *           <li>List Item</li>
 248  *         </ul>
 249  *       </div>
 250  *     </td>
 251  * <!--setOuterHTML-->
 252  *     <td style="white-space:nowrap">
 253  *       <ul style="color: red;">
 254  *         <li>List Item</li>
 255  *       </ul>
 256  *     </td>
 257  *   </tr>
 258  * </table>
 259  *
 260  * <p><strong>Warning:</strong> Serialized objects of this class will
 261  * not be compatible with future Swing releases. The current
 262  * serialization support is appropriate for short term storage or RMI
 263  * between applications running the same version of Swing.  As of 1.4,
 264  * support for long term storage of all JavaBeans&trade;
 265  * has been added to the
 266  * <code>java.beans</code> package.  Please see {@link
 267  * java.beans.XMLEncoder}.</p>
 268  *
 269  * @author  Timothy Prinzing
 270  * @author  Scott Violet
 271  * @author  Sunita Mani
 272  */
 273 @SuppressWarnings("serial") // Same-version serialization only
 274 public class HTMLDocument extends DefaultStyledDocument {
 275     /**
 276      * Constructs an HTML document using the default buffer size
 277      * and a default <code>StyleSheet</code>.  This is a convenience
 278      * method for the constructor
 279      * <code>HTMLDocument(Content, StyleSheet)</code>.
 280      */
 281     public HTMLDocument() {
 282         this(new GapContent(BUFFER_SIZE_DEFAULT), new StyleSheet());
 283     }
 284 
 285     /**
 286      * Constructs an HTML document with the default content
 287      * storage implementation and the specified style/attribute
 288      * storage mechanism.  This is a convenience method for the
 289      * constructor
 290      * <code>HTMLDocument(Content, StyleSheet)</code>.
 291      *
 292      * @param styles  the styles
 293      */
 294     public HTMLDocument(StyleSheet styles) {
 295         this(new GapContent(BUFFER_SIZE_DEFAULT), styles);
 296     }
 297 
 298     /**
 299      * Constructs an HTML document with the given content
 300      * storage implementation and the given style/attribute
 301      * storage mechanism.
 302      *
 303      * @param c  the container for the content
 304      * @param styles the styles
 305      */
 306     public HTMLDocument(Content c, StyleSheet styles) {
 307         super(c, styles);
 308     }
 309 
 310     /**
 311      * Fetches the reader for the parser to use when loading the document
 312      * with HTML.  This is implemented to return an instance of
 313      * <code>HTMLDocument.HTMLReader</code>.
 314      * Subclasses can reimplement this
 315      * method to change how the document gets structured if desired.
 316      * (For example, to handle custom tags, or structurally represent character
 317      * style elements.)
 318      *
 319      * @param pos the starting position
 320      * @return the reader used by the parser to load the document
 321      */
 322     public HTMLEditorKit.ParserCallback getReader(int pos) {
 323         Object desc = getProperty(Document.StreamDescriptionProperty);
 324         if (desc instanceof URL) {
 325             setBase((URL)desc);
 326         }
 327         HTMLReader reader = new HTMLReader(pos);
 328         return reader;
 329     }
 330 
 331     /**
 332      * Returns the reader for the parser to use to load the document
 333      * with HTML.  This is implemented to return an instance of
 334      * <code>HTMLDocument.HTMLReader</code>.
 335      * Subclasses can reimplement this
 336      * method to change how the document gets structured if desired.
 337      * (For example, to handle custom tags, or structurally represent character
 338      * style elements.)
 339      * <p>This is a convenience method for
 340      * <code>getReader(int, int, int, HTML.Tag, TRUE)</code>.
 341      *
 342      * @param pos the starting position
 343      * @param popDepth   the number of <code>ElementSpec.EndTagTypes</code>
 344      *          to generate before inserting
 345      * @param pushDepth  the number of <code>ElementSpec.StartTagTypes</code>
 346      *          with a direction of <code>ElementSpec.JoinNextDirection</code>
 347      *          that should be generated before inserting,
 348      *          but after the end tags have been generated
 349      * @param insertTag  the first tag to start inserting into document
 350      * @return the reader used by the parser to load the document
 351      */
 352     public HTMLEditorKit.ParserCallback getReader(int pos, int popDepth,
 353                                                   int pushDepth,
 354                                                   HTML.Tag insertTag) {
 355         return getReader(pos, popDepth, pushDepth, insertTag, true);
 356     }
 357 
 358     /**
 359      * Fetches the reader for the parser to use to load the document
 360      * with HTML.  This is implemented to return an instance of
 361      * HTMLDocument.HTMLReader.  Subclasses can reimplement this
 362      * method to change how the document get structured if desired
 363      * (e.g. to handle custom tags, structurally represent character
 364      * style elements, etc.).
 365      *
 366      * @param popDepth   the number of <code>ElementSpec.EndTagTypes</code>
 367      *          to generate before inserting
 368      * @param pushDepth  the number of <code>ElementSpec.StartTagTypes</code>
 369      *          with a direction of <code>ElementSpec.JoinNextDirection</code>
 370      *          that should be generated before inserting,
 371      *          but after the end tags have been generated
 372      * @param insertTag  the first tag to start inserting into document
 373      * @param insertInsertTag  false if all the Elements after insertTag should
 374      *        be inserted; otherwise insertTag will be inserted
 375      * @return the reader used by the parser to load the document
 376      */
 377     HTMLEditorKit.ParserCallback getReader(int pos, int popDepth,
 378                                            int pushDepth,
 379                                            HTML.Tag insertTag,
 380                                            boolean insertInsertTag) {
 381         Object desc = getProperty(Document.StreamDescriptionProperty);
 382         if (desc instanceof URL) {
 383             setBase((URL)desc);
 384         }
 385         HTMLReader reader = new HTMLReader(pos, popDepth, pushDepth,
 386                                            insertTag, insertInsertTag, false,
 387                                            true);
 388         return reader;
 389     }
 390 
 391     /**
 392      * Returns the location to resolve relative URLs against.  By
 393      * default this will be the document's URL if the document
 394      * was loaded from a URL.  If a base tag is found and
 395      * can be parsed, it will be used as the base location.
 396      *
 397      * @return the base location
 398      */
 399     public URL getBase() {
 400         return base;
 401     }
 402 
 403     /**
 404      * Sets the location to resolve relative URLs against.  By
 405      * default this will be the document's URL if the document
 406      * was loaded from a URL.  If a base tag is found and
 407      * can be parsed, it will be used as the base location.
 408      * <p>This also sets the base of the <code>StyleSheet</code>
 409      * to be <code>u</code> as well as the base of the document.
 410      *
 411      * @param u  the desired base URL
 412      */
 413     public void setBase(URL u) {
 414         base = u;
 415         getStyleSheet().setBase(u);
 416     }
 417 
 418     /**
 419      * Inserts new elements in bulk.  This is how elements get created
 420      * in the document.  The parsing determines what structure is needed
 421      * and creates the specification as a set of tokens that describe the
 422      * edit while leaving the document free of a write-lock.  This method
 423      * can then be called in bursts by the reader to acquire a write-lock
 424      * for a shorter duration (i.e. while the document is actually being
 425      * altered).
 426      *
 427      * @param offset the starting offset
 428      * @param data the element data
 429      * @exception BadLocationException  if the given position does not
 430      *   represent a valid location in the associated document.
 431      */
 432     protected void insert(int offset, ElementSpec[] data) throws BadLocationException {
 433         super.insert(offset, data);
 434     }
 435 
 436     /**
 437      * Updates document structure as a result of text insertion.  This
 438      * will happen within a write lock.  This implementation simply
 439      * parses the inserted content for line breaks and builds up a set
 440      * of instructions for the element buffer.
 441      *
 442      * @param chng a description of the document change
 443      * @param attr the attributes
 444      */
 445     protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
 446         if(attr == null) {
 447             attr = contentAttributeSet;
 448         }
 449 
 450         // If this is the composed text element, merge the content attribute to it
 451         else if (attr.isDefined(StyleConstants.ComposedTextAttribute)) {
 452             ((MutableAttributeSet)attr).addAttributes(contentAttributeSet);
 453         }
 454 
 455         if (attr.isDefined(IMPLIED_CR)) {
 456             ((MutableAttributeSet)attr).removeAttribute(IMPLIED_CR);
 457         }
 458 
 459         super.insertUpdate(chng, attr);
 460     }
 461 
 462     /**
 463      * Replaces the contents of the document with the given
 464      * element specifications.  This is called before insert if
 465      * the loading is done in bursts.  This is the only method called
 466      * if loading the document entirely in one burst.
 467      *
 468      * @param data  the new contents of the document
 469      */
 470     protected void create(ElementSpec[] data) {
 471         super.create(data);
 472     }
 473 
 474     /**
 475      * Sets attributes for a paragraph.
 476      * <p>
 477      * This method is thread safe, although most Swing methods
 478      * are not. Please see
 479      * <A HREF="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency
 480      * in Swing</A> for more information.
 481      *
 482      * @param offset the offset into the paragraph (must be at least 0)
 483      * @param length the number of characters affected (must be at least 0)
 484      * @param s the attributes
 485      * @param replace whether to replace existing attributes, or merge them
 486      */
 487     public void setParagraphAttributes(int offset, int length, AttributeSet s,
 488                                        boolean replace) {
 489         try {
 490             writeLock();
 491             // Make sure we send out a change for the length of the paragraph.
 492             int end = Math.min(offset + length, getLength());
 493             Element e = getParagraphElement(offset);
 494             offset = e.getStartOffset();
 495             e = getParagraphElement(end);
 496             length = Math.max(0, e.getEndOffset() - offset);
 497             DefaultDocumentEvent changes =
 498                 new DefaultDocumentEvent(offset, length,
 499                                          DocumentEvent.EventType.CHANGE);
 500             AttributeSet sCopy = s.copyAttributes();
 501             int lastEnd = Integer.MAX_VALUE;
 502             for (int pos = offset; pos <= end; pos = lastEnd) {
 503                 Element paragraph = getParagraphElement(pos);
 504                 if (lastEnd == paragraph.getEndOffset()) {
 505                     lastEnd++;
 506                 }
 507                 else {
 508                     lastEnd = paragraph.getEndOffset();
 509                 }
 510                 MutableAttributeSet attr =
 511                     (MutableAttributeSet) paragraph.getAttributes();
 512                 changes.addEdit(new AttributeUndoableEdit(paragraph, sCopy, replace));
 513                 if (replace) {
 514                     attr.removeAttributes(attr);
 515                 }
 516                 attr.addAttributes(s);
 517             }
 518             changes.end();
 519             fireChangedUpdate(changes);
 520             fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
 521         } finally {
 522             writeUnlock();
 523         }
 524     }
 525 
 526     /**
 527      * Fetches the <code>StyleSheet</code> with the document-specific display
 528      * rules (CSS) that were specified in the HTML document itself.
 529      *
 530      * @return the <code>StyleSheet</code>
 531      */
 532     public StyleSheet getStyleSheet() {
 533         return (StyleSheet) getAttributeContext();
 534     }
 535 
 536     /**
 537      * Fetches an iterator for the specified HTML tag.
 538      * This can be used for things like iterating over the
 539      * set of anchors contained, or iterating over the input
 540      * elements.
 541      *
 542      * @param t the requested <code>HTML.Tag</code>
 543      * @return the <code>Iterator</code> for the given HTML tag
 544      * @see javax.swing.text.html.HTML.Tag
 545      */
 546     public Iterator getIterator(HTML.Tag t) {
 547         if (t.isBlock()) {
 548             // TBD
 549             return null;
 550         }
 551         return new LeafIterator(t, this);
 552     }
 553 
 554     /**
 555      * Creates a document leaf element that directly represents
 556      * text (doesn't have any children).  This is implemented
 557      * to return an element of type
 558      * <code>HTMLDocument.RunElement</code>.
 559      *
 560      * @param parent the parent element
 561      * @param a the attributes for the element
 562      * @param p0 the beginning of the range (must be at least 0)
 563      * @param p1 the end of the range (must be at least p0)
 564      * @return the new element
 565      */
 566     protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1) {
 567         return new RunElement(parent, a, p0, p1);
 568     }
 569 
 570     /**
 571      * Creates a document branch element, that can contain other elements.
 572      * This is implemented to return an element of type
 573      * <code>HTMLDocument.BlockElement</code>.
 574      *
 575      * @param parent the parent element
 576      * @param a the attributes
 577      * @return the element
 578      */
 579     protected Element createBranchElement(Element parent, AttributeSet a) {
 580         return new BlockElement(parent, a);
 581     }
 582 
 583     /**
 584      * Creates the root element to be used to represent the
 585      * default document structure.
 586      *
 587      * @return the element base
 588      */
 589     protected AbstractElement createDefaultRoot() {
 590         // grabs a write-lock for this initialization and
 591         // abandon it during initialization so in normal
 592         // operation we can detect an illegitimate attempt
 593         // to mutate attributes.
 594         writeLock();
 595         MutableAttributeSet a = new SimpleAttributeSet();
 596         a.addAttribute(StyleConstants.NameAttribute, HTML.Tag.HTML);
 597         BlockElement html = new BlockElement(null, a.copyAttributes());
 598         a.removeAttributes(a);
 599         a.addAttribute(StyleConstants.NameAttribute, HTML.Tag.BODY);
 600         BlockElement body = new BlockElement(html, a.copyAttributes());
 601         a.removeAttributes(a);
 602         a.addAttribute(StyleConstants.NameAttribute, HTML.Tag.P);
 603         getStyleSheet().addCSSAttributeFromHTML(a, CSS.Attribute.MARGIN_TOP, "0");
 604         BlockElement paragraph = new BlockElement(body, a.copyAttributes());
 605         a.removeAttributes(a);
 606         a.addAttribute(StyleConstants.NameAttribute, HTML.Tag.CONTENT);
 607         RunElement brk = new RunElement(paragraph, a, 0, 1);
 608         Element[] buff = new Element[1];
 609         buff[0] = brk;
 610         paragraph.replace(0, 0, buff);
 611         buff[0] = paragraph;
 612         body.replace(0, 0, buff);
 613         buff[0] = body;
 614         html.replace(0, 0, buff);
 615         writeUnlock();
 616         return html;
 617     }
 618 
 619     /**
 620      * Sets the number of tokens to buffer before trying to update
 621      * the documents element structure.
 622      *
 623      * @param n  the number of tokens to buffer
 624      */
 625     public void setTokenThreshold(int n) {
 626         putProperty(TokenThreshold, new Integer(n));
 627     }
 628 
 629     /**
 630      * Gets the number of tokens to buffer before trying to update
 631      * the documents element structure.  The default value is
 632      * <code>Integer.MAX_VALUE</code>.
 633      *
 634      * @return the number of tokens to buffer
 635      */
 636     public int getTokenThreshold() {
 637         Integer i = (Integer) getProperty(TokenThreshold);
 638         if (i != null) {
 639             return i.intValue();
 640         }
 641         return Integer.MAX_VALUE;
 642     }
 643 
 644     /**
 645      * Determines how unknown tags are handled by the parser.
 646      * If set to true, unknown
 647      * tags are put in the model, otherwise they are dropped.
 648      *
 649      * @param preservesTags  true if unknown tags should be
 650      *          saved in the model, otherwise tags are dropped
 651      * @see javax.swing.text.html.HTML.Tag
 652      */
 653     public void setPreservesUnknownTags(boolean preservesTags) {
 654         preservesUnknownTags = preservesTags;
 655     }
 656 
 657     /**
 658      * Returns the behavior the parser observes when encountering
 659      * unknown tags.
 660      *
 661      * @see javax.swing.text.html.HTML.Tag
 662      * @return true if unknown tags are to be preserved when parsing
 663      */
 664     public boolean getPreservesUnknownTags() {
 665         return preservesUnknownTags;
 666     }
 667 
 668     /**
 669      * Processes <code>HyperlinkEvents</code> that
 670      * are generated by documents in an HTML frame.
 671      * The <code>HyperlinkEvent</code> type, as the parameter suggests,
 672      * is <code>HTMLFrameHyperlinkEvent</code>.
 673      * In addition to the typical information contained in a
 674      * <code>HyperlinkEvent</code>,
 675      * this event contains the element that corresponds to the frame in
 676      * which the click happened (the source element) and the
 677      * target name.  The target name has 4 possible values:
 678      * <ul>
 679      * <li>  _self
 680      * <li>  _parent
 681      * <li>  _top
 682      * <li>  a named frame
 683      * </ul>
 684      *
 685      * If target is _self, the action is to change the value of the
 686      * <code>HTML.Attribute.SRC</code> attribute and fires a
 687      * <code>ChangedUpdate</code> event.
 688      *<p>
 689      * If the target is _parent, then it deletes the parent element,
 690      * which is a &lt;FRAMESET&gt; element, and inserts a new &lt;FRAME&gt;
 691      * element, and sets its <code>HTML.Attribute.SRC</code> attribute
 692      * to have a value equal to the destination URL and fire a
 693      * <code>RemovedUpdate</code> and <code>InsertUpdate</code>.
 694      *<p>
 695      * If the target is _top, this method does nothing. In the implementation
 696      * of the view for a frame, namely the <code>FrameView</code>,
 697      * the processing of _top is handled.  Given that _top implies
 698      * replacing the entire document, it made sense to handle this outside
 699      * of the document that it will replace.
 700      *<p>
 701      * If the target is a named frame, then the element hierarchy is searched
 702      * for an element with a name equal to the target, its
 703      * <code>HTML.Attribute.SRC</code> attribute is updated and a
 704      * <code>ChangedUpdate</code> event is fired.
 705      *
 706      * @param e the event
 707      */
 708     public void processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent e) {
 709         String frameName = e.getTarget();
 710         Element element = e.getSourceElement();
 711         String urlStr = e.getURL().toString();
 712 
 713         if (frameName.equals("_self")) {
 714             /*
 715               The source and destination elements
 716               are the same.
 717             */
 718             updateFrame(element, urlStr);
 719         } else if (frameName.equals("_parent")) {
 720             /*
 721               The destination is the parent of the frame.
 722             */
 723             updateFrameSet(element.getParentElement(), urlStr);
 724         } else {
 725             /*
 726               locate a named frame
 727             */
 728             Element targetElement = findFrame(frameName);
 729             if (targetElement != null) {
 730                 updateFrame(targetElement, urlStr);
 731             }
 732         }
 733     }
 734 
 735 
 736     /**
 737      * Searches the element hierarchy for an FRAME element
 738      * that has its name attribute equal to the <code>frameName</code>.
 739      *
 740      * @param frameName
 741      * @return the element whose NAME attribute has a value of
 742      *          <code>frameName</code>; returns <code>null</code>
 743      *          if not found
 744      */
 745     private Element findFrame(String frameName) {
 746         ElementIterator it = new ElementIterator(this);
 747         Element next;
 748 
 749         while ((next = it.next()) != null) {
 750             AttributeSet attr = next.getAttributes();
 751             if (matchNameAttribute(attr, HTML.Tag.FRAME)) {
 752                 String frameTarget = (String)attr.getAttribute(HTML.Attribute.NAME);
 753                 if (frameTarget != null && frameTarget.equals(frameName)) {
 754                     break;
 755                 }
 756             }
 757         }
 758         return next;
 759     }
 760 
 761     /**
 762      * Returns true if <code>StyleConstants.NameAttribute</code> is
 763      * equal to the tag that is passed in as a parameter.
 764      *
 765      * @param attr the attributes to be matched
 766      * @param tag the value to be matched
 767      * @return true if there is a match, false otherwise
 768      * @see javax.swing.text.html.HTML.Attribute
 769      */
 770     static boolean matchNameAttribute(AttributeSet attr, HTML.Tag tag) {
 771         Object o = attr.getAttribute(StyleConstants.NameAttribute);
 772         if (o instanceof HTML.Tag) {
 773             HTML.Tag name = (HTML.Tag) o;
 774             if (name == tag) {
 775                 return true;
 776             }
 777         }
 778         return false;
 779     }
 780 
 781     /**
 782      * Replaces a frameset branch Element with a frame leaf element.
 783      *
 784      * @param element the frameset element to remove
 785      * @param url     the value for the SRC attribute for the
 786      *                new frame that will replace the frameset
 787      */
 788     private void updateFrameSet(Element element, String url) {
 789         try {
 790             int startOffset = element.getStartOffset();
 791             int endOffset = Math.min(getLength(), element.getEndOffset());
 792             String html = "<frame";
 793             if (url != null) {
 794                 html += " src=\"" + url + "\"";
 795             }
 796             html += ">";
 797             installParserIfNecessary();
 798             setOuterHTML(element, html);
 799         } catch (BadLocationException e1) {
 800             // Should handle this better
 801         } catch (IOException ioe) {
 802             // Should handle this better
 803         }
 804     }
 805 
 806 
 807     /**
 808      * Updates the Frame elements <code>HTML.Attribute.SRC attribute</code>
 809      * and fires a <code>ChangedUpdate</code> event.
 810      *
 811      * @param element a FRAME element whose SRC attribute will be updated
 812      * @param url     a string specifying the new value for the SRC attribute
 813      */
 814     private void updateFrame(Element element, String url) {
 815 
 816         try {
 817             writeLock();
 818             DefaultDocumentEvent changes = new DefaultDocumentEvent(element.getStartOffset(),
 819                                                                     1,
 820                                                                     DocumentEvent.EventType.CHANGE);
 821             AttributeSet sCopy = element.getAttributes().copyAttributes();
 822             MutableAttributeSet attr = (MutableAttributeSet) element.getAttributes();
 823             changes.addEdit(new AttributeUndoableEdit(element, sCopy, false));
 824             attr.removeAttribute(HTML.Attribute.SRC);
 825             attr.addAttribute(HTML.Attribute.SRC, url);
 826             changes.end();
 827             fireChangedUpdate(changes);
 828             fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
 829         } finally {
 830             writeUnlock();
 831         }
 832     }
 833 
 834 
 835     /**
 836      * Returns true if the document will be viewed in a frame.
 837      * @return true if document will be viewed in a frame, otherwise false
 838      */
 839     boolean isFrameDocument() {
 840         return frameDocument;
 841     }
 842 
 843     /**
 844      * Sets a boolean state about whether the document will be
 845      * viewed in a frame.
 846      * @param frameDoc  true if the document will be viewed in a frame,
 847      *          otherwise false
 848      */
 849     void setFrameDocumentState(boolean frameDoc) {
 850         this.frameDocument = frameDoc;
 851     }
 852 
 853     /**
 854      * Adds the specified map, this will remove a Map that has been
 855      * previously registered with the same name.
 856      *
 857      * @param map  the <code>Map</code> to be registered
 858      */
 859     void addMap(Map map) {
 860         String     name = map.getName();
 861 
 862         if (name != null) {
 863             Object     maps = getProperty(MAP_PROPERTY);
 864 
 865             if (maps == null) {
 866                 maps = new Hashtable<>(11);
 867                 putProperty(MAP_PROPERTY, maps);
 868             }
 869             if (maps instanceof Hashtable) {
 870                 @SuppressWarnings("unchecked")
 871                 Hashtable<Object, Object> tmp = (Hashtable)maps;
 872                 tmp.put("#" + name, map);
 873             }
 874         }
 875     }
 876 
 877     /**
 878      * Removes a previously registered map.
 879      * @param map the <code>Map</code> to be removed
 880      */
 881     void removeMap(Map map) {
 882         String     name = map.getName();
 883 
 884         if (name != null) {
 885             Object     maps = getProperty(MAP_PROPERTY);
 886 
 887             if (maps instanceof Hashtable) {
 888                 ((Hashtable)maps).remove("#" + name);
 889             }
 890         }
 891     }
 892 
 893     /**
 894      * Returns the Map associated with the given name.
 895      * @param name the name of the desired <code>Map</code>
 896      * @return the <code>Map</code> or <code>null</code> if it can't
 897      *          be found, or if <code>name</code> is <code>null</code>
 898      */
 899     Map getMap(String name) {
 900         if (name != null) {
 901             Object     maps = getProperty(MAP_PROPERTY);
 902 
 903             if (maps != null && (maps instanceof Hashtable)) {
 904                 return (Map)((Hashtable)maps).get(name);
 905             }
 906         }
 907         return null;
 908     }
 909 
 910     /**
 911      * Returns an <code>Enumeration</code> of the possible Maps.
 912      * @return the enumerated list of maps, or <code>null</code>
 913      *          if the maps are not an instance of <code>Hashtable</code>
 914      */
 915     Enumeration<Object> getMaps() {
 916         Object     maps = getProperty(MAP_PROPERTY);
 917 
 918         if (maps instanceof Hashtable) {
 919             @SuppressWarnings("unchecked")
 920             Hashtable<Object, Object> tmp = (Hashtable) maps;
 921             return tmp.elements();
 922         }
 923         return null;
 924     }
 925 
 926     /**
 927      * Sets the content type language used for style sheets that do not
 928      * explicitly specify the type. The default is text/css.
 929      * @param contentType  the content type language for the style sheets
 930      */
 931     /* public */
 932     void setDefaultStyleSheetType(String contentType) {
 933         putProperty(StyleType, contentType);
 934     }
 935 
 936     /**
 937      * Returns the content type language used for style sheets. The default
 938      * is text/css.
 939      * @return the content type language used for the style sheets
 940      */
 941     /* public */
 942     String getDefaultStyleSheetType() {
 943         String retValue = (String)getProperty(StyleType);
 944         if (retValue == null) {
 945             return "text/css";
 946         }
 947         return retValue;
 948     }
 949 
 950     /**
 951      * Sets the parser that is used by the methods that insert html
 952      * into the existing document, such as <code>setInnerHTML</code>,
 953      * and <code>setOuterHTML</code>.
 954      * <p>
 955      * <code>HTMLEditorKit.createDefaultDocument</code> will set the parser
 956      * for you. If you create an <code>HTMLDocument</code> by hand,
 957      * be sure and set the parser accordingly.
 958      * @param parser the parser to be used for text insertion
 959      *
 960      * @since 1.3
 961      */
 962     public void setParser(HTMLEditorKit.Parser parser) {
 963         this.parser = parser;
 964         putProperty("__PARSER__", null);
 965     }
 966 
 967     /**
 968      * Returns the parser that is used when inserting HTML into the existing
 969      * document.
 970      * @return the parser used for text insertion
 971      *
 972      * @since 1.3
 973      */
 974     public HTMLEditorKit.Parser getParser() {
 975         Object p = getProperty("__PARSER__");
 976 
 977         if (p instanceof HTMLEditorKit.Parser) {
 978             return (HTMLEditorKit.Parser)p;
 979         }
 980         return parser;
 981     }
 982 
 983     /**
 984      * Replaces the children of the given element with the contents
 985      * specified as an HTML string.
 986      *
 987      * <p>This will be seen as at least two events, n inserts followed by
 988      * a remove.</p>
 989      *
 990      * <p>Consider the following structure (the <code>elem</code>
 991      * parameter is <b>in bold</b>).</p>
 992      *
 993      * <pre>
 994      *     &lt;body&gt;
 995      *       |
 996      *     <b>&lt;div&gt;</b>
 997      *      /  \
 998      *    &lt;p&gt;   &lt;p&gt;
 999      * </pre>
1000      *
1001      * <p>Invoking <code>setInnerHTML(elem, "&lt;ul&gt;&lt;li&gt;")</code>
1002      * results in the following structure (new elements are <font
1003      * style="color: red;">in red</font>).</p>
1004      *
1005      * <pre>
1006      *     &lt;body&gt;
1007      *       |
1008      *     <b>&lt;div&gt;</b>
1009      *         \
1010      *         <font style="color: red;">&lt;ul&gt;</font>
1011      *           \
1012      *           <font style="color: red;">&lt;li&gt;</font>
1013      * </pre>
1014      *
1015      * <p>Parameter <code>elem</code> must not be a leaf element,
1016      * otherwise an <code>IllegalArgumentException</code> is thrown.
1017      * If either <code>elem</code> or <code>htmlText</code> parameter
1018      * is <code>null</code>, no changes are made to the document.</p>
1019      *
1020      * <p>For this to work correctly, the document must have an
1021      * <code>HTMLEditorKit.Parser</code> set. This will be the case
1022      * if the document was created from an HTMLEditorKit via the
1023      * <code>createDefaultDocument</code> method.</p>
1024      *
1025      * @param elem the branch element whose children will be replaced
1026      * @param htmlText the string to be parsed and assigned to <code>elem</code>
1027      * @throws IllegalArgumentException if <code>elem</code> is a leaf
1028      * @throws IllegalStateException if an <code>HTMLEditorKit.Parser</code>
1029      *         has not been defined
1030      * @throws BadLocationException if replacement is impossible because of
1031      *         a structural issue
1032      * @throws IOException if an I/O exception occurs
1033      * @since 1.3
1034      */
1035     public void setInnerHTML(Element elem, String htmlText) throws
1036                              BadLocationException, IOException {
1037         verifyParser();
1038         if (elem != null && elem.isLeaf()) {
1039             throw new IllegalArgumentException
1040                 ("Can not set inner HTML of a leaf");
1041         }
1042         if (elem != null && htmlText != null) {
1043             int oldCount = elem.getElementCount();
1044             int insertPosition = elem.getStartOffset();
1045             insertHTML(elem, elem.getStartOffset(), htmlText, true);
1046             if (elem.getElementCount() > oldCount) {
1047                 // Elements were inserted, do the cleanup.
1048                 removeElements(elem, elem.getElementCount() - oldCount,
1049                                oldCount);
1050             }
1051         }
1052     }
1053 
1054     /**
1055      * Replaces the given element in the parent with the contents
1056      * specified as an HTML string.
1057      *
1058      * <p>This will be seen as at least two events, n inserts followed by
1059      * a remove.</p>
1060      *
1061      * <p>When replacing a leaf this will attempt to make sure there is
1062      * a newline present if one is needed. This may result in an additional
1063      * element being inserted. Consider, if you were to replace a character
1064      * element that contained a newline with &lt;img&gt; this would create
1065      * two elements, one for the image, and one for the newline.</p>
1066      *
1067      * <p>If you try to replace the element at length you will most
1068      * likely end up with two elements, eg
1069      * <code>setOuterHTML(getCharacterElement (getLength()),
1070      * "blah")</code> will result in two leaf elements at the end, one
1071      * representing 'blah', and the other representing the end
1072      * element.</p>
1073      *
1074      * <p>Consider the following structure (the <code>elem</code>
1075      * parameter is <b>in bold</b>).</p>
1076      *
1077      * <pre>
1078      *     &lt;body&gt;
1079      *       |
1080      *     <b>&lt;div&gt;</b>
1081      *      /  \
1082      *    &lt;p&gt;   &lt;p&gt;
1083      * </pre>
1084      *
1085      * <p>Invoking <code>setOuterHTML(elem, "&lt;ul&gt;&lt;li&gt;")</code>
1086      * results in the following structure (new elements are <font
1087      * style="color: red;">in red</font>).</p>
1088      *
1089      * <pre>
1090      *    &lt;body&gt;
1091      *      |
1092      *     <font style="color: red;">&lt;ul&gt;</font>
1093      *       \
1094      *       <font style="color: red;">&lt;li&gt;</font>
1095      * </pre>
1096      *
1097      * <p>If either <code>elem</code> or <code>htmlText</code>
1098      * parameter is <code>null</code>, no changes are made to the
1099      * document.</p>
1100      *
1101      * <p>For this to work correctly, the document must have an
1102      * HTMLEditorKit.Parser set. This will be the case if the document
1103      * was created from an HTMLEditorKit via the
1104      * <code>createDefaultDocument</code> method.</p>
1105      *
1106      * @param elem the element to replace
1107      * @param htmlText the string to be parsed and inserted in place of <code>elem</code>
1108      * @throws IllegalStateException if an HTMLEditorKit.Parser has not
1109      *         been set
1110      * @throws BadLocationException if replacement is impossible because of
1111      *         a structural issue
1112      * @throws IOException if an I/O exception occurs
1113      * @since 1.3
1114      */
1115     public void setOuterHTML(Element elem, String htmlText) throws
1116                             BadLocationException, IOException {
1117         verifyParser();
1118         if (elem != null && elem.getParentElement() != null &&
1119             htmlText != null) {
1120             int start = elem.getStartOffset();
1121             int end = elem.getEndOffset();
1122             int startLength = getLength();
1123             // We don't want a newline if elem is a leaf, and doesn't contain
1124             // a newline.
1125             boolean wantsNewline = !elem.isLeaf();
1126             if (!wantsNewline && (end > startLength ||
1127                                  getText(end - 1, 1).charAt(0) == NEWLINE[0])){
1128                 wantsNewline = true;
1129             }
1130             Element parent = elem.getParentElement();
1131             int oldCount = parent.getElementCount();
1132             insertHTML(parent, start, htmlText, wantsNewline);
1133             // Remove old.
1134             int newLength = getLength();
1135             if (oldCount != parent.getElementCount()) {
1136                 int removeIndex = parent.getElementIndex(start + newLength -
1137                                                          startLength);
1138                 removeElements(parent, removeIndex, 1);
1139             }
1140         }
1141     }
1142 
1143     /**
1144      * Inserts the HTML specified as a string at the start
1145      * of the element.
1146      *
1147      * <p>Consider the following structure (the <code>elem</code>
1148      * parameter is <b>in bold</b>).</p>
1149      *
1150      * <pre>
1151      *     &lt;body&gt;
1152      *       |
1153      *     <b>&lt;div&gt;</b>
1154      *      /  \
1155      *    &lt;p&gt;   &lt;p&gt;
1156      * </pre>
1157      *
1158      * <p>Invoking <code>insertAfterStart(elem,
1159      * "&lt;ul&gt;&lt;li&gt;")</code> results in the following structure
1160      * (new elements are <font style="color: red;">in red</font>).</p>
1161      *
1162      * <pre>
1163      *        &lt;body&gt;
1164      *          |
1165      *        <b>&lt;div&gt;</b>
1166      *       /  |  \
1167      *    <font style="color: red;">&lt;ul&gt;</font> &lt;p&gt; &lt;p&gt;
1168      *     /
1169      *  <font style="color: red;">&lt;li&gt;</font>
1170      * </pre>
1171      *
1172      * <p>Unlike the <code>insertBeforeStart</code> method, new
1173      *  elements become <em>children</em> of the specified element,
1174      *  not siblings.</p>
1175      *
1176      * <p>Parameter <code>elem</code> must not be a leaf element,
1177      * otherwise an <code>IllegalArgumentException</code> is thrown.
1178      * If either <code>elem</code> or <code>htmlText</code> parameter
1179      * is <code>null</code>, no changes are made to the document.</p>
1180      *
1181      * <p>For this to work correctly, the document must have an
1182      * <code>HTMLEditorKit.Parser</code> set. This will be the case
1183      * if the document was created from an HTMLEditorKit via the
1184      * <code>createDefaultDocument</code> method.</p>
1185      *
1186      * @param elem the branch element to be the root for the new text
1187      * @param htmlText the string to be parsed and assigned to <code>elem</code>
1188      * @throws IllegalArgumentException if <code>elem</code> is a leaf
1189      * @throws IllegalStateException if an HTMLEditorKit.Parser has not
1190      *         been set on the document
1191      * @throws BadLocationException if insertion is impossible because of
1192      *         a structural issue
1193      * @throws IOException if an I/O exception occurs
1194      * @since 1.3
1195      */
1196     public void insertAfterStart(Element elem, String htmlText) throws
1197                                  BadLocationException, IOException {
1198         verifyParser();
1199 
1200         if (elem == null || htmlText == null) {
1201             return;
1202         }
1203 
1204         if (elem.isLeaf()) {
1205             throw new IllegalArgumentException
1206                 ("Can not insert HTML after start of a leaf");
1207         }
1208         insertHTML(elem, elem.getStartOffset(), htmlText, false);
1209     }
1210 
1211     /**
1212      * Inserts the HTML specified as a string at the end of
1213      * the element.
1214      *
1215      * <p> If <code>elem</code>'s children are leaves, and the
1216      * character at a <code>elem.getEndOffset() - 1</code> is a newline,
1217      * this will insert before the newline so that there isn't text after
1218      * the newline.</p>
1219      *
1220      * <p>Consider the following structure (the <code>elem</code>
1221      * parameter is <b>in bold</b>).</p>
1222      *
1223      * <pre>
1224      *     &lt;body&gt;
1225      *       |
1226      *     <b>&lt;div&gt;</b>
1227      *      /  \
1228      *    &lt;p&gt;   &lt;p&gt;
1229      * </pre>
1230      *
1231      * <p>Invoking <code>insertBeforeEnd(elem, "&lt;ul&gt;&lt;li&gt;")</code>
1232      * results in the following structure (new elements are <font
1233      * style="color: red;">in red</font>).</p>
1234      *
1235      * <pre>
1236      *        &lt;body&gt;
1237      *          |
1238      *        <b>&lt;div&gt;</b>
1239      *       /  |  \
1240      *     &lt;p&gt; &lt;p&gt; <font style="color: red;">&lt;ul&gt;</font>
1241      *               \
1242      *               <font style="color: red;">&lt;li&gt;</font>
1243      * </pre>
1244      *
1245      * <p>Unlike the <code>insertAfterEnd</code> method, new elements
1246      * become <em>children</em> of the specified element, not
1247      * siblings.</p>
1248      *
1249      * <p>Parameter <code>elem</code> must not be a leaf element,
1250      * otherwise an <code>IllegalArgumentException</code> is thrown.
1251      * If either <code>elem</code> or <code>htmlText</code> parameter
1252      * is <code>null</code>, no changes are made to the document.</p>
1253      *
1254      * <p>For this to work correctly, the document must have an
1255      * <code>HTMLEditorKit.Parser</code> set. This will be the case
1256      * if the document was created from an HTMLEditorKit via the
1257      * <code>createDefaultDocument</code> method.</p>
1258      *
1259      * @param elem the element to be the root for the new text
1260      * @param htmlText the string to be parsed and assigned to <code>elem</code>
1261      * @throws IllegalArgumentException if <code>elem</code> is a leaf
1262      * @throws IllegalStateException if an HTMLEditorKit.Parser has not
1263      *         been set on the document
1264      * @throws BadLocationException if insertion is impossible because of
1265      *         a structural issue
1266      * @throws IOException if an I/O exception occurs
1267      * @since 1.3
1268      */
1269     public void insertBeforeEnd(Element elem, String htmlText) throws
1270                                 BadLocationException, IOException {
1271         verifyParser();
1272         if (elem != null && elem.isLeaf()) {
1273             throw new IllegalArgumentException
1274                 ("Can not set inner HTML before end of leaf");
1275         }
1276         if (elem != null) {
1277             int offset = elem.getEndOffset();
1278             if (elem.getElement(elem.getElementIndex(offset - 1)).isLeaf() &&
1279                 getText(offset - 1, 1).charAt(0) == NEWLINE[0]) {
1280                 offset--;
1281             }
1282             insertHTML(elem, offset, htmlText, false);
1283         }
1284     }
1285 
1286     /**
1287      * Inserts the HTML specified as a string before the start of
1288      * the given element.
1289      *
1290      * <p>Consider the following structure (the <code>elem</code>
1291      * parameter is <b>in bold</b>).</p>
1292      *
1293      * <pre>
1294      *     &lt;body&gt;
1295      *       |
1296      *     <b>&lt;div&gt;</b>
1297      *      /  \
1298      *    &lt;p&gt;   &lt;p&gt;
1299      * </pre>
1300      *
1301      * <p>Invoking <code>insertBeforeStart(elem,
1302      * "&lt;ul&gt;&lt;li&gt;")</code> results in the following structure
1303      * (new elements are <font style="color: red;">in red</font>).</p>
1304      *
1305      * <pre>
1306      *        &lt;body&gt;
1307      *         /  \
1308      *      <font style="color: red;">&lt;ul&gt;</font> <b>&lt;div&gt;</b>
1309      *       /    /  \
1310      *     <font style="color: red;">&lt;li&gt;</font> &lt;p&gt;  &lt;p&gt;
1311      * </pre>
1312      *
1313      * <p>Unlike the <code>insertAfterStart</code> method, new
1314      * elements become <em>siblings</em> of the specified element, not
1315      * children.</p>
1316      *
1317      * <p>If either <code>elem</code> or <code>htmlText</code>
1318      * parameter is <code>null</code>, no changes are made to the
1319      * document.</p>
1320      *
1321      * <p>For this to work correctly, the document must have an
1322      * <code>HTMLEditorKit.Parser</code> set. This will be the case
1323      * if the document was created from an HTMLEditorKit via the
1324      * <code>createDefaultDocument</code> method.</p>
1325      *
1326      * @param elem the element the content is inserted before
1327      * @param htmlText the string to be parsed and inserted before <code>elem</code>
1328      * @throws IllegalStateException if an HTMLEditorKit.Parser has not
1329      *         been set on the document
1330      * @throws BadLocationException if insertion is impossible because of
1331      *         a structural issue
1332      * @throws IOException if an I/O exception occurs
1333      * @since 1.3
1334      */
1335     public void insertBeforeStart(Element elem, String htmlText) throws
1336                                   BadLocationException, IOException {
1337         verifyParser();
1338         if (elem != null) {
1339             Element parent = elem.getParentElement();
1340 
1341             if (parent != null) {
1342                 insertHTML(parent, elem.getStartOffset(), htmlText, false);
1343             }
1344         }
1345     }
1346 
1347     /**
1348      * Inserts the HTML specified as a string after the the end of the
1349      * given element.
1350      *
1351      * <p>Consider the following structure (the <code>elem</code>
1352      * parameter is <b>in bold</b>).</p>
1353      *
1354      * <pre>
1355      *     &lt;body&gt;
1356      *       |
1357      *     <b>&lt;div&gt;</b>
1358      *      /  \
1359      *    &lt;p&gt;   &lt;p&gt;
1360      * </pre>
1361      *
1362      * <p>Invoking <code>insertAfterEnd(elem, "&lt;ul&gt;&lt;li&gt;")</code>
1363      * results in the following structure (new elements are <font
1364      * style="color: red;">in red</font>).</p>
1365      *
1366      * <pre>
1367      *        &lt;body&gt;
1368      *         /  \
1369      *      <b>&lt;div&gt;</b> <font style="color: red;">&lt;ul&gt;</font>
1370      *       / \    \
1371      *     &lt;p&gt; &lt;p&gt;  <font style="color: red;">&lt;li&gt;</font>
1372      * </pre>
1373      *
1374      * <p>Unlike the <code>insertBeforeEnd</code> method, new elements
1375      * become <em>siblings</em> of the specified element, not
1376      * children.</p>
1377      *
1378      * <p>If either <code>elem</code> or <code>htmlText</code>
1379      * parameter is <code>null</code>, no changes are made to the
1380      * document.</p>
1381      *
1382      * <p>For this to work correctly, the document must have an
1383      * <code>HTMLEditorKit.Parser</code> set. This will be the case
1384      * if the document was created from an HTMLEditorKit via the
1385      * <code>createDefaultDocument</code> method.</p>
1386      *
1387      * @param elem the element the content is inserted after
1388      * @param htmlText the string to be parsed and inserted after <code>elem</code>
1389      * @throws IllegalStateException if an HTMLEditorKit.Parser has not
1390      *         been set on the document
1391      * @throws BadLocationException if insertion is impossible because of
1392      *         a structural issue
1393      * @throws IOException if an I/O exception occurs
1394      * @since 1.3
1395      */
1396     public void insertAfterEnd(Element elem, String htmlText) throws
1397                                BadLocationException, IOException {
1398         verifyParser();
1399         if (elem != null) {
1400             Element parent = elem.getParentElement();
1401 
1402             if (parent != null) {
1403                 int offset = elem.getEndOffset();
1404                 if (offset > getLength()) {
1405                     offset--;
1406                 }
1407                 else if (elem.isLeaf() && getText(offset - 1, 1).
1408                     charAt(0) == NEWLINE[0]) {
1409                     offset--;
1410                 }
1411                 insertHTML(parent, offset, htmlText, false);
1412             }
1413         }
1414     }
1415 
1416     /**
1417      * Returns the element that has the given id <code>Attribute</code>.
1418      * If the element can't be found, <code>null</code> is returned.
1419      * Note that this method works on an <code>Attribute</code>,
1420      * <i>not</i> a character tag.  In the following HTML snippet:
1421      * <code>&lt;a id="HelloThere"&gt;</code> the attribute is
1422      * 'id' and the character tag is 'a'.
1423      * This is a convenience method for
1424      * <code>getElement(RootElement, HTML.Attribute.id, id)</code>.
1425      * This is not thread-safe.
1426      *
1427      * @param id  the string representing the desired <code>Attribute</code>
1428      * @return the element with the specified <code>Attribute</code>
1429      *          or <code>null</code> if it can't be found,
1430      *          or <code>null</code> if <code>id</code> is <code>null</code>
1431      * @see javax.swing.text.html.HTML.Attribute
1432      * @since 1.3
1433      */
1434     public Element getElement(String id) {
1435         if (id == null) {
1436             return null;
1437         }
1438         return getElement(getDefaultRootElement(), HTML.Attribute.ID, id,
1439                           true);
1440     }
1441 
1442     /**
1443      * Returns the child element of <code>e</code> that contains the
1444      * attribute, <code>attribute</code> with value <code>value</code>, or
1445      * <code>null</code> if one isn't found. This is not thread-safe.
1446      *
1447      * @param e the root element where the search begins
1448      * @param attribute the desired <code>Attribute</code>
1449      * @param value the values for the specified <code>Attribute</code>
1450      * @return the element with the specified <code>Attribute</code>
1451      *          and the specified <code>value</code>, or <code>null</code>
1452      *          if it can't be found
1453      * @see javax.swing.text.html.HTML.Attribute
1454      * @since 1.3
1455      */
1456     public Element getElement(Element e, Object attribute, Object value) {
1457         return getElement(e, attribute, value, true);
1458     }
1459 
1460     /**
1461      * Returns the child element of <code>e</code> that contains the
1462      * attribute, <code>attribute</code> with value <code>value</code>, or
1463      * <code>null</code> if one isn't found. This is not thread-safe.
1464      * <p>
1465      * If <code>searchLeafAttributes</code> is true, and <code>e</code> is
1466      * a leaf, any attributes that are instances of <code>HTML.Tag</code>
1467      * with a value that is an <code>AttributeSet</code> will also be checked.
1468      *
1469      * @param e the root element where the search begins
1470      * @param attribute the desired <code>Attribute</code>
1471      * @param value the values for the specified <code>Attribute</code>
1472      * @return the element with the specified <code>Attribute</code>
1473      *          and the specified <code>value</code>, or <code>null</code>
1474      *          if it can't be found
1475      * @see javax.swing.text.html.HTML.Attribute
1476      */
1477     private Element getElement(Element e, Object attribute, Object value,
1478                                boolean searchLeafAttributes) {
1479         AttributeSet attr = e.getAttributes();
1480 
1481         if (attr != null && attr.isDefined(attribute)) {
1482             if (value.equals(attr.getAttribute(attribute))) {
1483                 return e;
1484             }
1485         }
1486         if (!e.isLeaf()) {
1487             for (int counter = 0, maxCounter = e.getElementCount();
1488                  counter < maxCounter; counter++) {
1489                 Element retValue = getElement(e.getElement(counter), attribute,
1490                                               value, searchLeafAttributes);
1491 
1492                 if (retValue != null) {
1493                     return retValue;
1494                 }
1495             }
1496         }
1497         else if (searchLeafAttributes && attr != null) {
1498             // For some leaf elements we store the actual attributes inside
1499             // the AttributeSet of the Element (such as anchors).
1500             Enumeration<?> names = attr.getAttributeNames();
1501             if (names != null) {
1502                 while (names.hasMoreElements()) {
1503                     Object name = names.nextElement();
1504                     if ((name instanceof HTML.Tag) &&
1505                         (attr.getAttribute(name) instanceof AttributeSet)) {
1506 
1507                         AttributeSet check = (AttributeSet)attr.
1508                                              getAttribute(name);
1509                         if (check.isDefined(attribute) &&
1510                             value.equals(check.getAttribute(attribute))) {
1511                             return e;
1512                         }
1513                     }
1514                 }
1515             }
1516         }
1517         return null;
1518     }
1519 
1520     /**
1521      * Verifies the document has an <code>HTMLEditorKit.Parser</code> set.
1522      * If <code>getParser</code> returns <code>null</code>, this will throw an
1523      * IllegalStateException.
1524      *
1525      * @throws IllegalStateException if the document does not have a Parser
1526      */
1527     private void verifyParser() {
1528         if (getParser() == null) {
1529             throw new IllegalStateException("No HTMLEditorKit.Parser");
1530         }
1531     }
1532 
1533     /**
1534      * Installs a default Parser if one has not been installed yet.
1535      */
1536     private void installParserIfNecessary() {
1537         if (getParser() == null) {
1538             setParser(new HTMLEditorKit().getParser());
1539         }
1540     }
1541 
1542     /**
1543      * Inserts a string of HTML into the document at the given position.
1544      * <code>parent</code> is used to identify the location to insert the
1545      * <code>html</code>. If <code>parent</code> is a leaf this can have
1546      * unexpected results.
1547      */
1548     private void insertHTML(Element parent, int offset, String html,
1549                             boolean wantsTrailingNewline)
1550                  throws BadLocationException, IOException {
1551         if (parent != null && html != null) {
1552             HTMLEditorKit.Parser parser = getParser();
1553             if (parser != null) {
1554                 int lastOffset = Math.max(0, offset - 1);
1555                 Element charElement = getCharacterElement(lastOffset);
1556                 Element commonParent = parent;
1557                 int pop = 0;
1558                 int push = 0;
1559 
1560                 if (parent.getStartOffset() > lastOffset) {
1561                     while (commonParent != null &&
1562                            commonParent.getStartOffset() > lastOffset) {
1563                         commonParent = commonParent.getParentElement();
1564                         push++;
1565                     }
1566                     if (commonParent == null) {
1567                         throw new BadLocationException("No common parent",
1568                                                        offset);
1569                     }
1570                 }
1571                 while (charElement != null && charElement != commonParent) {
1572                     pop++;
1573                     charElement = charElement.getParentElement();
1574                 }
1575                 if (charElement != null) {
1576                     // Found it, do the insert.
1577                     HTMLReader reader = new HTMLReader(offset, pop - 1, push,
1578                                                        null, false, true,
1579                                                        wantsTrailingNewline);
1580 
1581                     parser.parse(new StringReader(html), reader, true);
1582                     reader.flush();
1583                 }
1584             }
1585         }
1586     }
1587 
1588     /**
1589      * Removes child Elements of the passed in Element <code>e</code>. This
1590      * will do the necessary cleanup to ensure the element representing the
1591      * end character is correctly created.
1592      * <p>This is not a general purpose method, it assumes that <code>e</code>
1593      * will still have at least one child after the remove, and it assumes
1594      * the character at <code>e.getStartOffset() - 1</code> is a newline and
1595      * is of length 1.
1596      */
1597     private void removeElements(Element e, int index, int count) throws BadLocationException {
1598         writeLock();
1599         try {
1600             int start = e.getElement(index).getStartOffset();
1601             int end = e.getElement(index + count - 1).getEndOffset();
1602             if (end > getLength()) {
1603                 removeElementsAtEnd(e, index, count, start, end);
1604             }
1605             else {
1606                 removeElements(e, index, count, start, end);
1607             }
1608         } finally {
1609             writeUnlock();
1610         }
1611     }
1612 
1613     /**
1614      * Called to remove child elements of <code>e</code> when one of the
1615      * elements to remove is representing the end character.
1616      * <p>Since the Content will not allow a removal to the end character
1617      * this will do a remove from <code>start - 1</code> to <code>end</code>.
1618      * The end Element(s) will be removed, and the element representing
1619      * <code>start - 1</code> to <code>start</code> will be recreated. This
1620      * Element has to be recreated as after the content removal its offsets
1621      * become <code>start - 1</code> to <code>start - 1</code>.
1622      */
1623     private void removeElementsAtEnd(Element e, int index, int count,
1624                          int start, int end) throws BadLocationException {
1625         // index must be > 0 otherwise no insert would have happened.
1626         boolean isLeaf = (e.getElement(index - 1).isLeaf());
1627         DefaultDocumentEvent dde = new DefaultDocumentEvent(
1628                        start - 1, end - start + 1, DocumentEvent.
1629                        EventType.REMOVE);
1630 
1631         if (isLeaf) {
1632             Element endE = getCharacterElement(getLength());
1633             // e.getElement(index - 1) should represent the newline.
1634             index--;
1635             if (endE.getParentElement() != e) {
1636                 // The hiearchies don't match, we'll have to manually
1637                 // recreate the leaf at e.getElement(index - 1)
1638                 replace(dde, e, index, ++count, start, end, true, true);
1639             }
1640             else {
1641                 // The hierarchies for the end Element and
1642                 // e.getElement(index - 1), match, we can safely remove
1643                 // the Elements and the end content will be aligned
1644                 // appropriately.
1645                 replace(dde, e, index, count, start, end, true, false);
1646             }
1647         }
1648         else {
1649             // Not a leaf, descend until we find the leaf representing
1650             // start - 1 and remove it.
1651             Element newLineE = e.getElement(index - 1);
1652             while (!newLineE.isLeaf()) {
1653                 newLineE = newLineE.getElement(newLineE.getElementCount() - 1);
1654             }
1655             newLineE = newLineE.getParentElement();
1656             replace(dde, e, index, count, start, end, false, false);
1657             replace(dde, newLineE, newLineE.getElementCount() - 1, 1, start,
1658                     end, true, true);
1659         }
1660         postRemoveUpdate(dde);
1661         dde.end();
1662         fireRemoveUpdate(dde);
1663         fireUndoableEditUpdate(new UndoableEditEvent(this, dde));
1664     }
1665 
1666     /**
1667      * This is used by <code>removeElementsAtEnd</code>, it removes
1668      * <code>count</code> elements starting at <code>start</code> from
1669      * <code>e</code>.  If <code>remove</code> is true text of length
1670      * <code>start - 1</code> to <code>end - 1</code> is removed.  If
1671      * <code>create</code> is true a new leaf is created of length 1.
1672      */
1673     private void replace(DefaultDocumentEvent dde, Element e, int index,
1674                          int count, int start, int end, boolean remove,
1675                          boolean create) throws BadLocationException {
1676         Element[] added;
1677         AttributeSet attrs = e.getElement(index).getAttributes();
1678         Element[] removed = new Element[count];
1679 
1680         for (int counter = 0; counter < count; counter++) {
1681             removed[counter] = e.getElement(counter + index);
1682         }
1683         if (remove) {
1684             UndoableEdit u = getContent().remove(start - 1, end - start);
1685             if (u != null) {
1686                 dde.addEdit(u);
1687             }
1688         }
1689         if (create) {
1690             added = new Element[1];
1691             added[0] = createLeafElement(e, attrs, start - 1, start);
1692         }
1693         else {
1694             added = new Element[0];
1695         }
1696         dde.addEdit(new ElementEdit(e, index, removed, added));
1697         ((AbstractDocument.BranchElement)e).replace(
1698                                              index, removed.length, added);
1699     }
1700 
1701     /**
1702      * Called to remove child Elements when the end is not touched.
1703      */
1704     private void removeElements(Element e, int index, int count,
1705                              int start, int end) throws BadLocationException {
1706         Element[] removed = new Element[count];
1707         Element[] added = new Element[0];
1708         for (int counter = 0; counter < count; counter++) {
1709             removed[counter] = e.getElement(counter + index);
1710         }
1711         DefaultDocumentEvent dde = new DefaultDocumentEvent
1712                 (start, end - start, DocumentEvent.EventType.REMOVE);
1713         ((AbstractDocument.BranchElement)e).replace(index, removed.length,
1714                                                     added);
1715         dde.addEdit(new ElementEdit(e, index, removed, added));
1716         UndoableEdit u = getContent().remove(start, end - start);
1717         if (u != null) {
1718             dde.addEdit(u);
1719         }
1720         postRemoveUpdate(dde);
1721         dde.end();
1722         fireRemoveUpdate(dde);
1723         if (u != null) {
1724             fireUndoableEditUpdate(new UndoableEditEvent(this, dde));
1725         }
1726     }
1727 
1728 
1729     // These two are provided for inner class access. The are named different
1730     // than the super class as the super class implementations are final.
1731     void obtainLock() {
1732         writeLock();
1733     }
1734 
1735     void releaseLock() {
1736         writeUnlock();
1737     }
1738 
1739     //
1740     // Provided for inner class access.
1741     //
1742 
1743     /**
1744      * Notifies all listeners that have registered interest for
1745      * notification on this event type.  The event instance
1746      * is lazily created using the parameters passed into
1747      * the fire method.
1748      *
1749      * @param e the event
1750      * @see EventListenerList
1751      */
1752     protected void fireChangedUpdate(DocumentEvent e) {
1753         super.fireChangedUpdate(e);
1754     }
1755 
1756     /**
1757      * Notifies all listeners that have registered interest for
1758      * notification on this event type.  The event instance
1759      * is lazily created using the parameters passed into
1760      * the fire method.
1761      *
1762      * @param e the event
1763      * @see EventListenerList
1764      */
1765     protected void fireUndoableEditUpdate(UndoableEditEvent e) {
1766         super.fireUndoableEditUpdate(e);
1767     }
1768 
1769     boolean hasBaseTag() {
1770         return hasBaseTag;
1771     }
1772 
1773     String getBaseTarget() {
1774         return baseTarget;
1775     }
1776 
1777     /*
1778      * state defines whether the document is a frame document
1779      * or not.
1780      */
1781     private boolean frameDocument = false;
1782     private boolean preservesUnknownTags = true;
1783 
1784     /*
1785      * Used to store button groups for radio buttons in
1786      * a form.
1787      */
1788     private HashMap<String, ButtonGroup> radioButtonGroupsMap;
1789 
1790     /**
1791      * Document property for the number of tokens to buffer
1792      * before building an element subtree to represent them.
1793      */
1794     static final String TokenThreshold = "token threshold";
1795 
1796     private static final int MaxThreshold = 10000;
1797 
1798     private static final int StepThreshold = 5;
1799 
1800 
1801     /**
1802      * Document property key value. The value for the key will be a Vector
1803      * of Strings that are comments not found in the body.
1804      */
1805     public static final String AdditionalComments = "AdditionalComments";
1806 
1807     /**
1808      * Document property key value. The value for the key will be a
1809      * String indicating the default type of stylesheet links.
1810      */
1811     /* public */ static final String StyleType = "StyleType";
1812 
1813     /**
1814      * The location to resolve relative URLs against.  By
1815      * default this will be the document's URL if the document
1816      * was loaded from a URL.  If a base tag is found and
1817      * can be parsed, it will be used as the base location.
1818      */
1819     URL base;
1820 
1821     /**
1822      * does the document have base tag
1823      */
1824     boolean hasBaseTag = false;
1825 
1826     /**
1827      * BASE tag's TARGET attribute value
1828      */
1829     private String baseTarget = null;
1830 
1831     /**
1832      * The parser that is used when inserting html into the existing
1833      * document.
1834      */
1835     private HTMLEditorKit.Parser parser;
1836 
1837     /**
1838      * Used for inserts when a null AttributeSet is supplied.
1839      */
1840     private static AttributeSet contentAttributeSet;
1841 
1842     /**
1843      * Property Maps are registered under, will be a Hashtable.
1844      */
1845     static String MAP_PROPERTY = "__MAP__";
1846 
1847     private static char[] NEWLINE;
1848 
1849     /**
1850      * I18N property key.
1851      *
1852      * @see AbstractDocument#I18NProperty
1853      */
1854     private static final String I18NProperty = "i18n";
1855 
1856     static {
1857         contentAttributeSet = new SimpleAttributeSet();
1858         ((MutableAttributeSet)contentAttributeSet).
1859                         addAttribute(StyleConstants.NameAttribute,
1860                                      HTML.Tag.CONTENT);
1861         NEWLINE = new char[1];
1862         NEWLINE[0] = '\n';
1863     }
1864 
1865 
1866     /**
1867      * An iterator to iterate over a particular type of
1868      * tag.  The iterator is not thread safe.  If reliable
1869      * access to the document is not already ensured by
1870      * the context under which the iterator is being used,
1871      * its use should be performed under the protection of
1872      * Document.render.
1873      */
1874     public static abstract class Iterator {
1875 
1876         /**
1877          * Return the attributes for this tag.
1878          * @return the <code>AttributeSet</code> for this tag, or
1879          *      <code>null</code> if none can be found
1880          */
1881         public abstract AttributeSet getAttributes();
1882 
1883         /**
1884          * Returns the start of the range for which the current occurrence of
1885          * the tag is defined and has the same attributes.
1886          *
1887          * @return the start of the range, or -1 if it can't be found
1888          */
1889         public abstract int getStartOffset();
1890 
1891         /**
1892          * Returns the end of the range for which the current occurrence of
1893          * the tag is defined and has the same attributes.
1894          *
1895          * @return the end of the range
1896          */
1897         public abstract int getEndOffset();
1898 
1899         /**
1900          * Move the iterator forward to the next occurrence
1901          * of the tag it represents.
1902          */
1903         public abstract void next();
1904 
1905         /**
1906          * Indicates if the iterator is currently
1907          * representing an occurrence of a tag.  If
1908          * false there are no more tags for this iterator.
1909          * @return true if the iterator is currently representing an
1910          *              occurrence of a tag, otherwise returns false
1911          */
1912         public abstract boolean isValid();
1913 
1914         /**
1915          * Type of tag this iterator represents.
1916          * @return the tag
1917          */
1918         public abstract HTML.Tag getTag();
1919     }
1920 
1921     /**
1922      * An iterator to iterate over a particular type of tag.
1923      */
1924     static class LeafIterator extends Iterator {
1925 
1926         LeafIterator(HTML.Tag t, Document doc) {
1927             tag = t;
1928             pos = new ElementIterator(doc);
1929             endOffset = 0;
1930             next();
1931         }
1932 
1933         /**
1934          * Returns the attributes for this tag.
1935          * @return the <code>AttributeSet</code> for this tag,
1936          *              or <code>null</code> if none can be found
1937          */
1938         public AttributeSet getAttributes() {
1939             Element elem = pos.current();
1940             if (elem != null) {
1941                 AttributeSet a = (AttributeSet)
1942                     elem.getAttributes().getAttribute(tag);
1943                 if (a == null) {
1944                     a = elem.getAttributes();
1945                 }
1946                 return a;
1947             }
1948             return null;
1949         }
1950 
1951         /**
1952          * Returns the start of the range for which the current occurrence of
1953          * the tag is defined and has the same attributes.
1954          *
1955          * @return the start of the range, or -1 if it can't be found
1956          */
1957         public int getStartOffset() {
1958             Element elem = pos.current();
1959             if (elem != null) {
1960                 return elem.getStartOffset();
1961             }
1962             return -1;
1963         }
1964 
1965         /**
1966          * Returns the end of the range for which the current occurrence of
1967          * the tag is defined and has the same attributes.
1968          *
1969          * @return the end of the range
1970          */
1971         public int getEndOffset() {
1972             return endOffset;
1973         }
1974 
1975         /**
1976          * Moves the iterator forward to the next occurrence
1977          * of the tag it represents.
1978          */
1979         public void next() {
1980             for (nextLeaf(pos); isValid(); nextLeaf(pos)) {
1981                 Element elem = pos.current();
1982                 if (elem.getStartOffset() >= endOffset) {
1983                     AttributeSet a = pos.current().getAttributes();
1984 
1985                     if (a.isDefined(tag) ||
1986                         a.getAttribute(StyleConstants.NameAttribute) == tag) {
1987 
1988                         // we found the next one
1989                         setEndOffset();
1990                         break;
1991                     }
1992                 }
1993             }
1994         }
1995 
1996         /**
1997          * Returns the type of tag this iterator represents.
1998          *
1999          * @return the <code>HTML.Tag</code> that this iterator represents.
2000          * @see javax.swing.text.html.HTML.Tag
2001          */
2002         public HTML.Tag getTag() {
2003             return tag;
2004         }
2005 
2006         /**
2007          * Returns true if the current position is not <code>null</code>.
2008          * @return true if current position is not <code>null</code>,
2009          *              otherwise returns false
2010          */
2011         public boolean isValid() {
2012             return (pos.current() != null);
2013         }
2014 
2015         /**
2016          * Moves the given iterator to the next leaf element.
2017          * @param iter  the iterator to be scanned
2018          */
2019         void nextLeaf(ElementIterator iter) {
2020             for (iter.next(); iter.current() != null; iter.next()) {
2021                 Element e = iter.current();
2022                 if (e.isLeaf()) {
2023                     break;
2024                 }
2025             }
2026         }
2027 
2028         /**
2029          * Marches a cloned iterator forward to locate the end
2030          * of the run.  This sets the value of <code>endOffset</code>.
2031          */
2032         void setEndOffset() {
2033             AttributeSet a0 = getAttributes();
2034             endOffset = pos.current().getEndOffset();
2035             ElementIterator fwd = (ElementIterator) pos.clone();
2036             for (nextLeaf(fwd); fwd.current() != null; nextLeaf(fwd)) {
2037                 Element e = fwd.current();
2038                 AttributeSet a1 = (AttributeSet) e.getAttributes().getAttribute(tag);
2039                 if ((a1 == null) || (! a1.equals(a0))) {
2040                     break;
2041                 }
2042                 endOffset = e.getEndOffset();
2043             }
2044         }
2045 
2046         private int endOffset;
2047         private HTML.Tag tag;
2048         private ElementIterator pos;
2049 
2050     }
2051 
2052     /**
2053      * An HTML reader to load an HTML document with an HTML
2054      * element structure.  This is a set of callbacks from
2055      * the parser, implemented to create a set of elements
2056      * tagged with attributes.  The parse builds up tokens
2057      * (ElementSpec) that describe the element subtree desired,
2058      * and burst it into the document under the protection of
2059      * a write lock using the insert method on the document
2060      * outer class.
2061      * <p>
2062      * The reader can be configured by registering actions
2063      * (of type <code>HTMLDocument.HTMLReader.TagAction</code>)
2064      * that describe how to handle the action.  The idea behind
2065      * the actions provided is that the most natural text editing
2066      * operations can be provided if the element structure boils
2067      * down to paragraphs with runs of some kind of style
2068      * in them.  Some things are more naturally specified
2069      * structurally, so arbitrary structure should be allowed
2070      * above the paragraphs, but will need to be edited with structural
2071      * actions.  The implication of this is that some of the
2072      * HTML elements specified in the stream being parsed will
2073      * be collapsed into attributes, and in some cases paragraphs
2074      * will be synthesized.  When HTML elements have been
2075      * converted to attributes, the attribute key will be of
2076      * type HTML.Tag, and the value will be of type AttributeSet
2077      * so that no information is lost.  This enables many of the
2078      * existing actions to work so that the user can type input,
2079      * hit the return key, backspace, delete, etc and have a
2080      * reasonable result.  Selections can be created, and attributes
2081      * applied or removed, etc.  With this in mind, the work done
2082      * by the reader can be categorized into the following kinds
2083      * of tasks:
2084      * <dl>
2085      * <dt>Block
2086      * <dd>Build the structure like it's specified in the stream.
2087      * This produces elements that contain other elements.
2088      * <dt>Paragraph
2089      * <dd>Like block except that it's expected that the element
2090      * will be used with a paragraph view so a paragraph element
2091      * won't need to be synthesized.
2092      * <dt>Character
2093      * <dd>Contribute the element as an attribute that will start
2094      * and stop at arbitrary text locations.  This will ultimately
2095      * be mixed into a run of text, with all of the currently
2096      * flattened HTML character elements.
2097      * <dt>Special
2098      * <dd>Produce an embedded graphical element.
2099      * <dt>Form
2100      * <dd>Produce an element that is like the embedded graphical
2101      * element, except that it also has a component model associated
2102      * with it.
2103      * <dt>Hidden
2104      * <dd>Create an element that is hidden from view when the
2105      * document is being viewed read-only, and visible when the
2106      * document is being edited.  This is useful to keep the
2107      * model from losing information, and used to store things
2108      * like comments and unrecognized tags.
2109      *
2110      * </dl>
2111      * <p>
2112      * Currently, &lt;APPLET&gt;, &lt;PARAM&gt;, &lt;MAP&gt;, &lt;AREA&gt;, &lt;LINK&gt;,
2113      * &lt;SCRIPT&gt; and &lt;STYLE&gt; are unsupported.
2114      *
2115      * <p>
2116      * The assignment of the actions described is shown in the
2117      * following table for the tags defined in <code>HTML.Tag</code>.
2118      * <table border=1 summary="HTML tags and assigned actions">
2119      * <tr><th>Tag</th><th>Action</th></tr>
2120      * <tr><td><code>HTML.Tag.A</code>         <td>CharacterAction
2121      * <tr><td><code>HTML.Tag.ADDRESS</code>   <td>CharacterAction
2122      * <tr><td><code>HTML.Tag.APPLET</code>    <td>HiddenAction
2123      * <tr><td><code>HTML.Tag.AREA</code>      <td>AreaAction
2124      * <tr><td><code>HTML.Tag.B</code>         <td>CharacterAction
2125      * <tr><td><code>HTML.Tag.BASE</code>      <td>BaseAction
2126      * <tr><td><code>HTML.Tag.BASEFONT</code>  <td>CharacterAction
2127      * <tr><td><code>HTML.Tag.BIG</code>       <td>CharacterAction
2128      * <tr><td><code>HTML.Tag.BLOCKQUOTE</code><td>BlockAction
2129      * <tr><td><code>HTML.Tag.BODY</code>      <td>BlockAction
2130      * <tr><td><code>HTML.Tag.BR</code>        <td>SpecialAction
2131      * <tr><td><code>HTML.Tag.CAPTION</code>   <td>BlockAction
2132      * <tr><td><code>HTML.Tag.CENTER</code>    <td>BlockAction
2133      * <tr><td><code>HTML.Tag.CITE</code>      <td>CharacterAction
2134      * <tr><td><code>HTML.Tag.CODE</code>      <td>CharacterAction
2135      * <tr><td><code>HTML.Tag.DD</code>        <td>BlockAction
2136      * <tr><td><code>HTML.Tag.DFN</code>       <td>CharacterAction
2137      * <tr><td><code>HTML.Tag.DIR</code>       <td>BlockAction
2138      * <tr><td><code>HTML.Tag.DIV</code>       <td>BlockAction
2139      * <tr><td><code>HTML.Tag.DL</code>        <td>BlockAction
2140      * <tr><td><code>HTML.Tag.DT</code>        <td>ParagraphAction
2141      * <tr><td><code>HTML.Tag.EM</code>        <td>CharacterAction
2142      * <tr><td><code>HTML.Tag.FONT</code>      <td>CharacterAction
2143      * <tr><td><code>HTML.Tag.FORM</code>      <td>As of 1.4 a BlockAction
2144      * <tr><td><code>HTML.Tag.FRAME</code>     <td>SpecialAction
2145      * <tr><td><code>HTML.Tag.FRAMESET</code>  <td>BlockAction
2146      * <tr><td><code>HTML.Tag.H1</code>        <td>ParagraphAction
2147      * <tr><td><code>HTML.Tag.H2</code>        <td>ParagraphAction
2148      * <tr><td><code>HTML.Tag.H3</code>        <td>ParagraphAction
2149      * <tr><td><code>HTML.Tag.H4</code>        <td>ParagraphAction
2150      * <tr><td><code>HTML.Tag.H5</code>        <td>ParagraphAction
2151      * <tr><td><code>HTML.Tag.H6</code>        <td>ParagraphAction
2152      * <tr><td><code>HTML.Tag.HEAD</code>      <td>HeadAction
2153      * <tr><td><code>HTML.Tag.HR</code>        <td>SpecialAction
2154      * <tr><td><code>HTML.Tag.HTML</code>      <td>BlockAction
2155      * <tr><td><code>HTML.Tag.I</code>         <td>CharacterAction
2156      * <tr><td><code>HTML.Tag.IMG</code>       <td>SpecialAction
2157      * <tr><td><code>HTML.Tag.INPUT</code>     <td>FormAction
2158      * <tr><td><code>HTML.Tag.ISINDEX</code>   <td>IsndexAction
2159      * <tr><td><code>HTML.Tag.KBD</code>       <td>CharacterAction
2160      * <tr><td><code>HTML.Tag.LI</code>        <td>BlockAction
2161      * <tr><td><code>HTML.Tag.LINK</code>      <td>LinkAction
2162      * <tr><td><code>HTML.Tag.MAP</code>       <td>MapAction
2163      * <tr><td><code>HTML.Tag.MENU</code>      <td>BlockAction
2164      * <tr><td><code>HTML.Tag.META</code>      <td>MetaAction
2165      * <tr><td><code>HTML.Tag.NOFRAMES</code>  <td>BlockAction
2166      * <tr><td><code>HTML.Tag.OBJECT</code>    <td>SpecialAction
2167      * <tr><td><code>HTML.Tag.OL</code>        <td>BlockAction
2168      * <tr><td><code>HTML.Tag.OPTION</code>    <td>FormAction
2169      * <tr><td><code>HTML.Tag.P</code>         <td>ParagraphAction
2170      * <tr><td><code>HTML.Tag.PARAM</code>     <td>HiddenAction
2171      * <tr><td><code>HTML.Tag.PRE</code>       <td>PreAction
2172      * <tr><td><code>HTML.Tag.SAMP</code>      <td>CharacterAction
2173      * <tr><td><code>HTML.Tag.SCRIPT</code>    <td>HiddenAction
2174      * <tr><td><code>HTML.Tag.SELECT</code>    <td>FormAction
2175      * <tr><td><code>HTML.Tag.SMALL</code>     <td>CharacterAction
2176      * <tr><td><code>HTML.Tag.STRIKE</code>    <td>CharacterAction
2177      * <tr><td><code>HTML.Tag.S</code>         <td>CharacterAction
2178      * <tr><td><code>HTML.Tag.STRONG</code>    <td>CharacterAction
2179      * <tr><td><code>HTML.Tag.STYLE</code>     <td>StyleAction
2180      * <tr><td><code>HTML.Tag.SUB</code>       <td>CharacterAction
2181      * <tr><td><code>HTML.Tag.SUP</code>       <td>CharacterAction
2182      * <tr><td><code>HTML.Tag.TABLE</code>     <td>BlockAction
2183      * <tr><td><code>HTML.Tag.TD</code>        <td>BlockAction
2184      * <tr><td><code>HTML.Tag.TEXTAREA</code>  <td>FormAction
2185      * <tr><td><code>HTML.Tag.TH</code>        <td>BlockAction
2186      * <tr><td><code>HTML.Tag.TITLE</code>     <td>TitleAction
2187      * <tr><td><code>HTML.Tag.TR</code>        <td>BlockAction
2188      * <tr><td><code>HTML.Tag.TT</code>        <td>CharacterAction
2189      * <tr><td><code>HTML.Tag.U</code>         <td>CharacterAction
2190      * <tr><td><code>HTML.Tag.UL</code>        <td>BlockAction
2191      * <tr><td><code>HTML.Tag.VAR</code>       <td>CharacterAction
2192      * </table>
2193      * <p>
2194      * Once &lt;/html&gt; is encountered, the Actions are no longer notified.
2195      */
2196     public class HTMLReader extends HTMLEditorKit.ParserCallback {
2197 
2198         /**
2199          * Constructs an HTMLReader using default pop and push depth and no tag to insert.
2200          *
2201          * @param offset the starting offset
2202          */
2203         public HTMLReader(int offset) {
2204             this(offset, 0, 0, null);
2205         }
2206 
2207         /**
2208          * Constructs an HTMLReader.
2209          *
2210          * @param offset the starting offset
2211          * @param popDepth how many parents to ascend before insert new element
2212          * @param pushDepth how many parents to descend (relative to popDepth) before
2213          *                  inserting
2214          * @param insertTag a tag to insert (may be null)
2215          */
2216         public HTMLReader(int offset, int popDepth, int pushDepth,
2217                           HTML.Tag insertTag) {
2218             this(offset, popDepth, pushDepth, insertTag, true, false, true);
2219         }
2220 
2221         /**
2222          * Generates a RuntimeException (will eventually generate
2223          * a BadLocationException when API changes are alloced) if inserting
2224          * into non empty document, <code>insertTag</code> is
2225          * non-<code>null</code>, and <code>offset</code> is not in the body.
2226          */
2227         // PENDING(sky): Add throws BadLocationException and remove
2228         // RuntimeException
2229         HTMLReader(int offset, int popDepth, int pushDepth,
2230                    HTML.Tag insertTag, boolean insertInsertTag,
2231                    boolean insertAfterImplied, boolean wantsTrailingNewline) {
2232             emptyDocument = (getLength() == 0);
2233             isStyleCSS = "text/css".equals(getDefaultStyleSheetType());
2234             this.offset = offset;
2235             threshold = HTMLDocument.this.getTokenThreshold();
2236             tagMap = new Hashtable<HTML.Tag, TagAction>(57);
2237             TagAction na = new TagAction();
2238             TagAction ba = new BlockAction();
2239             TagAction pa = new ParagraphAction();
2240             TagAction ca = new CharacterAction();
2241             TagAction sa = new SpecialAction();
2242             TagAction fa = new FormAction();
2243             TagAction ha = new HiddenAction();
2244             TagAction conv = new ConvertAction();
2245 
2246             // register handlers for the well known tags
2247             tagMap.put(HTML.Tag.A, new AnchorAction());
2248             tagMap.put(HTML.Tag.ADDRESS, ca);
2249             tagMap.put(HTML.Tag.APPLET, ha);
2250             tagMap.put(HTML.Tag.AREA, new AreaAction());
2251             tagMap.put(HTML.Tag.B, conv);
2252             tagMap.put(HTML.Tag.BASE, new BaseAction());
2253             tagMap.put(HTML.Tag.BASEFONT, ca);
2254             tagMap.put(HTML.Tag.BIG, ca);
2255             tagMap.put(HTML.Tag.BLOCKQUOTE, ba);
2256             tagMap.put(HTML.Tag.BODY, ba);
2257             tagMap.put(HTML.Tag.BR, sa);
2258             tagMap.put(HTML.Tag.CAPTION, ba);
2259             tagMap.put(HTML.Tag.CENTER, ba);
2260             tagMap.put(HTML.Tag.CITE, ca);
2261             tagMap.put(HTML.Tag.CODE, ca);
2262             tagMap.put(HTML.Tag.DD, ba);
2263             tagMap.put(HTML.Tag.DFN, ca);
2264             tagMap.put(HTML.Tag.DIR, ba);
2265             tagMap.put(HTML.Tag.DIV, ba);
2266             tagMap.put(HTML.Tag.DL, ba);
2267             tagMap.put(HTML.Tag.DT, pa);
2268             tagMap.put(HTML.Tag.EM, ca);
2269             tagMap.put(HTML.Tag.FONT, conv);
2270             tagMap.put(HTML.Tag.FORM, new FormTagAction());
2271             tagMap.put(HTML.Tag.FRAME, sa);
2272             tagMap.put(HTML.Tag.FRAMESET, ba);
2273             tagMap.put(HTML.Tag.H1, pa);
2274             tagMap.put(HTML.Tag.H2, pa);
2275             tagMap.put(HTML.Tag.H3, pa);
2276             tagMap.put(HTML.Tag.H4, pa);
2277             tagMap.put(HTML.Tag.H5, pa);
2278             tagMap.put(HTML.Tag.H6, pa);
2279             tagMap.put(HTML.Tag.HEAD, new HeadAction());
2280             tagMap.put(HTML.Tag.HR, sa);
2281             tagMap.put(HTML.Tag.HTML, ba);
2282             tagMap.put(HTML.Tag.I, conv);
2283             tagMap.put(HTML.Tag.IMG, sa);
2284             tagMap.put(HTML.Tag.INPUT, fa);
2285             tagMap.put(HTML.Tag.ISINDEX, new IsindexAction());
2286             tagMap.put(HTML.Tag.KBD, ca);
2287             tagMap.put(HTML.Tag.LI, ba);
2288             tagMap.put(HTML.Tag.LINK, new LinkAction());
2289             tagMap.put(HTML.Tag.MAP, new MapAction());
2290             tagMap.put(HTML.Tag.MENU, ba);
2291             tagMap.put(HTML.Tag.META, new MetaAction());
2292             tagMap.put(HTML.Tag.NOBR, ca);
2293             tagMap.put(HTML.Tag.NOFRAMES, ba);
2294             tagMap.put(HTML.Tag.OBJECT, sa);
2295             tagMap.put(HTML.Tag.OL, ba);
2296             tagMap.put(HTML.Tag.OPTION, fa);
2297             tagMap.put(HTML.Tag.P, pa);
2298             tagMap.put(HTML.Tag.PARAM, new ObjectAction());
2299             tagMap.put(HTML.Tag.PRE, new PreAction());
2300             tagMap.put(HTML.Tag.SAMP, ca);
2301             tagMap.put(HTML.Tag.SCRIPT, ha);
2302             tagMap.put(HTML.Tag.SELECT, fa);
2303             tagMap.put(HTML.Tag.SMALL, ca);
2304             tagMap.put(HTML.Tag.SPAN, ca);
2305             tagMap.put(HTML.Tag.STRIKE, conv);
2306             tagMap.put(HTML.Tag.S, ca);
2307             tagMap.put(HTML.Tag.STRONG, ca);
2308             tagMap.put(HTML.Tag.STYLE, new StyleAction());
2309             tagMap.put(HTML.Tag.SUB, conv);
2310             tagMap.put(HTML.Tag.SUP, conv);
2311             tagMap.put(HTML.Tag.TABLE, ba);
2312             tagMap.put(HTML.Tag.TD, ba);
2313             tagMap.put(HTML.Tag.TEXTAREA, fa);
2314             tagMap.put(HTML.Tag.TH, ba);
2315             tagMap.put(HTML.Tag.TITLE, new TitleAction());
2316             tagMap.put(HTML.Tag.TR, ba);
2317             tagMap.put(HTML.Tag.TT, ca);
2318             tagMap.put(HTML.Tag.U, conv);
2319             tagMap.put(HTML.Tag.UL, ba);
2320             tagMap.put(HTML.Tag.VAR, ca);
2321 
2322             if (insertTag != null) {
2323                 this.insertTag = insertTag;
2324                 this.popDepth = popDepth;
2325                 this.pushDepth = pushDepth;
2326                 this.insertInsertTag = insertInsertTag;
2327                 foundInsertTag = false;
2328             }
2329             else {
2330                 foundInsertTag = true;
2331             }
2332             if (insertAfterImplied) {
2333                 this.popDepth = popDepth;
2334                 this.pushDepth = pushDepth;
2335                 this.insertAfterImplied = true;
2336                 foundInsertTag = false;
2337                 midInsert = false;
2338                 this.insertInsertTag = true;
2339                 this.wantsTrailingNewline = wantsTrailingNewline;
2340             }
2341             else {
2342                 midInsert = (!emptyDocument && insertTag == null);
2343                 if (midInsert) {
2344                     generateEndsSpecsForMidInsert();
2345                 }
2346             }
2347 
2348             /**
2349              * This block initializes the <code>inParagraph</code> flag.
2350              * It is left in <code>false</code> value automatically
2351              * if the target document is empty or future inserts
2352              * were positioned into the 'body' tag.
2353              */
2354             if (!emptyDocument && !midInsert) {
2355                 int targetOffset = Math.max(this.offset - 1, 0);
2356                 Element elem =
2357                         HTMLDocument.this.getCharacterElement(targetOffset);
2358                 /* Going up by the left document structure path */
2359                 for (int i = 0; i <= this.popDepth; i++) {
2360                     elem = elem.getParentElement();
2361                 }
2362                 /* Going down by the right document structure path */
2363                 for (int i = 0; i < this.pushDepth; i++) {
2364                     int index = elem.getElementIndex(this.offset);
2365                     elem = elem.getElement(index);
2366                 }
2367                 AttributeSet attrs = elem.getAttributes();
2368                 if (attrs != null) {
2369                     HTML.Tag tagToInsertInto =
2370                             (HTML.Tag) attrs.getAttribute(StyleConstants.NameAttribute);
2371                     if (tagToInsertInto != null) {
2372                         this.inParagraph = tagToInsertInto.isParagraph();
2373                     }
2374                 }
2375             }
2376         }
2377 
2378         /**
2379          * Generates an initial batch of end <code>ElementSpecs</code>
2380          * in parseBuffer to position future inserts into the body.
2381          */
2382         private void generateEndsSpecsForMidInsert() {
2383             int           count = heightToElementWithName(HTML.Tag.BODY,
2384                                                    Math.max(0, offset - 1));
2385             boolean       joinNext = false;
2386 
2387             if (count == -1 && offset > 0) {
2388                 count = heightToElementWithName(HTML.Tag.BODY, offset);
2389                 if (count != -1) {
2390                     // Previous isn't in body, but current is. Have to
2391                     // do some end specs, followed by join next.
2392                     count = depthTo(offset - 1) - 1;
2393                     joinNext = true;
2394                 }
2395             }
2396             if (count == -1) {
2397                 throw new RuntimeException("Must insert new content into body element-");
2398             }
2399             if (count != -1) {
2400                 // Insert a newline, if necessary.
2401                 try {
2402                     if (!joinNext && offset > 0 &&
2403                         !getText(offset - 1, 1).equals("\n")) {
2404                         SimpleAttributeSet newAttrs = new SimpleAttributeSet();
2405                         newAttrs.addAttribute(StyleConstants.NameAttribute,
2406                                               HTML.Tag.CONTENT);
2407                         ElementSpec spec = new ElementSpec(newAttrs,
2408                                     ElementSpec.ContentType, NEWLINE, 0, 1);
2409                         parseBuffer.addElement(spec);
2410                     }
2411                     // Should never throw, but will catch anyway.
2412                 } catch (BadLocationException ble) {}
2413                 while (count-- > 0) {
2414                     parseBuffer.addElement(new ElementSpec
2415                                            (null, ElementSpec.EndTagType));
2416                 }
2417                 if (joinNext) {
2418                     ElementSpec spec = new ElementSpec(null, ElementSpec.
2419                                                        StartTagType);
2420 
2421                     spec.setDirection(ElementSpec.JoinNextDirection);
2422                     parseBuffer.addElement(spec);
2423                 }
2424             }
2425             // We should probably throw an exception if (count == -1)
2426             // Or look for the body and reset the offset.
2427         }
2428 
2429         /**
2430          * @return number of parents to reach the child at offset.
2431          */
2432         private int depthTo(int offset) {
2433             Element       e = getDefaultRootElement();
2434             int           count = 0;
2435 
2436             while (!e.isLeaf()) {
2437                 count++;
2438                 e = e.getElement(e.getElementIndex(offset));
2439             }
2440             return count;
2441         }
2442 
2443         /**
2444          * @return number of parents of the leaf at <code>offset</code>
2445          *         until a parent with name, <code>name</code> has been
2446          *         found. -1 indicates no matching parent with
2447          *         <code>name</code>.
2448          */
2449         private int heightToElementWithName(Object name, int offset) {
2450             Element       e = getCharacterElement(offset).getParentElement();
2451             int           count = 0;
2452 
2453             while (e != null && e.getAttributes().getAttribute
2454                    (StyleConstants.NameAttribute) != name) {
2455                 count++;
2456                 e = e.getParentElement();
2457             }
2458             return (e == null) ? -1 : count;
2459         }
2460 
2461         /**
2462          * This will make sure there aren't two BODYs (the second is
2463          * typically created when you do a remove all, and then an insert).
2464          */
2465         private void adjustEndElement() {
2466             int length = getLength();
2467             if (length == 0) {
2468                 return;
2469             }
2470             obtainLock();
2471             try {
2472                 Element[] pPath = getPathTo(length - 1);
2473                 int pLength = pPath.length;
2474                 if (pLength > 1 && pPath[1].getAttributes().getAttribute
2475                          (StyleConstants.NameAttribute) == HTML.Tag.BODY &&
2476                          pPath[1].getEndOffset() == length) {
2477                     String lastText = getText(length - 1, 1);
2478                     DefaultDocumentEvent event;
2479                     Element[] added;
2480                     Element[] removed;
2481                     int index;
2482                     // Remove the fake second body.
2483                     added = new Element[0];
2484                     removed = new Element[1];
2485                     index = pPath[0].getElementIndex(length);
2486                     removed[0] = pPath[0].getElement(index);
2487                     ((BranchElement)pPath[0]).replace(index, 1, added);
2488                     ElementEdit firstEdit = new ElementEdit(pPath[0], index,
2489                                                             removed, added);
2490 
2491                     // Insert a new element to represent the end that the
2492                     // second body was representing.
2493                     SimpleAttributeSet sas = new SimpleAttributeSet();
2494                     sas.addAttribute(StyleConstants.NameAttribute,
2495                                          HTML.Tag.CONTENT);
2496                     sas.addAttribute(IMPLIED_CR, Boolean.TRUE);
2497                     added = new Element[1];
2498                     added[0] = createLeafElement(pPath[pLength - 1],
2499                                                      sas, length, length + 1);
2500                     index = pPath[pLength - 1].getElementCount();
2501                     ((BranchElement)pPath[pLength - 1]).replace(index, 0,
2502                                                                 added);
2503                     event = new DefaultDocumentEvent(length, 1,
2504                                             DocumentEvent.EventType.CHANGE);
2505                     event.addEdit(new ElementEdit(pPath[pLength - 1],
2506                                          index, new Element[0], added));
2507                     event.addEdit(firstEdit);
2508                     event.end();
2509                     fireChangedUpdate(event);
2510                     fireUndoableEditUpdate(new UndoableEditEvent(this, event));
2511 
2512                     if (lastText.equals("\n")) {
2513                         // We now have two \n's, one part of the Document.
2514                         // We need to remove one
2515                         event = new DefaultDocumentEvent(length - 1, 1,
2516                                            DocumentEvent.EventType.REMOVE);
2517                         removeUpdate(event);
2518                         UndoableEdit u = getContent().remove(length - 1, 1);
2519                         if (u != null) {
2520                             event.addEdit(u);
2521                         }
2522                         postRemoveUpdate(event);
2523                         // Mark the edit as done.
2524                         event.end();
2525                         fireRemoveUpdate(event);
2526                         fireUndoableEditUpdate(new UndoableEditEvent(
2527                                                this, event));
2528                     }
2529                 }
2530             }
2531             catch (BadLocationException ble) {
2532             }
2533             finally {
2534                 releaseLock();
2535             }
2536         }
2537 
2538         private Element[] getPathTo(int offset) {
2539             Stack<Element> elements = new Stack<Element>();
2540             Element e = getDefaultRootElement();
2541             int index;
2542             while (!e.isLeaf()) {
2543                 elements.push(e);
2544                 e = e.getElement(e.getElementIndex(offset));
2545             }
2546             Element[] retValue = new Element[elements.size()];
2547             elements.copyInto(retValue);
2548             return retValue;
2549         }
2550 
2551         // -- HTMLEditorKit.ParserCallback methods --------------------
2552 
2553         /**
2554          * The last method called on the reader.  It allows
2555          * any pending changes to be flushed into the document.
2556          * Since this is currently loading synchronously, the entire
2557          * set of changes are pushed in at this point.
2558          */
2559         public void flush() throws BadLocationException {
2560             if (emptyDocument && !insertAfterImplied) {
2561                 if (HTMLDocument.this.getLength() > 0 ||
2562                                       parseBuffer.size() > 0) {
2563                     flushBuffer(true);
2564                     adjustEndElement();
2565                 }
2566                 // We won't insert when
2567             }
2568             else {
2569                 flushBuffer(true);
2570             }
2571         }
2572 
2573         /**
2574          * Called by the parser to indicate a block of text was
2575          * encountered.
2576          */
2577         public void handleText(char[] data, int pos) {
2578             if (receivedEndHTML || (midInsert && !inBody)) {
2579                 return;
2580             }
2581 
2582             // see if complex glyph layout support is needed
2583             if(HTMLDocument.this.getProperty(I18NProperty).equals( Boolean.FALSE ) ) {
2584                 // if a default direction of right-to-left has been specified,
2585                 // we want complex layout even if the text is all left to right.
2586                 Object d = getProperty(TextAttribute.RUN_DIRECTION);
2587                 if ((d != null) && (d.equals(TextAttribute.RUN_DIRECTION_RTL))) {
2588                     HTMLDocument.this.putProperty( I18NProperty, Boolean.TRUE);
2589                 } else {
2590                     if (SwingUtilities2.isComplexLayout(data, 0, data.length)) {
2591                         HTMLDocument.this.putProperty( I18NProperty, Boolean.TRUE);
2592                     }
2593                 }
2594             }
2595 
2596             if (inTextArea) {
2597                 textAreaContent(data);
2598             } else if (inPre) {
2599                 preContent(data);
2600             } else if (inTitle) {
2601                 putProperty(Document.TitleProperty, new String(data));
2602             } else if (option != null) {
2603                 option.setLabel(new String(data));
2604             } else if (inStyle) {
2605                 if (styles != null) {
2606                     styles.addElement(new String(data));
2607                 }
2608             } else if (inBlock > 0) {
2609                 if (!foundInsertTag && insertAfterImplied) {
2610                     // Assume content should be added.
2611                     foundInsertTag(false);
2612                     foundInsertTag = true;
2613                     inParagraph = impliedP = true;
2614                 }
2615                 if (data.length >= 1) {
2616                     addContent(data, 0, data.length);
2617                 }
2618             }
2619         }
2620 
2621         /**
2622          * Callback from the parser.  Route to the appropriate
2623          * handler for the tag.
2624          */
2625         public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
2626             if (receivedEndHTML) {
2627                 return;
2628             }
2629             if (midInsert && !inBody) {
2630                 if (t == HTML.Tag.BODY) {
2631                     inBody = true;
2632                     // Increment inBlock since we know we are in the body,
2633                     // this is needed incase an implied-p is needed. If
2634                     // inBlock isn't incremented, and an implied-p is
2635                     // encountered, addContent won't be called!
2636                     inBlock++;
2637                 }
2638                 return;
2639             }
2640             if (!inBody && t == HTML.Tag.BODY) {
2641                 inBody = true;
2642             }
2643             if (isStyleCSS && a.isDefined(HTML.Attribute.STYLE)) {
2644                 // Map the style attributes.
2645                 String decl = (String)a.getAttribute(HTML.Attribute.STYLE);
2646                 a.removeAttribute(HTML.Attribute.STYLE);
2647                 styleAttributes = getStyleSheet().getDeclaration(decl);
2648                 a.addAttributes(styleAttributes);
2649             }
2650             else {
2651                 styleAttributes = null;
2652             }
2653             TagAction action = tagMap.get(t);
2654 
2655             if (action != null) {
2656                 action.start(t, a);
2657             }
2658         }
2659 
2660         public void handleComment(char[] data, int pos) {
2661             if (receivedEndHTML) {
2662                 addExternalComment(new String(data));
2663                 return;
2664             }
2665             if (inStyle) {
2666                 if (styles != null) {
2667                     styles.addElement(new String(data));
2668                 }
2669             }
2670             else if (getPreservesUnknownTags()) {
2671                 if (inBlock == 0 && (foundInsertTag ||
2672                                      insertTag != HTML.Tag.COMMENT)) {
2673                     // Comment outside of body, will not be able to show it,
2674                     // but can add it as a property on the Document.
2675                     addExternalComment(new String(data));
2676                     return;
2677                 }
2678                 SimpleAttributeSet sas = new SimpleAttributeSet();
2679                 sas.addAttribute(HTML.Attribute.COMMENT, new String(data));
2680                 addSpecialElement(HTML.Tag.COMMENT, sas);
2681             }
2682 
2683             TagAction action = tagMap.get(HTML.Tag.COMMENT);
2684             if (action != null) {
2685                 action.start(HTML.Tag.COMMENT, new SimpleAttributeSet());
2686                 action.end(HTML.Tag.COMMENT);
2687             }
2688         }
2689 
2690         /**
2691          * Adds the comment <code>comment</code> to the set of comments
2692          * maintained outside of the scope of elements.
2693          */
2694         private void addExternalComment(String comment) {
2695             Object comments = getProperty(AdditionalComments);
2696             if (comments != null && !(comments instanceof Vector)) {
2697                 // No place to put comment.
2698                 return;
2699             }
2700             if (comments == null) {
2701                 comments = new Vector<>();
2702                 putProperty(AdditionalComments, comments);
2703             }
2704             @SuppressWarnings("unchecked")
2705             Vector<Object> v = (Vector<Object>)comments;
2706             v.addElement(comment);
2707         }
2708 
2709         /**
2710          * Callback from the parser.  Route to the appropriate
2711          * handler for the tag.
2712          */
2713         public void handleEndTag(HTML.Tag t, int pos) {
2714             if (receivedEndHTML || (midInsert && !inBody)) {
2715                 return;
2716             }
2717             if (t == HTML.Tag.HTML) {
2718                 receivedEndHTML = true;
2719             }
2720             if (t == HTML.Tag.BODY) {
2721                 inBody = false;
2722                 if (midInsert) {
2723                     inBlock--;
2724                 }
2725             }
2726             TagAction action = tagMap.get(t);
2727             if (action != null) {
2728                 action.end(t);
2729             }
2730         }
2731 
2732         /**
2733          * Callback from the parser.  Route to the appropriate
2734          * handler for the tag.
2735          */
2736         public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
2737             if (receivedEndHTML || (midInsert && !inBody)) {
2738                 return;
2739             }
2740 
2741             if (isStyleCSS && a.isDefined(HTML.Attribute.STYLE)) {
2742                 // Map the style attributes.
2743                 String decl = (String)a.getAttribute(HTML.Attribute.STYLE);
2744                 a.removeAttribute(HTML.Attribute.STYLE);
2745                 styleAttributes = getStyleSheet().getDeclaration(decl);
2746                 a.addAttributes(styleAttributes);
2747             }
2748             else {
2749                 styleAttributes = null;
2750             }
2751 
2752             TagAction action = tagMap.get(t);
2753             if (action != null) {
2754                 action.start(t, a);
2755                 action.end(t);
2756             }
2757             else if (getPreservesUnknownTags()) {
2758                 // unknown tag, only add if should preserve it.
2759                 addSpecialElement(t, a);
2760             }
2761         }
2762 
2763         /**
2764          * This is invoked after the stream has been parsed, but before
2765          * <code>flush</code>. <code>eol</code> will be one of \n, \r
2766          * or \r\n, which ever is encountered the most in parsing the
2767          * stream.
2768          *
2769          * @since 1.3
2770          */
2771         public void handleEndOfLineString(String eol) {
2772             if (emptyDocument && eol != null) {
2773                 putProperty(DefaultEditorKit.EndOfLineStringProperty,
2774                             eol);
2775             }
2776         }
2777 
2778         // ---- tag handling support ------------------------------
2779 
2780         /**
2781          * Registers a handler for the given tag.  By default
2782          * all of the well-known tags will have been registered.
2783          * This can be used to change the handling of a particular
2784          * tag or to add support for custom tags.
2785          *
2786          * @param t an HTML tag
2787          * @param a tag action handler
2788          */
2789         protected void registerTag(HTML.Tag t, TagAction a) {
2790             tagMap.put(t, a);
2791         }
2792 
2793         /**
2794          * An action to be performed in response
2795          * to parsing a tag.  This allows customization
2796          * of how each tag is handled and avoids a large
2797          * switch statement.
2798          */
2799         public class TagAction {
2800 
2801             /**
2802              * Called when a start tag is seen for the
2803              * type of tag this action was registered
2804              * to.  The tag argument indicates the actual
2805              * tag for those actions that are shared across
2806              * many tags.  By default this does nothing and
2807              * completely ignores the tag.
2808              *
2809              * @param t the HTML tag
2810              * @param a the attributes
2811              */
2812             public void start(HTML.Tag t, MutableAttributeSet a) {
2813             }
2814 
2815             /**
2816              * Called when an end tag is seen for the
2817              * type of tag this action was registered
2818              * to.  The tag argument indicates the actual
2819              * tag for those actions that are shared across
2820              * many tags.  By default this does nothing and
2821              * completely ignores the tag.
2822              *
2823              * @param t the HTML tag
2824              */
2825             public void end(HTML.Tag t) {
2826             }
2827 
2828         }
2829 
2830         /**
2831          * Action assigned by default to handle the Block task of the reader.
2832          */
2833         public class BlockAction extends TagAction {
2834 
2835             public void start(HTML.Tag t, MutableAttributeSet attr) {
2836                 blockOpen(t, attr);
2837             }
2838 
2839             public void end(HTML.Tag t) {
2840                 blockClose(t);
2841             }
2842         }
2843 
2844 
2845         /**
2846          * Action used for the actual element form tag. This is named such
2847          * as there was already a public class named FormAction.
2848          */
2849         private class FormTagAction extends BlockAction {
2850             public void start(HTML.Tag t, MutableAttributeSet attr) {
2851                 super.start(t, attr);
2852                 // initialize a ButtonGroupsMap when
2853                 // FORM tag is encountered.  This will
2854                 // be used for any radio buttons that
2855                 // might be defined in the FORM.
2856                 // for new group new ButtonGroup will be created (fix for 4529702)
2857                 // group name is a key in radioButtonGroupsMap
2858                 radioButtonGroupsMap = new HashMap<String, ButtonGroup>();
2859             }
2860 
2861             public void end(HTML.Tag t) {
2862                 super.end(t);
2863                 // reset the button group to null since
2864                 // the form has ended.
2865                 radioButtonGroupsMap = null;
2866             }
2867         }
2868 
2869 
2870         /**
2871          * Action assigned by default to handle the Paragraph task of the reader.
2872          */
2873         public class ParagraphAction extends BlockAction {
2874 
2875             public void start(HTML.Tag t, MutableAttributeSet a) {
2876                 super.start(t, a);
2877                 inParagraph = true;
2878             }
2879 
2880             public void end(HTML.Tag t) {
2881                 super.end(t);
2882                 inParagraph = false;
2883             }
2884         }
2885 
2886         /**
2887          * Action assigned by default to handle the Special task of the reader.
2888          */
2889         public class SpecialAction extends TagAction {
2890 
2891             public void start(HTML.Tag t, MutableAttributeSet a) {
2892                 addSpecialElement(t, a);
2893             }
2894 
2895         }
2896 
2897         public class IsindexAction extends TagAction {
2898 
2899             public void start(HTML.Tag t, MutableAttributeSet a) {
2900                 blockOpen(HTML.Tag.IMPLIED, new SimpleAttributeSet());
2901                 addSpecialElement(t, a);
2902                 blockClose(HTML.Tag.IMPLIED);
2903             }
2904 
2905         }
2906 
2907 
2908         /**
2909          * Action assigned by default to handle the Hidden task of the reader.
2910          */
2911         public class HiddenAction extends TagAction {
2912 
2913             public void start(HTML.Tag t, MutableAttributeSet a) {
2914                 addSpecialElement(t, a);
2915             }
2916 
2917             public void end(HTML.Tag t) {
2918                 if (!isEmpty(t)) {
2919                     MutableAttributeSet a = new SimpleAttributeSet();
2920                     a.addAttribute(HTML.Attribute.ENDTAG, "true");
2921                     addSpecialElement(t, a);
2922                 }
2923             }
2924 
2925             boolean isEmpty(HTML.Tag t) {
2926                 if (t == HTML.Tag.APPLET ||
2927                     t == HTML.Tag.SCRIPT) {
2928                     return false;
2929                 }
2930                 return true;
2931             }
2932         }
2933 
2934 
2935         /**
2936          * Subclass of HiddenAction to set the content type for style sheets,
2937          * and to set the name of the default style sheet.
2938          */
2939         class MetaAction extends HiddenAction {
2940 
2941             public void start(HTML.Tag t, MutableAttributeSet a) {
2942                 Object equiv = a.getAttribute(HTML.Attribute.HTTPEQUIV);
2943                 if (equiv != null) {
2944                     equiv = ((String)equiv).toLowerCase();
2945                     if (equiv.equals("content-style-type")) {
2946                         String value = (String)a.getAttribute
2947                                        (HTML.Attribute.CONTENT);
2948                         setDefaultStyleSheetType(value);
2949                         isStyleCSS = "text/css".equals
2950                                       (getDefaultStyleSheetType());
2951                     }
2952                     else if (equiv.equals("default-style")) {
2953                         defaultStyle = (String)a.getAttribute
2954                                        (HTML.Attribute.CONTENT);
2955                     }
2956                 }
2957                 super.start(t, a);
2958             }
2959 
2960             boolean isEmpty(HTML.Tag t) {
2961                 return true;
2962             }
2963         }
2964 
2965 
2966         /**
2967          * End if overridden to create the necessary stylesheets that
2968          * are referenced via the link tag. It is done in this manner
2969          * as the meta tag can be used to specify an alternate style sheet,
2970          * and is not guaranteed to come before the link tags.
2971          */
2972         class HeadAction extends BlockAction {
2973 
2974             public void start(HTML.Tag t, MutableAttributeSet a) {
2975                 inHead = true;
2976                 // This check of the insertTag is put in to avoid considering
2977                 // the implied-p that is generated for the head. This allows
2978                 // inserts for HR to work correctly.
2979                 if ((insertTag == null && !insertAfterImplied) ||
2980                     (insertTag == HTML.Tag.HEAD) ||
2981                     (insertAfterImplied &&
2982                      (foundInsertTag || !a.isDefined(IMPLIED)))) {
2983                     super.start(t, a);
2984                 }
2985             }
2986 
2987             public void end(HTML.Tag t) {
2988                 inHead = inStyle = false;
2989                 // See if there is a StyleSheet to link to.
2990                 if (styles != null) {
2991                     boolean isDefaultCSS = isStyleCSS;
2992                     for (int counter = 0, maxCounter = styles.size();
2993                          counter < maxCounter;) {
2994                         Object value = styles.elementAt(counter);
2995                         if (value == HTML.Tag.LINK) {
2996                             handleLink((AttributeSet)styles.
2997                                        elementAt(++counter));
2998                             counter++;
2999                         }
3000                         else {
3001                             // Rule.
3002                             // First element gives type.
3003                             String type = (String)styles.elementAt(++counter);
3004                             boolean isCSS = (type == null) ? isDefaultCSS :
3005                                             type.equals("text/css");
3006                             while (++counter < maxCounter &&
3007                                    (styles.elementAt(counter)
3008                                     instanceof String)) {
3009                                 if (isCSS) {
3010                                     addCSSRules((String)styles.elementAt
3011                                                 (counter));
3012                                 }
3013                             }
3014                         }
3015                     }
3016                 }
3017                 if ((insertTag == null && !insertAfterImplied) ||
3018                     insertTag == HTML.Tag.HEAD ||
3019                     (insertAfterImplied && foundInsertTag)) {
3020                     super.end(t);
3021                 }
3022             }
3023 
3024             boolean isEmpty(HTML.Tag t) {
3025                 return false;
3026             }
3027 
3028             private void handleLink(AttributeSet attr) {
3029                 // Link.
3030                 String type = (String)attr.getAttribute(HTML.Attribute.TYPE);
3031                 if (type == null) {
3032                     type = getDefaultStyleSheetType();
3033                 }
3034                 // Only choose if type==text/css
3035                 // Select link if rel==stylesheet.
3036                 // Otherwise if rel==alternate stylesheet and
3037                 //   title matches default style.
3038                 if (type.equals("text/css")) {
3039                     String rel = (String)attr.getAttribute(HTML.Attribute.REL);
3040                     String title = (String)attr.getAttribute
3041                                                (HTML.Attribute.TITLE);
3042                     String media = (String)attr.getAttribute
3043                                                    (HTML.Attribute.MEDIA);
3044                     if (media == null) {
3045                         media = "all";
3046                     }
3047                     else {
3048                         media = media.toLowerCase();
3049                     }
3050                     if (rel != null) {
3051                         rel = rel.toLowerCase();
3052                         if ((media.indexOf("all") != -1 ||
3053                              media.indexOf("screen") != -1) &&
3054                             (rel.equals("stylesheet") ||
3055                              (rel.equals("alternate stylesheet") &&
3056                               title.equals(defaultStyle)))) {
3057                             linkCSSStyleSheet((String)attr.getAttribute
3058                                               (HTML.Attribute.HREF));
3059                         }
3060                     }
3061                 }
3062             }
3063         }
3064 
3065 
3066         /**
3067          * A subclass to add the AttributeSet to styles if the
3068          * attributes contains an attribute for 'rel' with value
3069          * 'stylesheet' or 'alternate stylesheet'.
3070          */
3071         class LinkAction extends HiddenAction {
3072 
3073             public void start(HTML.Tag t, MutableAttributeSet a) {
3074                 String rel = (String)a.getAttribute(HTML.Attribute.REL);
3075                 if (rel != null) {
3076                     rel = rel.toLowerCase();
3077                     if (rel.equals("stylesheet") ||
3078                         rel.equals("alternate stylesheet")) {
3079                         if (styles == null) {
3080                             styles = new Vector<Object>(3);
3081                         }
3082                         styles.addElement(t);
3083                         styles.addElement(a.copyAttributes());
3084                     }
3085                 }
3086                 super.start(t, a);
3087             }
3088         }
3089 
3090         class MapAction extends TagAction {
3091 
3092             public void start(HTML.Tag t, MutableAttributeSet a) {
3093                 lastMap = new Map((String)a.getAttribute(HTML.Attribute.NAME));
3094                 addMap(lastMap);
3095             }
3096 
3097             public void end(HTML.Tag t) {
3098             }
3099         }
3100 
3101 
3102         class AreaAction extends TagAction {
3103 
3104             public void start(HTML.Tag t, MutableAttributeSet a) {
3105                 if (lastMap != null) {
3106                     lastMap.addArea(a.copyAttributes());
3107                 }
3108             }
3109 
3110             public void end(HTML.Tag t) {
3111             }
3112         }
3113 
3114 
3115         class StyleAction extends TagAction {
3116 
3117             public void start(HTML.Tag t, MutableAttributeSet a) {
3118                 if (inHead) {
3119                     if (styles == null) {
3120                         styles = new Vector<Object>(3);
3121                     }
3122                     styles.addElement(t);
3123                     styles.addElement(a.getAttribute(HTML.Attribute.TYPE));
3124                     inStyle = true;
3125                 }
3126             }
3127 
3128             public void end(HTML.Tag t) {
3129                 inStyle = false;
3130             }
3131 
3132             boolean isEmpty(HTML.Tag t) {
3133                 return false;
3134             }
3135         }
3136 
3137 
3138         public class PreAction extends BlockAction {
3139 
3140             public void start(HTML.Tag t, MutableAttributeSet attr) {
3141                 inPre = true;
3142                 blockOpen(t, attr);
3143                 attr.addAttribute(CSS.Attribute.WHITE_SPACE, "pre");
3144                 blockOpen(HTML.Tag.IMPLIED, attr);
3145             }
3146 
3147             public void end(HTML.Tag t) {
3148                 blockClose(HTML.Tag.IMPLIED);
3149                 // set inPre to false after closing, so that if a newline
3150                 // is added it won't generate a blockOpen.
3151                 inPre = false;
3152                 blockClose(t);
3153             }
3154         }
3155 
3156         /**
3157          * Action assigned by default to handle the Character task of the reader.
3158          */
3159         public class CharacterAction extends TagAction {
3160 
3161             public void start(HTML.Tag t, MutableAttributeSet attr) {
3162                 pushCharacterStyle();
3163                 if (!foundInsertTag) {
3164                     // Note that the third argument should really be based off
3165                     // inParagraph and impliedP. If we're wrong (that is
3166                     // insertTagDepthDelta shouldn't be changed), we'll end up
3167                     // removing an extra EndSpec, which won't matter anyway.
3168                     boolean insert = canInsertTag(t, attr, false);
3169                     if (foundInsertTag) {
3170                         if (!inParagraph) {
3171                             inParagraph = impliedP = true;
3172                         }
3173                     }
3174                     if (!insert) {
3175                         return;
3176                     }
3177                 }
3178                 if (attr.isDefined(IMPLIED)) {
3179                     attr.removeAttribute(IMPLIED);
3180                 }
3181                 charAttr.addAttribute(t, attr.copyAttributes());
3182                 if (styleAttributes != null) {
3183                     charAttr.addAttributes(styleAttributes);
3184                 }
3185             }
3186 
3187             public void end(HTML.Tag t) {
3188                 popCharacterStyle();
3189             }
3190         }
3191 
3192         /**
3193          * Provides conversion of HTML tag/attribute
3194          * mappings that have a corresponding StyleConstants
3195          * and CSS mapping.  The conversion is to CSS attributes.
3196          */
3197         class ConvertAction extends TagAction {
3198 
3199             public void start(HTML.Tag t, MutableAttributeSet attr) {
3200                 pushCharacterStyle();
3201                 if (!foundInsertTag) {
3202                     // Note that the third argument should really be based off
3203                     // inParagraph and impliedP. If we're wrong (that is
3204                     // insertTagDepthDelta shouldn't be changed), we'll end up
3205                     // removing an extra EndSpec, which won't matter anyway.
3206                     boolean insert = canInsertTag(t, attr, false);
3207                     if (foundInsertTag) {
3208                         if (!inParagraph) {
3209                             inParagraph = impliedP = true;
3210                         }
3211                     }
3212                     if (!insert) {
3213                         return;
3214                     }
3215                 }
3216                 if (attr.isDefined(IMPLIED)) {
3217                     attr.removeAttribute(IMPLIED);
3218                 }
3219                 if (styleAttributes != null) {
3220                     charAttr.addAttributes(styleAttributes);
3221                 }
3222                 // We also need to add attr, otherwise we lose custom
3223                 // attributes, including class/id for style lookups, and
3224                 // further confuse style lookup (doesn't have tag).
3225                 charAttr.addAttribute(t, attr.copyAttributes());
3226                 StyleSheet sheet = getStyleSheet();
3227                 if (t == HTML.Tag.B) {
3228                     sheet.addCSSAttribute(charAttr, CSS.Attribute.FONT_WEIGHT, "bold");
3229                 } else if (t == HTML.Tag.I) {
3230                     sheet.addCSSAttribute(charAttr, CSS.Attribute.FONT_STYLE, "italic");
3231                 } else if (t == HTML.Tag.U) {
3232                     Object v = charAttr.getAttribute(CSS.Attribute.TEXT_DECORATION);
3233                     String value = "underline";
3234                     value = (v != null) ? value + "," + v.toString() : value;
3235                     sheet.addCSSAttribute(charAttr, CSS.Attribute.TEXT_DECORATION, value);
3236                 } else if (t == HTML.Tag.STRIKE) {
3237                     Object v = charAttr.getAttribute(CSS.Attribute.TEXT_DECORATION);
3238                     String value = "line-through";
3239                     value = (v != null) ? value + "," + v.toString() : value;
3240                     sheet.addCSSAttribute(charAttr, CSS.Attribute.TEXT_DECORATION, value);
3241                 } else if (t == HTML.Tag.SUP) {
3242                     Object v = charAttr.getAttribute(CSS.Attribute.VERTICAL_ALIGN);
3243                     String value = "sup";
3244                     value = (v != null) ? value + "," + v.toString() : value;
3245                     sheet.addCSSAttribute(charAttr, CSS.Attribute.VERTICAL_ALIGN, value);
3246                 } else if (t == HTML.Tag.SUB) {
3247                     Object v = charAttr.getAttribute(CSS.Attribute.VERTICAL_ALIGN);
3248                     String value = "sub";
3249                     value = (v != null) ? value + "," + v.toString() : value;
3250                     sheet.addCSSAttribute(charAttr, CSS.Attribute.VERTICAL_ALIGN, value);
3251                 } else if (t == HTML.Tag.FONT) {
3252                     String color = (String) attr.getAttribute(HTML.Attribute.COLOR);
3253                     if (color != null) {
3254                         sheet.addCSSAttribute(charAttr, CSS.Attribute.COLOR, color);
3255                     }
3256                     String face = (String) attr.getAttribute(HTML.Attribute.FACE);
3257                     if (face != null) {
3258                         sheet.addCSSAttribute(charAttr, CSS.Attribute.FONT_FAMILY, face);
3259                     }
3260                     String size = (String) attr.getAttribute(HTML.Attribute.SIZE);
3261                     if (size != null) {
3262                         sheet.addCSSAttributeFromHTML(charAttr, CSS.Attribute.FONT_SIZE, size);
3263                     }
3264                 }
3265             }
3266 
3267             public void end(HTML.Tag t) {
3268                 popCharacterStyle();
3269             }
3270 
3271         }
3272 
3273         class AnchorAction extends CharacterAction {
3274 
3275             public void start(HTML.Tag t, MutableAttributeSet attr) {
3276                 // set flag to catch empty anchors
3277                 emptyAnchor = true;
3278                 super.start(t, attr);
3279             }
3280 
3281             public void end(HTML.Tag t) {
3282                 if (emptyAnchor) {
3283                     // if the anchor was empty it was probably a
3284                     // named anchor point and we don't want to throw
3285                     // it away.
3286                     char[] one = new char[1];
3287                     one[0] = '\n';
3288                     addContent(one, 0, 1);
3289                 }
3290                 super.end(t);
3291             }
3292         }
3293 
3294         class TitleAction extends HiddenAction {
3295 
3296             public void start(HTML.Tag t, MutableAttributeSet attr) {
3297                 inTitle = true;
3298                 super.start(t, attr);
3299             }
3300 
3301             public void end(HTML.Tag t) {
3302                 inTitle = false;
3303                 super.end(t);
3304             }
3305 
3306             boolean isEmpty(HTML.Tag t) {
3307                 return false;
3308             }
3309         }
3310 
3311 
3312         class BaseAction extends TagAction {
3313 
3314             public void start(HTML.Tag t, MutableAttributeSet attr) {
3315                 String href = (String) attr.getAttribute(HTML.Attribute.HREF);
3316                 if (href != null) {
3317                     try {
3318                         URL newBase = new URL(base, href);
3319                         setBase(newBase);
3320                         hasBaseTag = true;
3321                     } catch (MalformedURLException ex) {
3322                     }
3323                 }
3324                 baseTarget = (String) attr.getAttribute(HTML.Attribute.TARGET);
3325             }
3326         }
3327 
3328         class ObjectAction extends SpecialAction {
3329 
3330             public void start(HTML.Tag t, MutableAttributeSet a) {
3331                 if (t == HTML.Tag.PARAM) {
3332                     addParameter(a);
3333                 } else {
3334                     super.start(t, a);
3335                 }
3336             }
3337 
3338             public void end(HTML.Tag t) {
3339                 if (t != HTML.Tag.PARAM) {
3340                     super.end(t);
3341                 }
3342             }
3343 
3344             void addParameter(AttributeSet a) {
3345                 String name = (String) a.getAttribute(HTML.Attribute.NAME);
3346                 String value = (String) a.getAttribute(HTML.Attribute.VALUE);
3347                 if ((name != null) && (value != null)) {
3348                     ElementSpec objSpec = parseBuffer.lastElement();
3349                     MutableAttributeSet objAttr = (MutableAttributeSet) objSpec.getAttributes();
3350                     objAttr.addAttribute(name, value);
3351                 }
3352             }
3353         }
3354 
3355         /**
3356          * Action to support forms by building all of the elements
3357          * used to represent form controls.  This will process
3358          * the &lt;INPUT&gt;, &lt;TEXTAREA&gt;, &lt;SELECT&gt;,
3359          * and &lt;OPTION&gt; tags.  The element created by
3360          * this action is expected to have the attribute
3361          * <code>StyleConstants.ModelAttribute</code> set to
3362          * the model that holds the state for the form control.
3363          * This enables multiple views, and allows document to
3364          * be iterated over picking up the data of the form.
3365          * The following are the model assignments for the
3366          * various type of form elements.
3367          * <table summary="model assignments for the various types of form elements">
3368          * <tr>
3369          *   <th>Element Type
3370          *   <th>Model Type
3371          * <tr>
3372          *   <td>input, type button
3373          *   <td>{@link DefaultButtonModel}
3374          * <tr>
3375          *   <td>input, type checkbox
3376          *   <td>{@link javax.swing.JToggleButton.ToggleButtonModel}
3377          * <tr>
3378          *   <td>input, type image
3379          *   <td>{@link DefaultButtonModel}
3380          * <tr>
3381          *   <td>input, type password
3382          *   <td>{@link PlainDocument}
3383          * <tr>
3384          *   <td>input, type radio
3385          *   <td>{@link javax.swing.JToggleButton.ToggleButtonModel}
3386          * <tr>
3387          *   <td>input, type reset
3388          *   <td>{@link DefaultButtonModel}
3389          * <tr>
3390          *   <td>input, type submit
3391          *   <td>{@link DefaultButtonModel}
3392          * <tr>
3393          *   <td>input, type text or type is null.
3394          *   <td>{@link PlainDocument}
3395          * <tr>
3396          *   <td>select
3397          *   <td>{@link DefaultComboBoxModel} or an {@link DefaultListModel}, with an item type of Option
3398          * <tr>
3399          *   <td>textarea
3400          *   <td>{@link PlainDocument}
3401          * </table>
3402          *
3403          */
3404         public class FormAction extends SpecialAction {
3405 
3406             public void start(HTML.Tag t, MutableAttributeSet attr) {
3407                 if (t == HTML.Tag.INPUT) {
3408                     String type = (String)
3409                         attr.getAttribute(HTML.Attribute.TYPE);
3410                     /*
3411                      * if type is not defined the default is
3412                      * assumed to be text.
3413                      */
3414                     if (type == null) {
3415                         type = "text";
3416                         attr.addAttribute(HTML.Attribute.TYPE, "text");
3417                     }
3418                     setModel(type, attr);
3419                 } else if (t == HTML.Tag.TEXTAREA) {
3420                     inTextArea = true;
3421                     textAreaDocument = new TextAreaDocument();
3422                     attr.addAttribute(StyleConstants.ModelAttribute,
3423                                       textAreaDocument);
3424                 } else if (t == HTML.Tag.SELECT) {
3425                     int size = HTML.getIntegerAttributeValue(attr,
3426                                                              HTML.Attribute.SIZE,
3427                                                              1);
3428                     boolean multiple = attr.getAttribute(HTML.Attribute.MULTIPLE) != null;
3429                     if ((size > 1) || multiple) {
3430                         OptionListModel<Option> m = new OptionListModel<Option>();
3431                         if (multiple) {
3432                             m.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
3433                         }
3434                         selectModel = m;
3435                     } else {
3436                         selectModel = new OptionComboBoxModel<Option>();
3437                     }
3438                     attr.addAttribute(StyleConstants.ModelAttribute,
3439                                       selectModel);
3440 
3441                 }
3442 
3443                 // build the element, unless this is an option.
3444                 if (t == HTML.Tag.OPTION) {
3445                     option = new Option(attr);
3446 
3447                     if (selectModel instanceof OptionListModel) {
3448                         @SuppressWarnings("unchecked")
3449                         OptionListModel<Option> m = (OptionListModel<Option>) selectModel;
3450                         m.addElement(option);
3451                         if (option.isSelected()) {
3452                             m.addSelectionInterval(optionCount, optionCount);
3453                             m.setInitialSelection(optionCount);
3454                         }
3455                     } else if (selectModel instanceof OptionComboBoxModel) {
3456                         @SuppressWarnings("unchecked")
3457                         OptionComboBoxModel<Option> m = (OptionComboBoxModel<Option>) selectModel;
3458                         m.addElement(option);
3459                         if (option.isSelected()) {
3460                             m.setSelectedItem(option);
3461                             m.setInitialSelection(option);
3462                         }
3463                     }
3464                     optionCount++;
3465                 } else {
3466                     super.start(t, attr);
3467                 }
3468             }
3469 
3470             public void end(HTML.Tag t) {
3471                 if (t == HTML.Tag.OPTION) {
3472                     option = null;
3473                 } else {
3474                     if (t == HTML.Tag.SELECT) {
3475                         selectModel = null;
3476                         optionCount = 0;
3477                     } else if (t == HTML.Tag.TEXTAREA) {
3478                         inTextArea = false;
3479 
3480                         /* Now that the textarea has ended,
3481                          * store the entire initial text
3482                          * of the text area.  This will
3483                          * enable us to restore the initial
3484                          * state if a reset is requested.
3485                          */
3486                         textAreaDocument.storeInitialText();
3487                     }
3488                     super.end(t);
3489                 }
3490             }
3491 
3492             void setModel(String type, MutableAttributeSet attr) {
3493                 if (type.equals("submit") ||
3494                     type.equals("reset") ||
3495                     type.equals("image")) {
3496 
3497                     // button model
3498                     attr.addAttribute(StyleConstants.ModelAttribute,
3499                                       new DefaultButtonModel());
3500                 } else if (type.equals("text") ||
3501                            type.equals("password")) {
3502                     // plain text model
3503                     int maxLength = HTML.getIntegerAttributeValue(
3504                                        attr, HTML.Attribute.MAXLENGTH, -1);
3505                     Document doc;
3506 
3507                     if (maxLength > 0) {
3508                         doc = new FixedLengthDocument(maxLength);
3509                     }
3510                     else {
3511                         doc = new PlainDocument();
3512                     }
3513                     String value = (String)
3514                         attr.getAttribute(HTML.Attribute.VALUE);
3515                     try {
3516                         doc.insertString(0, value, null);
3517                     } catch (BadLocationException e) {
3518                     }
3519                     attr.addAttribute(StyleConstants.ModelAttribute, doc);
3520                 } else if (type.equals("file")) {
3521                     // plain text model
3522                     attr.addAttribute(StyleConstants.ModelAttribute,
3523                                       new PlainDocument());
3524                 } else if (type.equals("checkbox") ||
3525                            type.equals("radio")) {
3526                     JToggleButton.ToggleButtonModel model = new JToggleButton.ToggleButtonModel();
3527                     if (type.equals("radio")) {
3528                         String name = (String) attr.getAttribute(HTML.Attribute.NAME);
3529                         if ( radioButtonGroupsMap == null ) { //fix for 4772743
3530                            radioButtonGroupsMap = new HashMap<String, ButtonGroup>();
3531                         }
3532                         ButtonGroup radioButtonGroup = radioButtonGroupsMap.get(name);
3533                         if (radioButtonGroup == null) {
3534                             radioButtonGroup = new ButtonGroup();
3535                             radioButtonGroupsMap.put(name,radioButtonGroup);
3536                         }
3537                         model.setGroup(radioButtonGroup);
3538                     }
3539                     boolean checked = (attr.getAttribute(HTML.Attribute.CHECKED) != null);
3540                     model.setSelected(checked);
3541                     attr.addAttribute(StyleConstants.ModelAttribute, model);
3542                 }
3543             }
3544 
3545             /**
3546              * If a &lt;SELECT&gt; tag is being processed, this
3547              * model will be a reference to the model being filled
3548              * with the &lt;OPTION&gt; elements (which produce
3549              * objects of type <code>Option</code>.
3550              */
3551             Object selectModel;
3552             int optionCount;
3553         }
3554 
3555 
3556         // --- utility methods used by the reader ------------------
3557 
3558         /**
3559          * Pushes the current character style on a stack in preparation
3560          * for forming a new nested character style.
3561          */
3562         protected void pushCharacterStyle() {
3563             charAttrStack.push(charAttr.copyAttributes());
3564         }
3565 
3566         /**
3567          * Pops a previously pushed character style off the stack
3568          * to return to a previous style.
3569          */
3570         protected void popCharacterStyle() {
3571             if (!charAttrStack.empty()) {
3572                 charAttr = (MutableAttributeSet) charAttrStack.peek();
3573                 charAttrStack.pop();
3574             }
3575         }
3576 
3577         /**
3578          * Adds the given content to the textarea document.
3579          * This method gets called when we are in a textarea
3580          * context.  Therefore all text that is seen belongs
3581          * to the text area and is hence added to the
3582          * TextAreaDocument associated with the text area.
3583          *
3584          * @param data the given content
3585          */
3586         protected void textAreaContent(char[] data) {
3587             try {
3588                 textAreaDocument.insertString(textAreaDocument.getLength(), new String(data), null);
3589             } catch (BadLocationException e) {
3590                 // Should do something reasonable
3591             }
3592         }
3593 
3594         /**
3595          * Adds the given content that was encountered in a
3596          * PRE element.  This synthesizes lines to hold the
3597          * runs of text, and makes calls to addContent to
3598          * actually add the text.
3599          *
3600          * @param data the given content
3601          */
3602         protected void preContent(char[] data) {
3603             int last = 0;
3604             for (int i = 0; i < data.length; i++) {
3605                 if (data[i] == '\n') {
3606                     addContent(data, last, i - last + 1);
3607                     blockClose(HTML.Tag.IMPLIED);
3608                     MutableAttributeSet a = new SimpleAttributeSet();
3609                     a.addAttribute(CSS.Attribute.WHITE_SPACE, "pre");
3610                     blockOpen(HTML.Tag.IMPLIED, a);
3611                     last = i + 1;
3612                 }
3613             }
3614             if (last < data.length) {
3615                 addContent(data, last, data.length - last);
3616             }
3617         }
3618 
3619         /**
3620          * Adds an instruction to the parse buffer to create a
3621          * block element with the given attributes.
3622          *
3623          * @param t an HTML tag
3624          * @param attr the attribute set
3625          */
3626         protected void blockOpen(HTML.Tag t, MutableAttributeSet attr) {
3627             if (impliedP) {
3628                 blockClose(HTML.Tag.IMPLIED);
3629             }
3630 
3631             inBlock++;
3632 
3633             if (!canInsertTag(t, attr, true)) {
3634                 return;
3635             }
3636             if (attr.isDefined(IMPLIED)) {
3637                 attr.removeAttribute(IMPLIED);
3638             }
3639             lastWasNewline = false;
3640             attr.addAttribute(StyleConstants.NameAttribute, t);
3641             ElementSpec es = new ElementSpec(
3642                 attr.copyAttributes(), ElementSpec.StartTagType);
3643             parseBuffer.addElement(es);
3644         }
3645 
3646         /**
3647          * Adds an instruction to the parse buffer to close out
3648          * a block element of the given type.
3649          *
3650          * @param t the HTML tag
3651          */
3652         protected void blockClose(HTML.Tag t) {
3653             inBlock--;
3654 
3655             if (!foundInsertTag) {
3656                 return;
3657             }
3658 
3659             // Add a new line, if the last character wasn't one. This is
3660             // needed for proper positioning of the cursor. addContent
3661             // with true will force an implied paragraph to be generated if
3662             // there isn't one. This may result in a rather bogus structure
3663             // (perhaps a table with a child pargraph), but the paragraph
3664             // is needed for proper positioning and display.
3665             if(!lastWasNewline) {
3666                 pushCharacterStyle();
3667                 charAttr.addAttribute(IMPLIED_CR, Boolean.TRUE);
3668                 addContent(NEWLINE, 0, 1, true);
3669                 popCharacterStyle();
3670                 lastWasNewline = true;
3671             }
3672 
3673             if (impliedP) {
3674                 impliedP = false;
3675                 inParagraph = false;
3676                 if (t != HTML.Tag.IMPLIED) {
3677                     blockClose(HTML.Tag.IMPLIED);
3678                 }
3679             }
3680             // an open/close with no content will be removed, so we
3681             // add a space of content to keep the element being formed.
3682             ElementSpec prev = (parseBuffer.size() > 0) ?
3683                 parseBuffer.lastElement() : null;
3684             if (prev != null && prev.getType() == ElementSpec.StartTagType) {
3685                 char[] one = new char[1];
3686                 one[0] = ' ';
3687                 addContent(one, 0, 1);
3688             }
3689             ElementSpec es = new ElementSpec(
3690                 null, ElementSpec.EndTagType);
3691             parseBuffer.addElement(es);
3692         }
3693 
3694         /**
3695          * Adds some text with the current character attributes.
3696          *
3697          * @param data the content to add
3698          * @param offs the initial offset
3699          * @param length the length
3700          */
3701         protected void addContent(char[] data, int offs, int length) {
3702             addContent(data, offs, length, true);
3703         }
3704 
3705         /**
3706          * Adds some text with the current character attributes.
3707          *
3708          * @param data the content to add
3709          * @param offs the initial offset
3710          * @param length the length
3711          * @param generateImpliedPIfNecessary whether to generate implied
3712          * paragraphs
3713          */
3714         protected void addContent(char[] data, int offs, int length,
3715                                   boolean generateImpliedPIfNecessary) {
3716             if (!foundInsertTag) {
3717                 return;
3718             }
3719 
3720             if (generateImpliedPIfNecessary && (! inParagraph) && (! inPre)) {
3721                 blockOpen(HTML.Tag.IMPLIED, new SimpleAttributeSet());
3722                 inParagraph = true;
3723                 impliedP = true;
3724             }
3725             emptyAnchor = false;
3726             charAttr.addAttribute(StyleConstants.NameAttribute, HTML.Tag.CONTENT);
3727             AttributeSet a = charAttr.copyAttributes();
3728             ElementSpec es = new ElementSpec(
3729                 a, ElementSpec.ContentType, data, offs, length);
3730             parseBuffer.addElement(es);
3731 
3732             if (parseBuffer.size() > threshold) {
3733                 if ( threshold <= MaxThreshold ) {
3734                     threshold *= StepThreshold;
3735                 }
3736                 try {
3737                     flushBuffer(false);
3738                 } catch (BadLocationException ble) {
3739                 }
3740             }
3741             if(length > 0) {
3742                 lastWasNewline = (data[offs + length - 1] == '\n');
3743             }
3744         }
3745 
3746         /**
3747          * Adds content that is basically specified entirely
3748          * in the attribute set.
3749          *
3750          * @param t an HTML tag
3751          * @param a the attribute set
3752          */
3753         protected void addSpecialElement(HTML.Tag t, MutableAttributeSet a) {
3754             if ((t != HTML.Tag.FRAME) && (! inParagraph) && (! inPre)) {
3755                 nextTagAfterPImplied = t;
3756                 blockOpen(HTML.Tag.IMPLIED, new SimpleAttributeSet());
3757                 nextTagAfterPImplied = null;
3758                 inParagraph = true;
3759                 impliedP = true;
3760             }
3761             if (!canInsertTag(t, a, t.isBlock())) {
3762                 return;
3763             }
3764             if (a.isDefined(IMPLIED)) {
3765                 a.removeAttribute(IMPLIED);
3766             }
3767             emptyAnchor = false;
3768             a.addAttributes(charAttr);
3769             a.addAttribute(StyleConstants.NameAttribute, t);
3770             char[] one = new char[1];
3771             one[0] = ' ';
3772             ElementSpec es = new ElementSpec(
3773                 a.copyAttributes(), ElementSpec.ContentType, one, 0, 1);
3774             parseBuffer.addElement(es);
3775             // Set this to avoid generating a newline for frames, frames
3776             // shouldn't have any content, and shouldn't need a newline.
3777             if (t == HTML.Tag.FRAME) {
3778                 lastWasNewline = true;
3779             }
3780         }
3781 
3782         /**
3783          * Flushes the current parse buffer into the document.
3784          * @param endOfStream true if there is no more content to parser
3785          */
3786         void flushBuffer(boolean endOfStream) throws BadLocationException {
3787             int oldLength = HTMLDocument.this.getLength();
3788             int size = parseBuffer.size();
3789             if (endOfStream && (insertTag != null || insertAfterImplied) &&
3790                 size > 0) {
3791                 adjustEndSpecsForPartialInsert();
3792                 size = parseBuffer.size();
3793             }
3794             ElementSpec[] spec = new ElementSpec[size];
3795             parseBuffer.copyInto(spec);
3796 
3797             if (oldLength == 0 && (insertTag == null && !insertAfterImplied)) {
3798                 create(spec);
3799             } else {
3800                 insert(offset, spec);
3801             }
3802             parseBuffer.removeAllElements();
3803             offset += HTMLDocument.this.getLength() - oldLength;
3804             flushCount++;
3805         }
3806 
3807         /**
3808          * This will be invoked for the last flush, if <code>insertTag</code>
3809          * is non null.
3810          */
3811         private void adjustEndSpecsForPartialInsert() {
3812             int size = parseBuffer.size();
3813             if (insertTagDepthDelta < 0) {
3814                 // When inserting via an insertTag, the depths (of the tree
3815                 // being read in, and existing hierarchy) may not match up.
3816                 // This attemps to clean it up.
3817                 int removeCounter = insertTagDepthDelta;
3818                 while (removeCounter < 0 && size >= 0 &&
3819                         parseBuffer.elementAt(size - 1).
3820                        getType() == ElementSpec.EndTagType) {
3821                     parseBuffer.removeElementAt(--size);
3822                     removeCounter++;
3823                 }
3824             }
3825             if (flushCount == 0 && (!insertAfterImplied ||
3826                                     !wantsTrailingNewline)) {
3827                 // If this starts with content (or popDepth > 0 &&
3828                 // pushDepth > 0) and ends with EndTagTypes, make sure
3829                 // the last content isn't a \n, otherwise will end up with
3830                 // an extra \n in the middle of content.
3831                 int index = 0;
3832                 if (pushDepth > 0) {
3833                     if (parseBuffer.elementAt(0).getType() ==
3834                         ElementSpec.ContentType) {
3835                         index++;
3836                     }
3837                 }
3838                 index += (popDepth + pushDepth);
3839                 int cCount = 0;
3840                 int cStart = index;
3841                 while (index < size && parseBuffer.elementAt
3842                         (index).getType() == ElementSpec.ContentType) {
3843                     index++;
3844                     cCount++;
3845                 }
3846                 if (cCount > 1) {
3847                     while (index < size && parseBuffer.elementAt
3848                             (index).getType() == ElementSpec.EndTagType) {
3849                         index++;
3850                     }
3851                     if (index == size) {
3852                         char[] lastText = parseBuffer.elementAt
3853                                 (cStart + cCount - 1).getArray();
3854                         if (lastText.length == 1 && lastText[0] == NEWLINE[0]){
3855                             index = cStart + cCount - 1;
3856                             while (size > index) {
3857                                 parseBuffer.removeElementAt(--size);
3858                             }
3859                         }
3860                     }
3861                 }
3862             }
3863             if (wantsTrailingNewline) {
3864                 // Make sure there is in fact a newline
3865                 for (int counter = parseBuffer.size() - 1; counter >= 0;
3866                                    counter--) {
3867                     ElementSpec spec = parseBuffer.elementAt(counter);
3868                     if (spec.getType() == ElementSpec.ContentType) {
3869                         if (spec.getArray()[spec.getLength() - 1] != '\n') {
3870                             SimpleAttributeSet attrs =new SimpleAttributeSet();
3871 
3872                             attrs.addAttribute(StyleConstants.NameAttribute,
3873                                                HTML.Tag.CONTENT);
3874                             parseBuffer.insertElementAt(new ElementSpec(
3875                                     attrs,
3876                                     ElementSpec.ContentType, NEWLINE, 0, 1),
3877                                     counter + 1);
3878                         }
3879                         break;
3880                     }
3881                 }
3882             }
3883         }
3884 
3885         /**
3886          * Adds the CSS rules in <code>rules</code>.
3887          */
3888         void addCSSRules(String rules) {
3889             StyleSheet ss = getStyleSheet();
3890             ss.addRule(rules);
3891         }
3892 
3893         /**
3894          * Adds the CSS stylesheet at <code>href</code> to the known list
3895          * of stylesheets.
3896          */
3897         void linkCSSStyleSheet(String href) {
3898             URL url;
3899             try {
3900                 url = new URL(base, href);
3901             } catch (MalformedURLException mfe) {
3902                 try {
3903                     url = new URL(href);
3904                 } catch (MalformedURLException mfe2) {
3905                     url = null;
3906                 }
3907             }
3908             if (url != null) {
3909                 getStyleSheet().importStyleSheet(url);
3910             }
3911         }
3912 
3913         /**
3914          * Returns true if can insert starting at <code>t</code>. This
3915          * will return false if the insert tag is set, and hasn't been found
3916          * yet.
3917          */
3918         private boolean canInsertTag(HTML.Tag t, AttributeSet attr,
3919                                      boolean isBlockTag) {
3920             if (!foundInsertTag) {
3921                 boolean needPImplied = ((t == HTML.Tag.IMPLIED)
3922                                                           && (!inParagraph)
3923                                                           && (!inPre));
3924                 if (needPImplied && (nextTagAfterPImplied != null)) {
3925 
3926                     /*
3927                      * If insertTag == null then just proceed to
3928                      * foundInsertTag() call below and return true.
3929                      */
3930                     if (insertTag != null) {
3931                         boolean nextTagIsInsertTag =
3932                                 isInsertTag(nextTagAfterPImplied);
3933                         if ( (! nextTagIsInsertTag) || (! insertInsertTag) ) {
3934                             return false;
3935                         }
3936                     }
3937                     /*
3938                      *  Proceed to foundInsertTag() call...
3939                      */
3940                  } else if ((insertTag != null && !isInsertTag(t))
3941                                || (insertAfterImplied
3942                                     && (attr == null
3943                                         || attr.isDefined(IMPLIED)
3944                                         || t == HTML.Tag.IMPLIED
3945                                        )
3946                                    )
3947                            ) {
3948                     return false;
3949                 }
3950 
3951                 // Allow the insert if t matches the insert tag, or
3952                 // insertAfterImplied is true and the element is implied.
3953                 foundInsertTag(isBlockTag);
3954                 if (!insertInsertTag) {
3955                     return false;
3956                 }
3957             }
3958             return true;
3959         }
3960 
3961         private boolean isInsertTag(HTML.Tag tag) {
3962             return (insertTag == tag);
3963         }
3964 
3965         private void foundInsertTag(boolean isBlockTag) {
3966             foundInsertTag = true;
3967             if (!insertAfterImplied && (popDepth > 0 || pushDepth > 0)) {
3968                 try {
3969                     if (offset == 0 || !getText(offset - 1, 1).equals("\n")) {
3970                         // Need to insert a newline.
3971                         AttributeSet newAttrs = null;
3972                         boolean joinP = true;
3973 
3974                         if (offset != 0) {
3975                             // Determine if we can use JoinPrevious, we can't
3976                             // if the Element has some attributes that are
3977                             // not meant to be duplicated.
3978                             Element charElement = getCharacterElement
3979                                                     (offset - 1);
3980                             AttributeSet attrs = charElement.getAttributes();
3981 
3982                             if (attrs.isDefined(StyleConstants.
3983                                                 ComposedTextAttribute)) {
3984                                 joinP = false;
3985                             }
3986                             else {
3987                                 Object name = attrs.getAttribute
3988                                               (StyleConstants.NameAttribute);
3989                                 if (name instanceof HTML.Tag) {
3990                                     HTML.Tag tag = (HTML.Tag)name;
3991                                     if (tag == HTML.Tag.IMG ||
3992                                         tag == HTML.Tag.HR ||
3993                                         tag == HTML.Tag.COMMENT ||
3994                                         (tag instanceof HTML.UnknownTag)) {
3995                                         joinP = false;
3996                                     }
3997                                 }
3998                             }
3999                         }
4000                         if (!joinP) {
4001                             // If not joining with the previous element, be
4002                             // sure and set the name (otherwise it will be
4003                             // inherited).
4004                             newAttrs = new SimpleAttributeSet();
4005                             ((SimpleAttributeSet)newAttrs).addAttribute
4006                                               (StyleConstants.NameAttribute,
4007                                                HTML.Tag.CONTENT);
4008                         }
4009                         ElementSpec es = new ElementSpec(newAttrs,
4010                                      ElementSpec.ContentType, NEWLINE, 0,
4011                                      NEWLINE.length);
4012                         if (joinP) {
4013                             es.setDirection(ElementSpec.
4014                                             JoinPreviousDirection);
4015                         }
4016                         parseBuffer.addElement(es);
4017                     }
4018                 } catch (BadLocationException ble) {}
4019             }
4020             // pops
4021             for (int counter = 0; counter < popDepth; counter++) {
4022                 parseBuffer.addElement(new ElementSpec(null, ElementSpec.
4023                                                        EndTagType));
4024             }
4025             // pushes
4026             for (int counter = 0; counter < pushDepth; counter++) {
4027                 ElementSpec es = new ElementSpec(null, ElementSpec.
4028                                                  StartTagType);
4029                 es.setDirection(ElementSpec.JoinNextDirection);
4030                 parseBuffer.addElement(es);
4031             }
4032             insertTagDepthDelta = depthTo(Math.max(0, offset - 1)) -
4033                                   popDepth + pushDepth - inBlock;
4034             if (isBlockTag) {
4035                 // A start spec will be added (for this tag), so we account
4036                 // for it here.
4037                 insertTagDepthDelta++;
4038             }
4039             else {
4040                 // An implied paragraph close (end spec) is going to be added,
4041                 // so we account for it here.
4042                 insertTagDepthDelta--;
4043                 inParagraph = true;
4044                 lastWasNewline = false;
4045             }
4046         }
4047 
4048         /**
4049          * This is set to true when and end is invoked for {@literal <html>}.
4050          */
4051         private boolean receivedEndHTML;
4052         /** Number of times <code>flushBuffer</code> has been invoked. */
4053         private int flushCount;
4054         /** If true, behavior is similar to insertTag, but instead of
4055          * waiting for insertTag will wait for first Element without
4056          * an 'implied' attribute and begin inserting then. */
4057         private boolean insertAfterImplied;
4058         /** This is only used if insertAfterImplied is true. If false, only
4059          * inserting content, and there is a trailing newline it is removed. */
4060         private boolean wantsTrailingNewline;
4061         int threshold;
4062         int offset;
4063         boolean inParagraph = false;
4064         boolean impliedP = false;
4065         boolean inPre = false;
4066         boolean inTextArea = false;
4067         TextAreaDocument textAreaDocument = null;
4068         boolean inTitle = false;
4069         boolean lastWasNewline = true;
4070         boolean emptyAnchor;
4071         /** True if (!emptyDocument &amp;&amp; insertTag == null), this is used so
4072          * much it is cached. */
4073         boolean midInsert;
4074         /** True when the body has been encountered. */
4075         boolean inBody;
4076         /** If non null, gives parent Tag that insert is to happen at. */
4077         HTML.Tag insertTag;
4078         /** If true, the insertTag is inserted, otherwise elements after
4079          * the insertTag is found are inserted. */
4080         boolean insertInsertTag;
4081         /** Set to true when insertTag has been found. */
4082         boolean foundInsertTag;
4083         /** When foundInsertTag is set to true, this will be updated to
4084          * reflect the delta between the two structures. That is, it
4085          * will be the depth the inserts are happening at minus the
4086          * depth of the tags being passed in. A value of 0 (the common
4087          * case) indicates the structures match, a value greater than 0 indicates
4088          * the insert is happening at a deeper depth than the stream is
4089          * parsing, and a value less than 0 indicates the insert is happening earlier
4090          * in the tree that the parser thinks and that we will need to remove
4091          * EndTagType specs in the flushBuffer method.
4092          */
4093         int insertTagDepthDelta;
4094         /** How many parents to ascend before insert new elements. */
4095         int popDepth;
4096         /** How many parents to descend (relative to popDepth) before
4097          * inserting. */
4098         int pushDepth;
4099         /** Last Map that was encountered. */
4100         Map lastMap;
4101         /** Set to true when a style element is encountered. */
4102         boolean inStyle = false;
4103         /** Name of style to use. Obtained from Meta tag. */
4104         String defaultStyle;
4105         /** Vector describing styles that should be include. Will consist
4106          * of a bunch of HTML.Tags, which will either be:
4107          * <p>LINK: in which case it is followed by an AttributeSet
4108          * <p>STYLE: in which case the following element is a String
4109          * indicating the type (may be null), and the elements following
4110          * it until the next HTML.Tag are the rules as Strings.
4111          */
4112         Vector<Object> styles;
4113         /** True if inside the head tag. */
4114         boolean inHead = false;
4115         /** Set to true if the style language is text/css. Since this is
4116          * used alot, it is cached. */
4117         boolean isStyleCSS;
4118         /** True if inserting into an empty document. */
4119         boolean emptyDocument;
4120         /** Attributes from a style Attribute. */
4121         AttributeSet styleAttributes;
4122 
4123         /**
4124          * Current option, if in an option element (needed to
4125          * load the label.
4126          */
4127         Option option;
4128 
4129         /**
4130          * Buffer to keep building elements.
4131          */
4132         protected Vector<ElementSpec> parseBuffer = new Vector<ElementSpec>();
4133         /**
4134          * Current character attribute set.
4135          */
4136         protected MutableAttributeSet charAttr = new TaggedAttributeSet();
4137         Stack<AttributeSet> charAttrStack = new Stack<AttributeSet>();
4138         Hashtable<HTML.Tag, TagAction> tagMap;
4139         int inBlock = 0;
4140 
4141         /**
4142          * This attribute is sometimes used to refer to next tag
4143          * to be handled after p-implied when the latter is
4144          * the current tag which is being handled.
4145          */
4146         private HTML.Tag nextTagAfterPImplied = null;
4147     }
4148 
4149 
4150     /**
4151      * Used by StyleSheet to determine when to avoid removing HTML.Tags
4152      * matching StyleConstants.
4153      */
4154     static class TaggedAttributeSet extends SimpleAttributeSet {
4155         TaggedAttributeSet() {
4156             super();
4157         }
4158     }
4159 
4160 
4161     /**
4162      * An element that represents a chunk of text that has
4163      * a set of HTML character level attributes assigned to
4164      * it.
4165      */
4166     public class RunElement extends LeafElement {
4167 
4168         /**
4169          * Constructs an element that represents content within the
4170          * document (has no children).
4171          *
4172          * @param parent  the parent element
4173          * @param a       the element attributes
4174          * @param offs0   the start offset (must be at least 0)
4175          * @param offs1   the end offset (must be at least offs0)
4176          * @since 1.4
4177          */
4178         public RunElement(Element parent, AttributeSet a, int offs0, int offs1) {
4179             super(parent, a, offs0, offs1);
4180         }
4181 
4182         /**
4183          * Gets the name of the element.
4184          *
4185          * @return the name, null if none
4186          */
4187         public String getName() {
4188             Object o = getAttribute(StyleConstants.NameAttribute);
4189             if (o != null) {
4190                 return o.toString();
4191             }
4192             return super.getName();
4193         }
4194 
4195         /**
4196          * Gets the resolving parent.  HTML attributes are not inherited
4197          * at the model level so we override this to return null.
4198          *
4199          * @return null, there are none
4200          * @see AttributeSet#getResolveParent
4201          */
4202         public AttributeSet getResolveParent() {
4203             return null;
4204         }
4205     }
4206 
4207     /**
4208      * An element that represents a structural <em>block</em> of
4209      * HTML.
4210      */
4211     public class BlockElement extends BranchElement {
4212 
4213         /**
4214          * Constructs a composite element that initially contains
4215          * no children.
4216          *
4217          * @param parent  the parent element
4218          * @param a       the attributes for the element
4219          * @since 1.4
4220          */
4221         public BlockElement(Element parent, AttributeSet a) {
4222             super(parent, a);
4223         }
4224 
4225         /**
4226          * Gets the name of the element.
4227          *
4228          * @return the name, null if none
4229          */
4230         public String getName() {
4231             Object o = getAttribute(StyleConstants.NameAttribute);
4232             if (o != null) {
4233                 return o.toString();
4234             }
4235             return super.getName();
4236         }
4237 
4238         /**
4239          * Gets the resolving parent.  HTML attributes are not inherited
4240          * at the model level so we override this to return null.
4241          *
4242          * @return null, there are none
4243          * @see AttributeSet#getResolveParent
4244          */
4245         public AttributeSet getResolveParent() {
4246             return null;
4247         }
4248 
4249     }
4250 
4251 
4252     /**
4253      * Document that allows you to set the maximum length of the text.
4254      */
4255     private static class FixedLengthDocument extends PlainDocument {
4256         private int maxLength;
4257 
4258         public FixedLengthDocument(int maxLength) {
4259             this.maxLength = maxLength;
4260         }
4261 
4262         public void insertString(int offset, String str, AttributeSet a)
4263             throws BadLocationException {
4264             if (str != null && str.length() + getLength() <= maxLength) {
4265                 super.insertString(offset, str, a);
4266             }
4267         }
4268     }
4269 }