1 17 18 19 20 21 27 28 package org.apache.fop.render.rtf.rtflib.rtfdoc; 29 30 import java.util.Iterator ; 31 import java.util.StringTokenizer ; 32 33 36 37 class WhitespaceCollapser { 38 private static final String SPACE = " "; 39 private boolean lastEndSpace = true; 40 41 42 WhitespaceCollapser(RtfContainer c) { 43 for (Iterator it = c.getChildren().iterator(); it.hasNext();) { 45 final Object kid = it.next(); 46 if (kid instanceof RtfText) { 47 RtfText current = (RtfText)kid; 48 processText(current); 49 } else if (kid instanceof RtfString) { 50 RtfString current = (RtfString)kid; 51 processString(current); 52 } else { 53 lastEndSpace = true; 55 } 56 } 57 } 58 59 60 private void processText(RtfText txt) { 61 final String newString = processString(txt.getText()); 62 if (newString != null) { 63 txt.setText(newString); 64 } 65 } 66 67 68 private void processString(RtfString txt) { 69 final String newString = processString(txt.getText()); 70 if (newString != null) { 71 txt.setText(newString); 72 } 73 } 74 75 76 private String processString(String txt) { 77 final String orig = txt; 78 79 if (orig == null) { 82 return null; 83 } else if (orig.length() > 0) { 84 final boolean allSpaces = orig.trim().length() == 0; 85 final boolean endSpace = allSpaces 86 || Character.isWhitespace(orig.charAt(orig.length() - 1)); 87 final boolean beginSpace = Character.isWhitespace(orig.charAt(0)); 88 final StringBuffer sb = new StringBuffer (orig.length()); 89 90 if (allSpaces) { 92 if (!lastEndSpace) { 93 sb.append(SPACE); 94 } 95 } else { 96 boolean first = true; 99 final StringTokenizer stk = new StringTokenizer (txt, " \t\n\r"); 100 while (stk.hasMoreTokens()) { 101 if (first && beginSpace && !lastEndSpace) { 102 sb.append(SPACE); 103 } 104 first = false; 105 106 sb.append(stk.nextToken()); 107 if (stk.hasMoreTokens() || endSpace) { 108 sb.append(SPACE); 109 } 110 } 111 } 112 113 lastEndSpace = endSpace; 114 return sb.toString(); 115 } else { 116 return ""; 117 } 118 } 119 } 120 | Popular Tags |