1. /*
  2. * @(#)RTFGenerator.java 1.12 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text.rtf;
  8. import java.lang.*;
  9. import java.util.*;
  10. import java.awt.Color;
  11. import java.awt.Font;
  12. import java.io.OutputStream;
  13. import java.io.IOException;
  14. import javax.swing.text.*;
  15. /**
  16. * Generates an RTF output stream (java.io.OutputStream) from rich text
  17. * (handed off through a series of LTTextAcceptor calls). Can be used to
  18. * generate RTF from any object which knows how to write to a text acceptor
  19. * (e.g., LTAttributedText and LTRTFFilter).
  20. *
  21. * <p>Note that this is a lossy conversion since RTF's model of
  22. * text does not exactly correspond with LightText's.
  23. *
  24. * @see LTAttributedText
  25. * @see LTRTFFilter
  26. * @see LTTextAcceptor
  27. * @see java.io.OutputStream
  28. */
  29. class RTFGenerator extends Object
  30. {
  31. /* These dictionaries map Colors, font names, or Style objects
  32. to Integers */
  33. Dictionary colorTable;
  34. int colorCount;
  35. Dictionary fontTable;
  36. int fontCount;
  37. Dictionary styleTable;
  38. int styleCount;
  39. /* where all the text is going */
  40. OutputStream outputStream;
  41. boolean afterKeyword;
  42. MutableAttributeSet outputAttributes;
  43. /* the value of the last \\ucN keyword emitted */
  44. int unicodeCount;
  45. /* for efficiency's sake (ha) */
  46. private Segment workingSegment;
  47. int[] outputConversion;
  48. /** The default color, used for text without an explicit color
  49. * attribute. */
  50. static public final Color defaultRTFColor = Color.black;
  51. static public final float defaultFontSize = 12f;
  52. static public final String defaultFontFamily = "Helvetica";
  53. /* constants so we can avoid allocating objects in inner loops */
  54. /* these should all be final, but javac seems to be a bit buggy */
  55. static protected Integer One, Zero;
  56. static protected Boolean False;
  57. static protected Float ZeroPointZero;
  58. static private Object MagicToken;
  59. /* An array of character-keyword pairs. This could be done
  60. as a dictionary (and lookup would be quicker), but that
  61. would require allocating an object for every character
  62. written (slow!). */
  63. static class CharacterKeywordPair
  64. { public char character; public String keyword; };
  65. static protected CharacterKeywordPair[] textKeywords;
  66. static {
  67. One = new Integer(1);
  68. Zero = new Integer(0);
  69. False = Boolean.valueOf(false);
  70. MagicToken = new Object();
  71. ZeroPointZero = new Float(0);
  72. Dictionary textKeywordDictionary = RTFReader.textKeywords;
  73. Enumeration keys = textKeywordDictionary.keys();
  74. Vector tempPairs = new Vector();
  75. while(keys.hasMoreElements()) {
  76. CharacterKeywordPair pair = new CharacterKeywordPair();
  77. pair.keyword = (String)keys.nextElement();
  78. pair.character = ((String)textKeywordDictionary.get(pair.keyword)).charAt(0);
  79. tempPairs.addElement(pair);
  80. }
  81. textKeywords = new CharacterKeywordPair[tempPairs.size()];
  82. tempPairs.copyInto(textKeywords);
  83. }
  84. static final char[] hexdigits = { '0', '1', '2', '3', '4', '5', '6', '7',
  85. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  86. static public void writeDocument(Document d, OutputStream to)
  87. throws IOException
  88. {
  89. RTFGenerator gen = new RTFGenerator(to);
  90. Element root = d.getDefaultRootElement();
  91. gen.examineElement(root);
  92. gen.writeRTFHeader();
  93. gen.writeDocumentProperties(d);
  94. /* TODO this assumes a particular element structure; is there
  95. a way to iterate more generically ? */
  96. int max = root.getElementCount();
  97. for(int idx = 0; idx < max; idx++)
  98. gen.writeParagraphElement(root.getElement(idx));
  99. gen.writeRTFTrailer();
  100. }
  101. public RTFGenerator(OutputStream to)
  102. {
  103. colorTable = new Hashtable();
  104. colorTable.put(defaultRTFColor, new Integer(0));
  105. colorCount = 1;
  106. fontTable = new Hashtable();
  107. fontCount = 0;
  108. styleTable = new Hashtable();
  109. /* TODO: put default style in style table */
  110. styleCount = 0;
  111. workingSegment = new Segment();
  112. outputStream = to;
  113. unicodeCount = 1;
  114. }
  115. public void examineElement(Element el)
  116. {
  117. AttributeSet a = el.getAttributes();
  118. String fontName;
  119. Object foregroundColor, backgroundColor;
  120. tallyStyles(a);
  121. if (a != null) {
  122. /* TODO: default color must be color 0! */
  123. foregroundColor = StyleConstants.getForeground(a);
  124. if (foregroundColor != null &&
  125. colorTable.get(foregroundColor) == null) {
  126. colorTable.put(foregroundColor, new Integer(colorCount));
  127. colorCount ++;
  128. }
  129. backgroundColor = a.getAttribute(StyleConstants.Background);
  130. if (backgroundColor != null &&
  131. colorTable.get(backgroundColor) == null) {
  132. colorTable.put(backgroundColor, new Integer(colorCount));
  133. colorCount ++;
  134. }
  135. fontName = StyleConstants.getFontFamily(a);
  136. if (fontName == null)
  137. fontName = defaultFontFamily;
  138. if (fontName != null &&
  139. fontTable.get(fontName) == null) {
  140. fontTable.put(fontName, new Integer(fontCount));
  141. fontCount ++;
  142. }
  143. }
  144. int el_count = el.getElementCount();
  145. for(int el_idx = 0; el_idx < el_count; el_idx ++) {
  146. examineElement(el.getElement(el_idx));
  147. }
  148. }
  149. private void tallyStyles(AttributeSet a) {
  150. while (a != null) {
  151. if (a instanceof Style) {
  152. Integer aNum = (Integer)styleTable.get(a);
  153. if (aNum == null) {
  154. styleCount = styleCount + 1;
  155. aNum = new Integer(styleCount);
  156. styleTable.put(a, aNum);
  157. }
  158. }
  159. a = a.getResolveParent();
  160. }
  161. }
  162. private Style findStyle(AttributeSet a)
  163. {
  164. while(a != null) {
  165. if (a instanceof Style) {
  166. Object aNum = styleTable.get(a);
  167. if (aNum != null)
  168. return (Style)a;
  169. }
  170. a = a.getResolveParent();
  171. }
  172. return null;
  173. }
  174. private Integer findStyleNumber(AttributeSet a, String domain)
  175. {
  176. while(a != null) {
  177. if (a instanceof Style) {
  178. Integer aNum = (Integer)styleTable.get(a);
  179. if (aNum != null) {
  180. if (domain == null ||
  181. domain.equals(a.getAttribute(Constants.StyleType)))
  182. return aNum;
  183. }
  184. }
  185. a = a.getResolveParent();
  186. }
  187. return null;
  188. }
  189. static private Object attrDiff(MutableAttributeSet oldAttrs,
  190. AttributeSet newAttrs,
  191. Object key,
  192. Object dfl)
  193. {
  194. Object oldValue, newValue;
  195. oldValue = oldAttrs.getAttribute(key);
  196. newValue = newAttrs.getAttribute(key);
  197. if (newValue == oldValue)
  198. return null;
  199. if (newValue == null) {
  200. oldAttrs.removeAttribute(key);
  201. if (dfl != null && !dfl.equals(oldValue))
  202. return dfl;
  203. else
  204. return null;
  205. }
  206. if (oldValue == null ||
  207. !equalArraysOK(oldValue, newValue)) {
  208. oldAttrs.addAttribute(key, newValue);
  209. return newValue;
  210. }
  211. return null;
  212. }
  213. static private boolean equalArraysOK(Object a, Object b)
  214. {
  215. Object[] aa, bb;
  216. if (a == b)
  217. return true;
  218. if (a == null || b == null)
  219. return false;
  220. if (a.equals(b))
  221. return true;
  222. if (!(a.getClass().isArray() && b.getClass().isArray()))
  223. return false;
  224. aa = (Object[])a;
  225. bb = (Object[])b;
  226. if (aa.length != bb.length)
  227. return false;
  228. int i;
  229. int l = aa.length;
  230. for(i = 0; i < l; i++) {
  231. if (!equalArraysOK(aa[i], bb[i]))
  232. return false;
  233. }
  234. return true;
  235. }
  236. /* Writes a line break to the output file, for ease in debugging */
  237. public void writeLineBreak()
  238. throws IOException
  239. {
  240. writeRawString("\n");
  241. afterKeyword = false;
  242. }
  243. public void writeRTFHeader()
  244. throws IOException
  245. {
  246. int index;
  247. /* TODO: Should the writer attempt to examine the text it's writing
  248. and pick a character set which will most compactly represent the
  249. document? (currently the writer always uses the ansi character
  250. set, which is roughly ISO-8859 Latin-1, and uses Unicode escapes
  251. for all other characters. However Unicode is a relatively
  252. recent addition to RTF, and not all readers will understand it.) */
  253. writeBegingroup();
  254. writeControlWord("rtf", 1);
  255. writeControlWord("ansi");
  256. outputConversion = outputConversionForName("ansi");
  257. writeLineBreak();
  258. /* write font table */
  259. String[] sortedFontTable = new String[fontCount];
  260. Enumeration fonts = fontTable.keys();
  261. String font;
  262. while(fonts.hasMoreElements()) {
  263. font = (String)fonts.nextElement();
  264. Integer num = (Integer)(fontTable.get(font));
  265. sortedFontTable[num.intValue()] = font;
  266. }
  267. writeBegingroup();
  268. writeControlWord("fonttbl");
  269. for(index = 0; index < fontCount; index ++) {
  270. writeControlWord("f", index);
  271. writeControlWord("fnil"); /* TODO: supply correct font style */
  272. writeText(sortedFontTable[index]);
  273. writeText(";");
  274. }
  275. writeEndgroup();
  276. writeLineBreak();
  277. /* write color table */
  278. if (colorCount > 1) {
  279. Color[] sortedColorTable = new Color[colorCount];
  280. Enumeration colors = colorTable.keys();
  281. Color color;
  282. while(colors.hasMoreElements()) {
  283. color = (Color)colors.nextElement();
  284. Integer num = (Integer)(colorTable.get(color));
  285. sortedColorTable[num.intValue()] = color;
  286. }
  287. writeBegingroup();
  288. writeControlWord("colortbl");
  289. for(index = 0; index < colorCount; index ++) {
  290. color = sortedColorTable[index];
  291. if (color != null) {
  292. writeControlWord("red", color.getRed());
  293. writeControlWord("green", color.getGreen());
  294. writeControlWord("blue", color.getBlue());
  295. }
  296. writeRawString(";");
  297. }
  298. writeEndgroup();
  299. writeLineBreak();
  300. }
  301. /* write the style sheet */
  302. if (styleCount > 1) {
  303. writeBegingroup();
  304. writeControlWord("stylesheet");
  305. Enumeration styles = styleTable.keys();
  306. while(styles.hasMoreElements()) {
  307. Style style = (Style)styles.nextElement();
  308. int styleNumber = ((Integer)styleTable.get(style)).intValue();
  309. writeBegingroup();
  310. String styleType = (String)style.getAttribute(Constants.StyleType);
  311. if (styleType == null)
  312. styleType = Constants.STParagraph;
  313. if (styleType.equals(Constants.STCharacter)) {
  314. writeControlWord("*");
  315. writeControlWord("cs", styleNumber);
  316. } else if(styleType.equals(Constants.STSection)) {
  317. writeControlWord("*");
  318. writeControlWord("ds", styleNumber);
  319. } else {
  320. writeControlWord("s", styleNumber);
  321. }
  322. AttributeSet basis = style.getResolveParent();
  323. MutableAttributeSet goat;
  324. if (basis == null) {
  325. goat = new SimpleAttributeSet();
  326. } else {
  327. goat = new SimpleAttributeSet(basis);
  328. }
  329. updateSectionAttributes(goat, style, false);
  330. updateParagraphAttributes(goat, style, false);
  331. updateCharacterAttributes(goat, style, false);
  332. basis = style.getResolveParent();
  333. if (basis != null && basis instanceof Style) {
  334. Integer basedOn = (Integer)styleTable.get(basis);
  335. if (basedOn != null) {
  336. writeControlWord("sbasedon", basedOn.intValue());
  337. }
  338. }
  339. Style nextStyle = (Style)style.getAttribute(Constants.StyleNext);
  340. if (nextStyle != null) {
  341. Integer nextNum = (Integer)styleTable.get(nextStyle);
  342. if (nextNum != null) {
  343. writeControlWord("snext", nextNum.intValue());
  344. }
  345. }
  346. Boolean hidden = (Boolean)style.getAttribute(Constants.StyleHidden);
  347. if (hidden != null && hidden.booleanValue())
  348. writeControlWord("shidden");
  349. Boolean additive = (Boolean)style.getAttribute(Constants.StyleAdditive);
  350. if (additive != null && additive.booleanValue())
  351. writeControlWord("additive");
  352. writeText(style.getName());
  353. writeText(";");
  354. writeEndgroup();
  355. }
  356. writeEndgroup();
  357. writeLineBreak();
  358. }
  359. outputAttributes = new SimpleAttributeSet();
  360. }
  361. void writeDocumentProperties(Document doc)
  362. throws IOException
  363. {
  364. /* Write the document properties */
  365. int i;
  366. boolean wroteSomething = false;
  367. for(i = 0; i < RTFAttributes.attributes.length; i++) {
  368. RTFAttribute attr = RTFAttributes.attributes[i];
  369. if (attr.domain() != RTFAttribute.D_DOCUMENT)
  370. continue;
  371. Object prop = doc.getProperty(attr.swingName());
  372. boolean ok = attr.writeValue(prop, this, false);
  373. if (ok)
  374. wroteSomething = true;
  375. }
  376. if (wroteSomething)
  377. writeLineBreak();
  378. }
  379. public void writeRTFTrailer()
  380. throws IOException
  381. {
  382. writeEndgroup();
  383. writeLineBreak();
  384. }
  385. protected void checkNumericControlWord(MutableAttributeSet currentAttributes,
  386. AttributeSet newAttributes,
  387. Object attrName,
  388. String controlWord,
  389. float dflt, float scale)
  390. throws IOException
  391. {
  392. Object parm;
  393. if ((parm = attrDiff(currentAttributes, newAttributes,
  394. attrName, MagicToken)) != null) {
  395. float targ;
  396. if (parm == MagicToken)
  397. targ = dflt;
  398. else
  399. targ = ((Number)parm).floatValue();
  400. writeControlWord(controlWord, Math.round(targ * scale));
  401. }
  402. }
  403. protected void checkControlWord(MutableAttributeSet currentAttributes,
  404. AttributeSet newAttributes,
  405. RTFAttribute word)
  406. throws IOException
  407. {
  408. Object parm;
  409. if ((parm = attrDiff(currentAttributes, newAttributes,
  410. word.swingName(), MagicToken)) != null) {
  411. if (parm == MagicToken)
  412. parm = null;
  413. word.writeValue(parm, this, true);
  414. }
  415. }
  416. protected void checkControlWords(MutableAttributeSet currentAttributes,
  417. AttributeSet newAttributes,
  418. RTFAttribute words[],
  419. int domain)
  420. throws IOException
  421. {
  422. int wordIndex;
  423. int wordCount = words.length;
  424. for(wordIndex = 0; wordIndex < wordCount; wordIndex++) {
  425. RTFAttribute attr = words[wordIndex];
  426. if (attr.domain() == domain)
  427. checkControlWord(currentAttributes, newAttributes, attr);
  428. }
  429. }
  430. void updateSectionAttributes(MutableAttributeSet current,
  431. AttributeSet newAttributes,
  432. boolean emitStyleChanges)
  433. throws IOException
  434. {
  435. if (emitStyleChanges) {
  436. Object oldStyle = current.getAttribute("sectionStyle");
  437. Object newStyle = findStyleNumber(newAttributes, Constants.STSection);
  438. if (oldStyle != newStyle) {
  439. if (oldStyle != null) {
  440. resetSectionAttributes(current);
  441. }
  442. if (newStyle != null) {
  443. writeControlWord("ds", ((Integer)newStyle).intValue());
  444. current.addAttribute("sectionStyle", newStyle);
  445. } else {
  446. current.removeAttribute("sectionStyle");
  447. }
  448. }
  449. }
  450. checkControlWords(current, newAttributes,
  451. RTFAttributes.attributes, RTFAttribute.D_SECTION);
  452. }
  453. protected void resetSectionAttributes(MutableAttributeSet currentAttributes)
  454. throws IOException
  455. {
  456. writeControlWord("sectd");
  457. int wordIndex;
  458. int wordCount = RTFAttributes.attributes.length;
  459. for(wordIndex = 0; wordIndex < wordCount; wordIndex++) {
  460. RTFAttribute attr = RTFAttributes.attributes[wordIndex];
  461. if (attr.domain() == RTFAttribute.D_SECTION)
  462. attr.setDefault(currentAttributes);
  463. }
  464. currentAttributes.removeAttribute("sectionStyle");
  465. }
  466. void updateParagraphAttributes(MutableAttributeSet current,
  467. AttributeSet newAttributes,
  468. boolean emitStyleChanges)
  469. throws IOException
  470. {
  471. Object parm;
  472. Object oldStyle, newStyle;
  473. /* The only way to get rid of tabs or styles is with the \pard keyword,
  474. emitted by resetParagraphAttributes(). Ideally we should avoid
  475. emitting \pard if the new paragraph's tabs are a superset of the old
  476. paragraph's tabs. */
  477. if (emitStyleChanges) {
  478. oldStyle = current.getAttribute("paragraphStyle");
  479. newStyle = findStyleNumber(newAttributes, Constants.STParagraph);
  480. if (oldStyle != newStyle) {
  481. if (oldStyle != null) {
  482. resetParagraphAttributes(current);
  483. oldStyle = null;
  484. }
  485. }
  486. } else {
  487. oldStyle = null;
  488. newStyle = null;
  489. }
  490. Object oldTabs = current.getAttribute(Constants.Tabs);
  491. Object newTabs = newAttributes.getAttribute(Constants.Tabs);
  492. if (oldTabs != newTabs) {
  493. if (oldTabs != null) {
  494. resetParagraphAttributes(current);
  495. oldTabs = null;
  496. oldStyle = null;
  497. }
  498. }
  499. if (oldStyle != newStyle && newStyle != null) {
  500. writeControlWord("s", ((Integer)newStyle).intValue());
  501. current.addAttribute("paragraphStyle", newStyle);
  502. }
  503. checkControlWords(current, newAttributes,
  504. RTFAttributes.attributes, RTFAttribute.D_PARAGRAPH);
  505. if (oldTabs != newTabs && newTabs != null) {
  506. TabStop tabs[] = (TabStop[])newTabs;
  507. int index;
  508. for(index = 0; index < tabs.length; index ++) {
  509. TabStop tab = tabs[index];
  510. switch (tab.getAlignment()) {
  511. case TabStop.ALIGN_LEFT:
  512. case TabStop.ALIGN_BAR:
  513. break;
  514. case TabStop.ALIGN_RIGHT:
  515. writeControlWord("tqr");
  516. break;
  517. case TabStop.ALIGN_CENTER:
  518. writeControlWord("tqc");
  519. break;
  520. case TabStop.ALIGN_DECIMAL:
  521. writeControlWord("tqdec");
  522. break;
  523. }
  524. switch (tab.getLeader()) {
  525. case TabStop.LEAD_NONE:
  526. break;
  527. case TabStop.LEAD_DOTS:
  528. writeControlWord("tldot");
  529. break;
  530. case TabStop.LEAD_HYPHENS:
  531. writeControlWord("tlhyph");
  532. break;
  533. case TabStop.LEAD_UNDERLINE:
  534. writeControlWord("tlul");
  535. break;
  536. case TabStop.LEAD_THICKLINE:
  537. writeControlWord("tlth");
  538. break;
  539. case TabStop.LEAD_EQUALS:
  540. writeControlWord("tleq");
  541. break;
  542. }
  543. int twips = Math.round(20f * tab.getPosition());
  544. if (tab.getAlignment() == TabStop.ALIGN_BAR) {
  545. writeControlWord("tb", twips);
  546. } else {
  547. writeControlWord("tx", twips);
  548. }
  549. }
  550. current.addAttribute(Constants.Tabs, tabs);
  551. }
  552. }
  553. public void writeParagraphElement(Element el)
  554. throws IOException
  555. {
  556. updateParagraphAttributes(outputAttributes, el.getAttributes(), true);
  557. int sub_count = el.getElementCount();
  558. for(int idx = 0; idx < sub_count; idx ++) {
  559. writeTextElement(el.getElement(idx));
  560. }
  561. writeControlWord("par");
  562. writeLineBreak(); /* makes the raw file more readable */
  563. }
  564. /* debugging. TODO: remove.
  565. private static String tabdump(Object tso)
  566. {
  567. String buf;
  568. int i;
  569. if (tso == null)
  570. return "[none]";
  571. TabStop[] ts = (TabStop[])tso;
  572. buf = "[";
  573. for(i = 0; i < ts.length; i++) {
  574. buf = buf + ts[i].toString();
  575. if ((i+1) < ts.length)
  576. buf = buf + ",";
  577. }
  578. return buf + "]";
  579. }
  580. */
  581. protected void resetParagraphAttributes(MutableAttributeSet currentAttributes)
  582. throws IOException
  583. {
  584. writeControlWord("pard");
  585. currentAttributes.addAttribute(StyleConstants.Alignment, Zero);
  586. int wordIndex;
  587. int wordCount = RTFAttributes.attributes.length;
  588. for(wordIndex = 0; wordIndex < wordCount; wordIndex++) {
  589. RTFAttribute attr = RTFAttributes.attributes[wordIndex];
  590. if (attr.domain() == RTFAttribute.D_PARAGRAPH)
  591. attr.setDefault(currentAttributes);
  592. }
  593. currentAttributes.removeAttribute("paragraphStyle");
  594. currentAttributes.removeAttribute(Constants.Tabs);
  595. }
  596. void updateCharacterAttributes(MutableAttributeSet current,
  597. AttributeSet newAttributes,
  598. boolean updateStyleChanges)
  599. throws IOException
  600. {
  601. Object parm;
  602. if (updateStyleChanges) {
  603. Object oldStyle = current.getAttribute("characterStyle");
  604. Object newStyle = findStyleNumber(newAttributes,
  605. Constants.STCharacter);
  606. if (oldStyle != newStyle) {
  607. if (oldStyle != null) {
  608. resetCharacterAttributes(current);
  609. }
  610. if (newStyle != null) {
  611. writeControlWord("cs", ((Integer)newStyle).intValue());
  612. current.addAttribute("characterStyle", newStyle);
  613. } else {
  614. current.removeAttribute("characterStyle");
  615. }
  616. }
  617. }
  618. if ((parm = attrDiff(current, newAttributes,
  619. StyleConstants.FontFamily, null)) != null) {
  620. Number fontNum = (Number)fontTable.get(parm);
  621. writeControlWord("f", fontNum.intValue());
  622. }
  623. checkNumericControlWord(current, newAttributes,
  624. StyleConstants.FontSize, "fs",
  625. defaultFontSize, 2f);
  626. checkControlWords(current, newAttributes,
  627. RTFAttributes.attributes, RTFAttribute.D_CHARACTER);
  628. checkNumericControlWord(current, newAttributes,
  629. StyleConstants.LineSpacing, "sl",
  630. 0, 20f); /* TODO: sl wackiness */
  631. if ((parm = attrDiff(current, newAttributes,
  632. StyleConstants.Background, MagicToken)) != null) {
  633. int colorNum;
  634. if (parm == MagicToken)
  635. colorNum = 0;
  636. else
  637. colorNum = ((Number)colorTable.get(parm)).intValue();
  638. writeControlWord("cb", colorNum);
  639. }
  640. if ((parm = attrDiff(current, newAttributes,
  641. StyleConstants.Foreground, null)) != null) {
  642. int colorNum;
  643. if (parm == MagicToken)
  644. colorNum = 0;
  645. else
  646. colorNum = ((Number)colorTable.get(parm)).intValue();
  647. writeControlWord("cf", colorNum);
  648. }
  649. }
  650. protected void resetCharacterAttributes(MutableAttributeSet currentAttributes)
  651. throws IOException
  652. {
  653. writeControlWord("plain");
  654. int wordIndex;
  655. int wordCount = RTFAttributes.attributes.length;
  656. for(wordIndex = 0; wordIndex < wordCount; wordIndex++) {
  657. RTFAttribute attr = RTFAttributes.attributes[wordIndex];
  658. if (attr.domain() == RTFAttribute.D_CHARACTER)
  659. attr.setDefault(currentAttributes);
  660. }
  661. StyleConstants.setFontFamily(currentAttributes, defaultFontFamily);
  662. currentAttributes.removeAttribute(StyleConstants.FontSize); /* =default */
  663. currentAttributes.removeAttribute(StyleConstants.Background);
  664. currentAttributes.removeAttribute(StyleConstants.Foreground);
  665. currentAttributes.removeAttribute(StyleConstants.LineSpacing);
  666. currentAttributes.removeAttribute("characterStyle");
  667. }
  668. public void writeTextElement(Element el)
  669. throws IOException
  670. {
  671. updateCharacterAttributes(outputAttributes, el.getAttributes(), true);
  672. if (el.isLeaf()) {
  673. try {
  674. el.getDocument().getText(el.getStartOffset(),
  675. el.getEndOffset() - el.getStartOffset(),
  676. this.workingSegment);
  677. } catch (BadLocationException ble) {
  678. /* TODO is this the correct error to raise? */
  679. ble.printStackTrace();
  680. throw new InternalError(ble.getMessage());
  681. }
  682. writeText(this.workingSegment);
  683. } else {
  684. int sub_count = el.getElementCount();
  685. for(int idx = 0; idx < sub_count; idx ++)
  686. writeTextElement(el.getElement(idx));
  687. }
  688. }
  689. public void writeText(Segment s)
  690. throws IOException
  691. {
  692. int pos, end;
  693. char[] array;
  694. pos = s.offset;
  695. end = pos + s.count;
  696. array = s.array;
  697. for( ; pos < end; pos ++)
  698. writeCharacter(array[pos]);
  699. }
  700. public void writeText(String s)
  701. throws IOException
  702. {
  703. int pos, end;
  704. pos = 0;
  705. end = s.length();
  706. for( ; pos < end; pos ++)
  707. writeCharacter(s.charAt(pos));
  708. }
  709. public void writeRawString(String str)
  710. throws IOException
  711. {
  712. int strlen = str.length();
  713. for (int offset = 0; offset < strlen; offset ++)
  714. outputStream.write((int)str.charAt(offset));
  715. }
  716. public void writeControlWord(String keyword)
  717. throws IOException
  718. {
  719. outputStream.write('\\');
  720. writeRawString(keyword);
  721. afterKeyword = true;
  722. }
  723. public void writeControlWord(String keyword, int arg)
  724. throws IOException
  725. {
  726. outputStream.write('\\');
  727. writeRawString(keyword);
  728. writeRawString(String.valueOf(arg)); /* TODO: correct in all cases? */
  729. afterKeyword = true;
  730. }
  731. public void writeBegingroup()
  732. throws IOException
  733. {
  734. outputStream.write('{');
  735. afterKeyword = false;
  736. }
  737. public void writeEndgroup()
  738. throws IOException
  739. {
  740. outputStream.write('}');
  741. afterKeyword = false;
  742. }
  743. public void writeCharacter(char ch)
  744. throws IOException
  745. {
  746. /* Nonbreaking space is in most RTF encodings, but the keyword is
  747. preferable; same goes for tabs */
  748. if (ch == 0xA0) { /* nonbreaking space */
  749. outputStream.write(0x5C); /* backslash */
  750. outputStream.write(0x7E); /* tilde */
  751. afterKeyword = false; /* non-alpha keywords are self-terminating */
  752. return;
  753. }
  754. if (ch == 0x09) { /* horizontal tab */
  755. writeControlWord("tab");
  756. return;
  757. }
  758. if (ch == 10 || ch == 13) { /* newline / paragraph */
  759. /* ignore CRs, we'll write a paragraph element soon enough */
  760. return;
  761. }
  762. int b = convertCharacter(outputConversion, ch);
  763. if (b == 0) {
  764. /* Unicode characters which have corresponding RTF keywords */
  765. int i;
  766. for(i = 0; i < textKeywords.length; i++) {
  767. if (textKeywords[i].character == ch) {
  768. writeControlWord(textKeywords[i].keyword);
  769. return;
  770. }
  771. }
  772. /* In some cases it would be reasonable to check to see if the
  773. glyph being written out is in the Symbol encoding, and if so,
  774. to switch to the Symbol font for this character. TODO. */
  775. /* Currently all unrepresentable characters are written as
  776. Unicode escapes. */
  777. String approximation = approximationForUnicode(ch);
  778. if (approximation.length() != unicodeCount) {
  779. unicodeCount = approximation.length();
  780. writeControlWord("uc", unicodeCount);
  781. }
  782. writeControlWord("u", (int)ch);
  783. writeRawString(" ");
  784. writeRawString(approximation);
  785. afterKeyword = false;
  786. return;
  787. }
  788. if (b > 127) {
  789. int nybble;
  790. outputStream.write('\\');
  791. outputStream.write('\'');
  792. nybble = ( b & 0xF0 ) >>> 4;
  793. outputStream.write(hexdigits[nybble]);
  794. nybble = ( b & 0x0F );
  795. outputStream.write(hexdigits[nybble]);
  796. afterKeyword = false;
  797. return;
  798. }
  799. switch (b) {
  800. case '}':
  801. case '{':
  802. case '\\':
  803. outputStream.write(0x5C); /* backslash */
  804. afterKeyword = false; /* in a keyword, actually ... */
  805. /* fall through */
  806. default:
  807. if (afterKeyword) {
  808. outputStream.write(0x20); /* space */
  809. afterKeyword = false;
  810. }
  811. outputStream.write(b);
  812. break;
  813. }
  814. }
  815. String approximationForUnicode(char ch)
  816. {
  817. /* TODO: Find reasonable approximations for all Unicode characters
  818. in all RTF code pages... heh, heh... */
  819. return "?";
  820. }
  821. /** Takes a translation table (a 256-element array of characters)
  822. * and creates an output conversion table for use by
  823. * convertCharacter(). */
  824. /* Not very efficient at all. Could be changed to sort the table
  825. for binary search. TODO. (Even though this is inefficient however,
  826. writing RTF is still much faster than reading it.) */
  827. static int[] outputConversionFromTranslationTable(char[] table)
  828. {
  829. int[] conversion = new int[2 * table.length];
  830. int index;
  831. for(index = 0; index < table.length; index ++) {
  832. conversion[index * 2] = table[index];
  833. conversion[(index * 2) + 1] = index;
  834. }
  835. return conversion;
  836. }
  837. static int[] outputConversionForName(String name)
  838. throws IOException
  839. {
  840. char[] table = (char[])RTFReader.getCharacterSet(name);
  841. return outputConversionFromTranslationTable(table);
  842. }
  843. /** Takes a char and a conversion table (an int[] in the current
  844. * implementation, but conversion tables should be treated as an opaque
  845. * type) and returns the
  846. * corresponding byte value (as an int, since bytes are signed).
  847. */
  848. /* Not very efficient. TODO. */
  849. static protected int convertCharacter(int[] conversion, char ch)
  850. {
  851. int index;
  852. for(index = 0; index < conversion.length; index += 2) {
  853. if(conversion[index] == ch)
  854. return conversion[index + 1];
  855. }
  856. return 0; /* 0 indicates an unrepresentable character */
  857. }
  858. }