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