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