1. /*
  2. * @(#)HTMLWriter.java 1.36 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text.html;
  8. import javax.swing.text.*;
  9. import java.io.Writer;
  10. import java.util.Stack;
  11. import java.util.Enumeration;
  12. import java.util.Vector;
  13. import java.io.IOException;
  14. import java.util.StringTokenizer;
  15. import java.util.NoSuchElementException;
  16. import java.net.URL;
  17. /**
  18. * This is a writer for HTMLDocuments.
  19. *
  20. * @author Sunita Mani
  21. * @version 1.26, 02/02/00
  22. */
  23. public class HTMLWriter extends AbstractWriter {
  24. /*
  25. * Stores all elements for which end tags have to
  26. * be emitted.
  27. */
  28. private Stack blockElementStack = new Stack();
  29. private boolean inContent = false;
  30. private boolean inPre = false;
  31. /** When inPre is true, this will indicate the end offset of the pre
  32. * element. */
  33. private int preEndOffset;
  34. private boolean inTextArea = false;
  35. private boolean newlineOutputed = false;
  36. private boolean completeDoc;
  37. /*
  38. * Stores all embedded tags. Embedded tags are tags that are
  39. * stored as attributes in other tags. Generally they're
  40. * character level attributes. Examples include
  41. * <b>, <i>, <font>, and <a>.
  42. */
  43. private Vector tags = new Vector(10);
  44. /**
  45. * Values for the tags.
  46. */
  47. private Vector tagValues = new Vector(10);
  48. /**
  49. * Used when writing out content.
  50. */
  51. private Segment segment;
  52. /*
  53. * This is used in closeOutUnwantedEmbeddedTags.
  54. */
  55. private Vector tagsToRemove = new Vector(10);
  56. /**
  57. * Set to true after the head has been output.
  58. */
  59. private boolean wroteHead;
  60. /**
  61. * Set to true when entities (such as <) should be replaced.
  62. */
  63. private boolean replaceEntities;
  64. /**
  65. * Temporary buffer.
  66. */
  67. private char[] tempChars;
  68. /**
  69. * Creates a new HTMLWriter.
  70. *
  71. * @param w a Writer
  72. * @param doc an HTMLDocument
  73. *
  74. */
  75. public HTMLWriter(Writer w, HTMLDocument doc) {
  76. this(w, doc, 0, doc.getLength());
  77. }
  78. /**
  79. * Creates a new HTMLWriter.
  80. *
  81. * @param w a Writer
  82. * @param doc an HTMLDocument
  83. * @param pos the document location from which to fetch the content
  84. * @param len the amount to write out
  85. */
  86. public HTMLWriter(Writer w, HTMLDocument doc, int pos, int len) {
  87. super(w, doc, pos, len);
  88. completeDoc = (pos == 0 && len == doc.getLength());
  89. setLineLength(80);
  90. }
  91. /**
  92. * Iterates over the
  93. * Element tree and controls the writing out of
  94. * all the tags and its attributes.
  95. *
  96. * @exception IOException on any I/O error
  97. * @exception BadLocationException if pos represents an invalid
  98. * location within the document.
  99. *
  100. */
  101. public void write() throws IOException, BadLocationException {
  102. ElementIterator it = getElementIterator();
  103. Element current = null;
  104. Element next = null;
  105. wroteHead = false;
  106. setCurrentLineLength(0);
  107. replaceEntities = false;
  108. setCanWrapLines(false);
  109. if (segment == null) {
  110. segment = new Segment();
  111. }
  112. inPre = false;
  113. boolean forcedBody = false;
  114. while ((next = it.next()) != null) {
  115. if (!inRange(next)) {
  116. if (completeDoc && next.getAttributes().getAttribute(
  117. StyleConstants.NameAttribute) == HTML.Tag.BODY) {
  118. forcedBody = true;
  119. }
  120. else {
  121. continue;
  122. }
  123. }
  124. if (current != null) {
  125. /*
  126. if next is child of current increment indent
  127. */
  128. if (indentNeedsIncrementing(current, next)) {
  129. incrIndent();
  130. } else if (current.getParentElement() != next.getParentElement()) {
  131. /*
  132. next and current are not siblings
  133. so emit end tags for items on the stack until the
  134. item on top of the stack, is the parent of the
  135. next.
  136. */
  137. Element top = (Element)blockElementStack.peek();
  138. while (top != next.getParentElement()) {
  139. /*
  140. pop() will return top.
  141. */
  142. blockElementStack.pop();
  143. if (!synthesizedElement(top)) {
  144. AttributeSet attrs = top.getAttributes();
  145. if (!matchNameAttribute(attrs, HTML.Tag.PRE) &&
  146. !isFormElementWithContent(attrs)) {
  147. decrIndent();
  148. }
  149. endTag(top);
  150. }
  151. top = (Element)blockElementStack.peek();
  152. }
  153. } else if (current.getParentElement() == next.getParentElement()) {
  154. /*
  155. if next and current are siblings the indent level
  156. is correct. But, we need to make sure that if current is
  157. on the stack, we pop it off, and put out its end tag.
  158. */
  159. Element top = (Element)blockElementStack.peek();
  160. if (top == current) {
  161. blockElementStack.pop();
  162. endTag(top);
  163. }
  164. }
  165. }
  166. if (!next.isLeaf() || isFormElementWithContent(next.getAttributes())) {
  167. blockElementStack.push(next);
  168. startTag(next);
  169. } else {
  170. emptyTag(next);
  171. }
  172. current = next;
  173. }
  174. /* Emit all remaining end tags */
  175. /* A null parameter ensures that all embedded tags
  176. currently in the tags vector have their
  177. corresponding end tags written out.
  178. */
  179. closeOutUnwantedEmbeddedTags(null);
  180. if (forcedBody) {
  181. blockElementStack.pop();
  182. endTag(current);
  183. }
  184. while (!blockElementStack.empty()) {
  185. current = (Element)blockElementStack.pop();
  186. if (!synthesizedElement(current)) {
  187. AttributeSet attrs = current.getAttributes();
  188. if (!matchNameAttribute(attrs, HTML.Tag.PRE) &&
  189. !isFormElementWithContent(attrs)) {
  190. decrIndent();
  191. }
  192. endTag(current);
  193. }
  194. }
  195. if (completeDoc) {
  196. writeAdditionalComments();
  197. }
  198. segment.array = null;
  199. }
  200. /**
  201. * Writes out the attribute set. Ignores all
  202. * attributes with a key of type HTML.Tag,
  203. * attributes with a key of type StyleConstants,
  204. * and attributes with a key of type
  205. * HTML.Attribute.ENDTAG.
  206. *
  207. * @param attr an AttributeSet
  208. * @exception IOException on any I/O error
  209. *
  210. */
  211. protected void writeAttributes(AttributeSet attr) throws IOException {
  212. // translate css attributes to html
  213. convAttr.removeAttributes(convAttr);
  214. convertToHTML32(attr, convAttr);
  215. Enumeration names = convAttr.getAttributeNames();
  216. while (names.hasMoreElements()) {
  217. Object name = names.nextElement();
  218. if (name instanceof HTML.Tag ||
  219. name instanceof StyleConstants ||
  220. name == HTML.Attribute.ENDTAG) {
  221. continue;
  222. }
  223. write(" " + name + "=\"" + convAttr.getAttribute(name) + "\"");
  224. }
  225. }
  226. /**
  227. * Writes out all empty elements (all tags that have no
  228. * corresponding end tag).
  229. *
  230. * @param elem an Element
  231. * @exception IOException on any I/O error
  232. * @exception BadLocationException if pos represents an invalid
  233. * location within the document.
  234. */
  235. protected void emptyTag(Element elem) throws BadLocationException, IOException {
  236. if (!inContent && !inPre) {
  237. indent();
  238. }
  239. AttributeSet attr = elem.getAttributes();
  240. closeOutUnwantedEmbeddedTags(attr);
  241. writeEmbeddedTags(attr);
  242. if (matchNameAttribute(attr, HTML.Tag.CONTENT)) {
  243. inContent = true;
  244. text(elem);
  245. } else if (matchNameAttribute(attr, HTML.Tag.COMMENT)) {
  246. comment(elem);
  247. } else {
  248. boolean isBlock = isBlockTag(elem.getAttributes());
  249. if (inContent && isBlock ) {
  250. writeLineSeparator();
  251. indent();
  252. }
  253. Object nameTag = (attr != null) ? attr.getAttribute
  254. (StyleConstants.NameAttribute) : null;
  255. Object endTag = (attr != null) ? attr.getAttribute
  256. (HTML.Attribute.ENDTAG) : null;
  257. boolean outputEndTag = false;
  258. // If an instance of an UNKNOWN Tag, or an instance of a
  259. // tag that is only visible during editing
  260. //
  261. if (nameTag != null && endTag != null &&
  262. (endTag instanceof String) &&
  263. ((String)endTag).equals("true")) {
  264. outputEndTag = true;
  265. }
  266. if (completeDoc && matchNameAttribute(attr, HTML.Tag.HEAD)) {
  267. if (outputEndTag) {
  268. // Write out any styles.
  269. writeStyles(((HTMLDocument)getDocument()).getStyleSheet());
  270. }
  271. wroteHead = true;
  272. }
  273. write('<');
  274. if (outputEndTag) {
  275. write('/');
  276. }
  277. write(elem.getName());
  278. writeAttributes(attr);
  279. write('>');
  280. if (matchNameAttribute(attr, HTML.Tag.TITLE) && !outputEndTag) {
  281. Document doc = elem.getDocument();
  282. String title = (String)doc.getProperty(Document.TitleProperty);
  283. write(title);
  284. } else if (!inContent || isBlock) {
  285. writeLineSeparator();
  286. if (isBlock && inContent) {
  287. indent();
  288. }
  289. }
  290. }
  291. }
  292. /**
  293. * Determines if the HTML.Tag associated with the
  294. * element is a block tag.
  295. *
  296. * @param attr an AttributeSet
  297. * @return true if tag is block tag, false otherwise.
  298. */
  299. protected boolean isBlockTag(AttributeSet attr) {
  300. Object o = attr.getAttribute(StyleConstants.NameAttribute);
  301. if (o instanceof HTML.Tag) {
  302. HTML.Tag name = (HTML.Tag) o;
  303. return name.isBlock();
  304. }
  305. return false;
  306. }
  307. /**
  308. * Writes out a start tag for the element.
  309. * Ignores all synthesized elements.
  310. *
  311. * @param elem an Element
  312. * @exception IOException on any I/O error
  313. */
  314. protected void startTag(Element elem) throws IOException, BadLocationException {
  315. if (synthesizedElement(elem)) {
  316. return;
  317. }
  318. // Determine the name, as an HTML.Tag.
  319. AttributeSet attr = elem.getAttributes();
  320. Object nameAttribute = attr.getAttribute(StyleConstants.NameAttribute);
  321. HTML.Tag name;
  322. if (nameAttribute instanceof HTML.Tag) {
  323. name = (HTML.Tag)nameAttribute;
  324. }
  325. else {
  326. name = null;
  327. }
  328. if (name == HTML.Tag.PRE) {
  329. inPre = true;
  330. preEndOffset = elem.getEndOffset();
  331. }
  332. // write out end tags for item on stack
  333. closeOutUnwantedEmbeddedTags(attr);
  334. if (inContent) {
  335. writeLineSeparator();
  336. inContent = false;
  337. newlineOutputed = false;
  338. }
  339. if (completeDoc && name == HTML.Tag.BODY && !wroteHead) {
  340. // If the head has not been output, output it and the styles.
  341. wroteHead = true;
  342. indent();
  343. write("<head>");
  344. writeLineSeparator();
  345. incrIndent();
  346. writeStyles(((HTMLDocument)getDocument()).getStyleSheet());
  347. decrIndent();
  348. writeLineSeparator();
  349. indent();
  350. write("</head>");
  351. writeLineSeparator();
  352. }
  353. indent();
  354. write('<');
  355. write(elem.getName());
  356. writeAttributes(attr);
  357. write('>');
  358. if (name != HTML.Tag.PRE) {
  359. writeLineSeparator();
  360. }
  361. if (name == HTML.Tag.TEXTAREA) {
  362. textAreaContent(elem.getAttributes());
  363. } else if (name == HTML.Tag.SELECT) {
  364. selectContent(elem.getAttributes());
  365. } else if (completeDoc && name == HTML.Tag.BODY) {
  366. // Write out the maps, which is not stored as Elements in
  367. // the Document.
  368. writeMaps(((HTMLDocument)getDocument()).getMaps());
  369. }
  370. else if (name == HTML.Tag.HEAD) {
  371. wroteHead = true;
  372. incrIndent();
  373. writeStyles(((HTMLDocument)getDocument()).getStyleSheet());
  374. decrIndent();
  375. }
  376. HTMLDocument document = null;
  377. if (name == HTML.Tag.BODY
  378. && (document = (HTMLDocument)getDocument()).hasBaseTag()) {
  379. incrIndent();
  380. indent();
  381. write("<base href = \"" + document.getBase() + "\">");
  382. writeLineSeparator();
  383. decrIndent();
  384. }
  385. }
  386. /**
  387. * Writes out text that is contained in a TEXTAREA form
  388. * element.
  389. *
  390. * @param attr an AttributeSet
  391. * @exception IOException on any I/O error
  392. * @exception BadLocationException if pos represents an invalid
  393. * location within the document.
  394. */
  395. protected void textAreaContent(AttributeSet attr) throws BadLocationException, IOException {
  396. Document doc = (Document)attr.getAttribute(StyleConstants.ModelAttribute);
  397. if (doc != null && doc.getLength() > 0) {
  398. if (segment == null) {
  399. segment = new Segment();
  400. }
  401. doc.getText(0, doc.getLength(), segment);
  402. if (segment.count > 0) {
  403. inTextArea = true;
  404. incrIndent();
  405. indent();
  406. setCanWrapLines(true);
  407. replaceEntities = true;
  408. write(segment.array, segment.offset, segment.count);
  409. replaceEntities = false;
  410. setCanWrapLines(false);
  411. writeLineSeparator();
  412. inTextArea = false;
  413. decrIndent();
  414. }
  415. }
  416. }
  417. /**
  418. * Writes out text. If a range is specified when the constructor
  419. * is invoked, then only the appropriate range of text is written
  420. * out.
  421. *
  422. * @param elem an Element
  423. * @exception IOException on any I/O error
  424. * @exception BadLocationException if pos represents an invalid
  425. * location within the document.
  426. */
  427. protected void text(Element elem) throws BadLocationException, IOException {
  428. int start = Math.max(getStartOffset(), elem.getStartOffset());
  429. int end = Math.min(getEndOffset(), elem.getEndOffset());
  430. if (start < end) {
  431. if (segment == null) {
  432. segment = new Segment();
  433. }
  434. getDocument().getText(start, end - start, segment);
  435. newlineOutputed = false;
  436. if (segment.count > 0) {
  437. if (segment.array[segment.offset + segment.count - 1] == '\n'){
  438. newlineOutputed = true;
  439. }
  440. if (inPre && end == preEndOffset) {
  441. if (segment.count > 1) {
  442. segment.count--;
  443. }
  444. else {
  445. return;
  446. }
  447. }
  448. replaceEntities = true;
  449. setCanWrapLines(!inPre);
  450. write(segment.array, segment.offset, segment.count);
  451. setCanWrapLines(false);
  452. replaceEntities = false;
  453. }
  454. }
  455. }
  456. /**
  457. * Writes out the content of the SELECT form element.
  458. *
  459. * @param attr the AttributeSet associated with the form element
  460. * @exception IOException on any I/O error
  461. */
  462. protected void selectContent(AttributeSet attr) throws IOException {
  463. Object model = attr.getAttribute(StyleConstants.ModelAttribute);
  464. incrIndent();
  465. if (model instanceof OptionListModel) {
  466. OptionListModel listModel = (OptionListModel)model;
  467. int size = listModel.getSize();
  468. for (int i = 0; i < size; i++) {
  469. Option option = (Option)listModel.getElementAt(i);
  470. writeOption(option);
  471. }
  472. } else if (model instanceof OptionComboBoxModel) {
  473. OptionComboBoxModel comboBoxModel = (OptionComboBoxModel)model;
  474. int size = comboBoxModel.getSize();
  475. for (int i = 0; i < size; i++) {
  476. Option option = (Option)comboBoxModel.getElementAt(i);
  477. writeOption(option);
  478. }
  479. }
  480. decrIndent();
  481. }
  482. /**
  483. * Writes out the content of the Option form element.
  484. * @param option an Option
  485. * @exception IOException on any I/O error
  486. *
  487. */
  488. protected void writeOption(Option option) throws IOException {
  489. indent();
  490. write('<');
  491. write("option");
  492. // PENDING: should this be changed to check for null first?
  493. Object value = option.getAttributes().getAttribute
  494. (HTML.Attribute.VALUE);
  495. if (value != null) {
  496. write(" value="+ value);
  497. }
  498. if (option.isSelected()) {
  499. write(" selected");
  500. }
  501. write('>');
  502. if (option.getLabel() != null) {
  503. write(option.getLabel());
  504. }
  505. writeLineSeparator();
  506. }
  507. /**
  508. * Writes out an end tag for the element.
  509. *
  510. * @param elem an Element
  511. * @exception IOException on any I/O error
  512. */
  513. protected void endTag(Element elem) throws IOException {
  514. if (synthesizedElement(elem)) {
  515. return;
  516. }
  517. // write out end tags for item on stack
  518. closeOutUnwantedEmbeddedTags(elem.getAttributes());
  519. if (inContent) {
  520. if (!newlineOutputed && !inPre) {
  521. writeLineSeparator();
  522. }
  523. newlineOutputed = false;
  524. inContent = false;
  525. }
  526. if (!inPre) {
  527. indent();
  528. }
  529. if (matchNameAttribute(elem.getAttributes(), HTML.Tag.PRE)) {
  530. inPre = false;
  531. }
  532. write('<');
  533. write('/');
  534. write(elem.getName());
  535. write('>');
  536. writeLineSeparator();
  537. }
  538. /**
  539. * Writes out comments.
  540. *
  541. * @param elem an Element
  542. * @exception IOException on any I/O error
  543. * @exception BadLocationException if pos represents an invalid
  544. * location within the document.
  545. */
  546. protected void comment(Element elem) throws BadLocationException, IOException {
  547. AttributeSet as = elem.getAttributes();
  548. if (matchNameAttribute(as, HTML.Tag.COMMENT)) {
  549. Object comment = as.getAttribute(HTML.Attribute.COMMENT);
  550. if (comment instanceof String) {
  551. writeComment((String)comment);
  552. }
  553. else {
  554. writeComment(null);
  555. }
  556. }
  557. }
  558. /**
  559. * Writes out comment string.
  560. *
  561. * @param string the comment
  562. * @exception IOException on any I/O error
  563. * @exception BadLocationException if pos represents an invalid
  564. * location within the document.
  565. */
  566. void writeComment(String string) throws IOException {
  567. write("<!--");
  568. if (string != null) {
  569. write(string);
  570. }
  571. write("-->");
  572. writeLineSeparator();
  573. }
  574. /**
  575. * Writes out any additional comments (comments outside of the body)
  576. * stored under the property HTMLDocument.AdditionalComments.
  577. */
  578. void writeAdditionalComments() throws IOException {
  579. Object comments = getDocument().getProperty
  580. (HTMLDocument.AdditionalComments);
  581. if (comments instanceof Vector) {
  582. Vector v = (Vector)comments;
  583. for (int counter = 0, maxCounter = v.size(); counter < maxCounter;
  584. counter++) {
  585. writeComment(v.elementAt(counter).toString());
  586. }
  587. }
  588. }
  589. /**
  590. * Returns true if the element is a
  591. * synthesized element. Currently we are only testing
  592. * for the p-implied tag.
  593. */
  594. protected boolean synthesizedElement(Element elem) {
  595. if (matchNameAttribute(elem.getAttributes(), HTML.Tag.IMPLIED)) {
  596. return true;
  597. }
  598. return false;
  599. }
  600. /**
  601. * Returns true if the StyleConstants.NameAttribute is
  602. * equal to the tag that is passed in as a parameter.
  603. */
  604. protected boolean matchNameAttribute(AttributeSet attr, HTML.Tag tag) {
  605. Object o = attr.getAttribute(StyleConstants.NameAttribute);
  606. if (o instanceof HTML.Tag) {
  607. HTML.Tag name = (HTML.Tag) o;
  608. if (name == tag) {
  609. return true;
  610. }
  611. }
  612. return false;
  613. }
  614. /**
  615. * Searches for embedded tags in the AttributeSet
  616. * and writes them out. It also stores these tags in a vector
  617. * so that when appropriate the corresponding end tags can be
  618. * written out.
  619. *
  620. * @exception IOException on any I/O error
  621. */
  622. protected void writeEmbeddedTags(AttributeSet attr) throws IOException {
  623. // translate css attributes to html
  624. attr = convertToHTML(attr, oConvAttr);
  625. Enumeration names = attr.getAttributeNames();
  626. while (names.hasMoreElements()) {
  627. Object name = names.nextElement();
  628. if (name instanceof HTML.Tag) {
  629. HTML.Tag tag = (HTML.Tag)name;
  630. if (tag == HTML.Tag.FORM || tags.contains(tag)) {
  631. continue;
  632. }
  633. write('<');
  634. write(tag.toString());
  635. Object o = attr.getAttribute(tag);
  636. if (o != null && o instanceof AttributeSet) {
  637. writeAttributes((AttributeSet)o);
  638. }
  639. write('>');
  640. tags.addElement(tag);
  641. tagValues.addElement(o);
  642. }
  643. }
  644. }
  645. /**
  646. * Searches the attribute set for a tag, both of which
  647. * are passed in as a parameter. Returns true if no match is found
  648. * and false otherwise.
  649. */
  650. private boolean noMatchForTagInAttributes(AttributeSet attr, HTML.Tag t,
  651. Object tagValue) {
  652. if (attr != null && attr.isDefined(t)) {
  653. Object newValue = attr.getAttribute(t);
  654. if ((tagValue == null) ? (newValue == null) :
  655. (newValue != null && tagValue.equals(newValue))) {
  656. return false;
  657. }
  658. }
  659. return true;
  660. }
  661. /**
  662. * Searches the attribute set and for each tag
  663. * that is stored in the tag vector. If the tag isnt found,
  664. * then the tag is removed from the vector and a corresponding
  665. * end tag is written out.
  666. *
  667. * @exception IOException on any I/O error
  668. */
  669. protected void closeOutUnwantedEmbeddedTags(AttributeSet attr) throws IOException {
  670. tagsToRemove.removeAllElements();
  671. // translate css attributes to html
  672. attr = convertToHTML(attr, null);
  673. HTML.Tag t;
  674. Object tValue;
  675. int firstIndex = -1;
  676. int size = tags.size();
  677. // First, find all the tags that need to be removed.
  678. for (int i = size - 1; i >= 0; i--) {
  679. t = (HTML.Tag)tags.elementAt(i);
  680. tValue = tagValues.elementAt(i);
  681. if ((attr == null) || noMatchForTagInAttributes(attr, t, tValue)) {
  682. firstIndex = i;
  683. tagsToRemove.addElement(t);
  684. }
  685. }
  686. if (firstIndex != -1) {
  687. // Then close them out.
  688. boolean removeAll = ((size - firstIndex) == tagsToRemove.size());
  689. for (int i = size - 1; i >= firstIndex; i--) {
  690. t = (HTML.Tag)tags.elementAt(i);
  691. if (removeAll || tagsToRemove.contains(t)) {
  692. tags.removeElementAt(i);
  693. tagValues.removeElementAt(i);
  694. }
  695. write('<');
  696. write('/');
  697. write(t.toString());
  698. write('>');
  699. }
  700. // Have to output any tags after firstIndex that still remaing,
  701. // as we closed them out, but they should remain open.
  702. size = tags.size();
  703. for (int i = firstIndex; i < size; i++) {
  704. t = (HTML.Tag)tags.elementAt(i);
  705. write('<');
  706. write(t.toString());
  707. Object o = tagValues.elementAt(i);
  708. if (o != null && o instanceof AttributeSet) {
  709. writeAttributes((AttributeSet)o);
  710. }
  711. write('>');
  712. }
  713. }
  714. }
  715. /**
  716. * Determines if the element associated with the attributeset
  717. * is a TEXTAREA or SELECT. If true, returns true else
  718. * false
  719. */
  720. private boolean isFormElementWithContent(AttributeSet attr) {
  721. if (matchNameAttribute(attr, HTML.Tag.TEXTAREA) ||
  722. matchNameAttribute(attr, HTML.Tag.SELECT)) {
  723. return true;
  724. }
  725. return false;
  726. }
  727. /**
  728. * Determines whether a the indentation needs to be
  729. * incremented. Basically, if next is a child of current, and
  730. * next is NOT a synthesized element, the indent level will be
  731. * incremented. If there is a parent-child relationship and "next"
  732. * is a synthesized element, then its children must be indented.
  733. * This state is maintained by the indentNext boolean.
  734. *
  735. * @return boolean that's true if indent level
  736. * needs incrementing.
  737. */
  738. private boolean indentNext = false;
  739. private boolean indentNeedsIncrementing(Element current, Element next) {
  740. if ((next.getParentElement() == current) && !inPre) {
  741. if (indentNext) {
  742. indentNext = false;
  743. return true;
  744. } else if (synthesizedElement(next)) {
  745. indentNext = true;
  746. } else if (!synthesizedElement(current)){
  747. return true;
  748. }
  749. }
  750. return false;
  751. }
  752. /**
  753. * Outputs the maps as elements. Maps are not stored as elements in
  754. * the document, and as such this is used to output them.
  755. */
  756. void writeMaps(Enumeration maps) throws IOException {
  757. if (maps != null) {
  758. while(maps.hasMoreElements()) {
  759. Map map = (Map)maps.nextElement();
  760. String name = map.getName();
  761. incrIndent();
  762. indent();
  763. write("<map");
  764. if (name != null) {
  765. write(" name=\"");
  766. write(name);
  767. write("\">");
  768. }
  769. else {
  770. write('>');
  771. }
  772. writeLineSeparator();
  773. incrIndent();
  774. // Output the areas
  775. AttributeSet[] areas = map.getAreas();
  776. if (areas != null) {
  777. for (int counter = 0, maxCounter = areas.length;
  778. counter < maxCounter; counter++) {
  779. indent();
  780. write("<area");
  781. writeAttributes(areas[counter]);
  782. write("></area>");
  783. writeLineSeparator();
  784. }
  785. }
  786. decrIndent();
  787. indent();
  788. write("</map>");
  789. writeLineSeparator();
  790. decrIndent();
  791. }
  792. }
  793. }
  794. /**
  795. * Outputs the styles as a single element. Styles are not stored as
  796. * elements, but part of the document. For the time being styles are
  797. * written out as a comment, inside a style tag.
  798. */
  799. void writeStyles(StyleSheet sheet) throws IOException {
  800. if (sheet != null) {
  801. Enumeration styles = sheet.getStyleNames();
  802. if (styles != null) {
  803. boolean outputStyle = false;
  804. while (styles.hasMoreElements()) {
  805. String name = (String)styles.nextElement();
  806. // Don't write out the default style.
  807. if (!StyleContext.DEFAULT_STYLE.equals(name) &&
  808. writeStyle(name, sheet.getStyle(name), outputStyle)) {
  809. outputStyle = true;
  810. }
  811. }
  812. if (outputStyle) {
  813. writeStyleEndTag();
  814. }
  815. }
  816. }
  817. }
  818. /**
  819. * Outputs the named style. <code>outputStyle</code> indicates
  820. * whether or not a style has been output yet. This will return
  821. * true if a style is written.
  822. */
  823. boolean writeStyle(String name, Style style, boolean outputStyle)
  824. throws IOException{
  825. boolean didOutputStyle = false;
  826. Enumeration attributes = style.getAttributeNames();
  827. if (attributes != null) {
  828. while (attributes.hasMoreElements()) {
  829. Object attribute = attributes.nextElement();
  830. if (attribute instanceof CSS.Attribute) {
  831. String value = style.getAttribute(attribute).toString();
  832. if (value != null) {
  833. if (!outputStyle) {
  834. writeStyleStartTag();
  835. outputStyle = true;
  836. }
  837. if (!didOutputStyle) {
  838. didOutputStyle = true;
  839. indent();
  840. write(name);
  841. write(" {");
  842. }
  843. else {
  844. write(";");
  845. }
  846. write(' ');
  847. write(attribute.toString());
  848. write(": ");
  849. write(value);
  850. }
  851. }
  852. }
  853. }
  854. if (didOutputStyle) {
  855. write(" }");
  856. writeLineSeparator();
  857. }
  858. return didOutputStyle;
  859. }
  860. void writeStyleStartTag() throws IOException {
  861. indent();
  862. write("<style type=\"text/css\">");
  863. incrIndent();
  864. writeLineSeparator();
  865. indent();
  866. write("<!--");
  867. incrIndent();
  868. writeLineSeparator();
  869. }
  870. void writeStyleEndTag() throws IOException {
  871. decrIndent();
  872. indent();
  873. write("-->");
  874. writeLineSeparator();
  875. decrIndent();
  876. indent();
  877. write("</style>");
  878. writeLineSeparator();
  879. indent();
  880. }
  881. // --- conversion support ---------------------------
  882. /**
  883. * Convert the give set of attributes to be html for
  884. * the purpose of writing them out. Any keys that
  885. * have been converted will not appear in the resultant
  886. * set. Any keys not converted will appear in the
  887. * resultant set the same as the received set.<p>
  888. * This will put the converted values into <code>to</code>, unless
  889. * it is null in which case a temporary AttributeSet will be returned.
  890. */
  891. AttributeSet convertToHTML(AttributeSet from, MutableAttributeSet to) {
  892. if (to == null) {
  893. to = convAttr;
  894. }
  895. to.removeAttributes(to);
  896. if (writeCSS) {
  897. convertToHTML40(from, to);
  898. } else {
  899. convertToHTML32(from, to);
  900. }
  901. return to;
  902. }
  903. /**
  904. * If true, the writer will emit CSS attributes in preference
  905. * to HTML tags/attributes (i.e. It will emit an HTML 4.0
  906. * style).
  907. */
  908. private boolean writeCSS = false;
  909. /**
  910. * Buffer for the purpose of attribute conversion
  911. */
  912. private MutableAttributeSet convAttr = new SimpleAttributeSet();
  913. /**
  914. * Buffer for the purpose of attribute conversion. This can be
  915. * used if convAttr is being used.
  916. */
  917. private MutableAttributeSet oConvAttr = new SimpleAttributeSet();
  918. /**
  919. * Create an older style of HTML attributes. This will
  920. * convert character level attributes that have a StyleConstants
  921. * mapping over to an HTML tag/attribute. Other CSS attributes
  922. * will be placed in an HTML style attribute.
  923. */
  924. private static void convertToHTML32(AttributeSet from, MutableAttributeSet to) {
  925. if (from == null) {
  926. return;
  927. }
  928. Enumeration keys = from.getAttributeNames();
  929. String value = "";
  930. while (keys.hasMoreElements()) {
  931. Object key = keys.nextElement();
  932. if (key instanceof CSS.Attribute) {
  933. if ((key == CSS.Attribute.FONT_FAMILY) ||
  934. (key == CSS.Attribute.FONT_SIZE) ||
  935. (key == CSS.Attribute.COLOR)) {
  936. createFontAttribute((CSS.Attribute)key, from, to);
  937. } else if (key == CSS.Attribute.FONT_WEIGHT) {
  938. // add a bold tag is weight is bold
  939. CSS.FontWeight weightValue = (CSS.FontWeight)
  940. from.getAttribute(CSS.Attribute.FONT_WEIGHT);
  941. if ((weightValue != null) && (weightValue.getValue() > 400)) {
  942. addAttribute(to, HTML.Tag.B, SimpleAttributeSet.EMPTY);
  943. }
  944. } else if (key == CSS.Attribute.FONT_STYLE) {
  945. String s = from.getAttribute(key).toString();
  946. if (s.indexOf("italic") >= 0) {
  947. addAttribute(to, HTML.Tag.I, SimpleAttributeSet.EMPTY);
  948. }
  949. } else if (key == CSS.Attribute.TEXT_DECORATION) {
  950. String decor = from.getAttribute(key).toString();
  951. if (decor.indexOf("underline") >= 0) {
  952. addAttribute(to, HTML.Tag.U, SimpleAttributeSet.EMPTY);
  953. }
  954. if (decor.indexOf("line-through") >= 0) {
  955. addAttribute(to, HTML.Tag.STRIKE, SimpleAttributeSet.EMPTY);
  956. }
  957. } else if (key == CSS.Attribute.VERTICAL_ALIGN) {
  958. String vAlign = from.getAttribute(key).toString();
  959. if (vAlign.indexOf("sup") >= 0) {
  960. addAttribute(to, HTML.Tag.SUP, SimpleAttributeSet.EMPTY);
  961. }
  962. if (vAlign.indexOf("sub") >= 0) {
  963. addAttribute(to, HTML.Tag.SUB, SimpleAttributeSet.EMPTY);
  964. }
  965. } else if (key == CSS.Attribute.TEXT_ALIGN) {
  966. addAttribute(to, HTML.Attribute.ALIGN,
  967. from.getAttribute(key).toString());
  968. } else {
  969. // default is to store in a HTML style attribute
  970. if (value.length() > 0) {
  971. value = value + "; ";
  972. }
  973. value = value + key + ": " + from.getAttribute(key);
  974. }
  975. } else {
  976. Object attr = from.getAttribute(key);
  977. if (attr instanceof AttributeSet) {
  978. attr = ((AttributeSet)attr).copyAttributes();
  979. }
  980. addAttribute(to, key, attr);
  981. }
  982. }
  983. if (value.length() > 0) {
  984. to.addAttribute(HTML.Attribute.STYLE, value);
  985. }
  986. }
  987. /**
  988. * Add an attribute only if it doesn't exist so that we don't
  989. * loose information replacing it with SimpleAttributeSet.EMPTY
  990. */
  991. private static void addAttribute(MutableAttributeSet to, Object key, Object value) {
  992. Object attr = to.getAttribute(key);
  993. if (attr == null || attr == SimpleAttributeSet.EMPTY) {
  994. to.addAttribute(key, value);
  995. } else {
  996. if (attr instanceof MutableAttributeSet &&
  997. value instanceof AttributeSet) {
  998. ((MutableAttributeSet)attr).addAttributes((AttributeSet)value);
  999. }
  1000. }
  1001. }
  1002. /**
  1003. * Create/update an HTML <font> tag attribute. The
  1004. * value of the attribute should be a MutableAttributeSet so
  1005. * that the attributes can be updated as they are discovered.
  1006. */
  1007. private static void createFontAttribute(CSS.Attribute a, AttributeSet from,
  1008. MutableAttributeSet to) {
  1009. MutableAttributeSet fontAttr = (MutableAttributeSet)
  1010. to.getAttribute(HTML.Tag.FONT);
  1011. if (fontAttr == null) {
  1012. fontAttr = new SimpleAttributeSet();
  1013. to.addAttribute(HTML.Tag.FONT, fontAttr);
  1014. }
  1015. // edit the parameters to the font tag
  1016. String htmlValue = from.getAttribute(a).toString();
  1017. if (a == CSS.Attribute.FONT_FAMILY) {
  1018. fontAttr.addAttribute(HTML.Attribute.FACE, htmlValue);
  1019. } else if (a == CSS.Attribute.FONT_SIZE) {
  1020. fontAttr.addAttribute(HTML.Attribute.SIZE, htmlValue);
  1021. } else if (a == CSS.Attribute.COLOR) {
  1022. fontAttr.addAttribute(HTML.Attribute.COLOR, htmlValue);
  1023. }
  1024. }
  1025. /**
  1026. * Copies the given AttributeSet to a new set, converting
  1027. * any CSS attributes found to arguments of an HTML style
  1028. * attribute.
  1029. */
  1030. private static void convertToHTML40(AttributeSet from, MutableAttributeSet to) {
  1031. Enumeration keys = from.getAttributeNames();
  1032. String value = "";
  1033. while (keys.hasMoreElements()) {
  1034. Object key = keys.nextElement();
  1035. if (key instanceof CSS.Attribute) {
  1036. value = value + " " + key + "=" + from.getAttribute(key) + ";";
  1037. } else {
  1038. to.addAttribute(key, from.getAttribute(key));
  1039. }
  1040. }
  1041. if (value.length() > 0) {
  1042. to.addAttribute(HTML.Attribute.STYLE, value);
  1043. }
  1044. }
  1045. //
  1046. // Overrides the writing methods to only break a string when
  1047. // canBreakString is true.
  1048. // In a future release it is likely AbstractWriter will get this
  1049. // functionality.
  1050. //
  1051. /**
  1052. * Writes the line separator. This is overriden to make sure we don't
  1053. * replace the newline content in case it is outside normal ascii.
  1054. */
  1055. protected void writeLineSeparator() throws IOException {
  1056. boolean oldReplace = replaceEntities;
  1057. replaceEntities = false;
  1058. super.writeLineSeparator();
  1059. replaceEntities = oldReplace;
  1060. }
  1061. /**
  1062. * This method is overriden to map any character entities, such as
  1063. * < to &lt;. <code>super.output</code> will be invoked to
  1064. * write the content.
  1065. */
  1066. protected void output(char[] chars, int start, int length)
  1067. throws IOException {
  1068. if (!replaceEntities) {
  1069. super.output(chars, start, length);
  1070. return;
  1071. }
  1072. int last = start;
  1073. length += start;
  1074. for (int counter = start; counter < length; counter++) {
  1075. // This will change, we need better support character level
  1076. // entities.
  1077. switch(chars[counter]) {
  1078. // Character level entities.
  1079. case '<':
  1080. if (counter > last) {
  1081. super.output(chars, last, counter - last);
  1082. }
  1083. last = counter + 1;
  1084. output("<");
  1085. break;
  1086. case '>':
  1087. if (counter > last) {
  1088. super.output(chars, last, counter - last);
  1089. }
  1090. last = counter + 1;
  1091. output(">");
  1092. break;
  1093. case '&':
  1094. if (counter > last) {
  1095. super.output(chars, last, counter - last);
  1096. }
  1097. last = counter + 1;
  1098. output("&");
  1099. break;
  1100. case '"':
  1101. if (counter > last) {
  1102. super.output(chars, last, counter - last);
  1103. }
  1104. last = counter + 1;
  1105. output(""");
  1106. break;
  1107. // Special characters
  1108. case '\n':
  1109. case '\t':
  1110. case '\r':
  1111. break;
  1112. default:
  1113. if (chars[counter] < ' ' || chars[counter] > 127) {
  1114. if (counter > last) {
  1115. super.output(chars, last, counter - last);
  1116. }
  1117. last = counter + 1;
  1118. // If the character is outside of ascii, write the
  1119. // numeric value.
  1120. output("&#");
  1121. output(String.valueOf((int)chars[counter]));
  1122. output(";");
  1123. }
  1124. break;
  1125. }
  1126. }
  1127. if (last < length) {
  1128. super.output(chars, last, length - last);
  1129. }
  1130. }
  1131. /**
  1132. * This directly invokes super's <code>output</code> after converting
  1133. * <code>string</code> to a char[].
  1134. */
  1135. private void output(String string) throws IOException {
  1136. int length = string.length();
  1137. if (tempChars == null || tempChars.length < length) {
  1138. tempChars = new char[length];
  1139. }
  1140. string.getChars(0, length, tempChars, 0);
  1141. super.output(tempChars, 0, length);
  1142. }
  1143. }