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