1 11 12 package org.eclipse.pde.internal.ui.util; 13 14 import java.io.BufferedReader ; 15 import java.io.IOException ; 16 import java.io.Reader ; 17 18 import com.ibm.icu.text.BreakIterator; 19 import org.eclipse.swt.graphics.GC; 20 21 25 public class LineBreakingReader { 26 27 private BufferedReader fReader; 28 29 private GC fGC; 30 31 private int fMaxWidth; 32 33 private String fLine; 34 35 private int fOffset; 36 37 private BreakIterator fLineBreakIterator; 38 39 private boolean fBreakWords; 40 41 51 public LineBreakingReader(Reader reader, GC gc, int maxLineWidth) { 52 fReader = new BufferedReader (reader); 53 fGC = gc; 54 fMaxWidth = maxLineWidth; 55 fOffset = 0; 56 fLine = null; 57 fLineBreakIterator = BreakIterator.getLineInstance(); 58 fBreakWords = true; 59 } 60 61 public boolean isFormattedLine() { 62 return fLine != null; 63 } 64 65 72 public String readLine() throws IOException { 73 if (fLine == null) { 74 String line = fReader.readLine(); 75 if (line == null) 76 return null; 77 78 int lineLen = fGC.textExtent(line).x; 79 if (lineLen < fMaxWidth) { 80 return line; 81 } 82 fLine = line; 83 fLineBreakIterator.setText(line); 84 fOffset = 0; 85 } 86 int breakOffset = findNextBreakOffset(fOffset); 87 String res; 88 if (breakOffset != BreakIterator.DONE) { 89 res = fLine.substring(fOffset, breakOffset); 90 fOffset = findWordBegin(breakOffset); 91 if (fOffset == fLine.length()) { 92 fLine = null; 93 } 94 } else { 95 res = fLine.substring(fOffset); 96 fLine = null; 97 } 98 return res; 99 } 100 101 private int findNextBreakOffset(int currOffset) { 102 int currWidth = 0; 103 int nextOffset = fLineBreakIterator.following(currOffset); 104 while (nextOffset != BreakIterator.DONE) { 105 String word = fLine.substring(currOffset, nextOffset); 106 int wordWidth = fGC.textExtent(word).x; 107 int nextWidth = wordWidth + currWidth; 108 if (nextWidth > fMaxWidth) { 109 if (currWidth > 0) 110 return currOffset; 111 112 if (!fBreakWords) 113 return nextOffset; 114 115 int length = word.length(); 117 while (length >= 0) { 118 length--; 119 word = word.substring(0, length); 120 wordWidth = fGC.textExtent(word).x; 121 if (wordWidth + currWidth < fMaxWidth) 122 return currOffset + length; 123 } 124 return nextOffset; 125 } 126 currWidth = nextWidth; 127 currOffset = nextOffset; 128 nextOffset = fLineBreakIterator.next(); 129 } 130 return nextOffset; 131 } 132 133 private int findWordBegin(int idx) { 134 while (idx < fLine.length() 135 && Character.isWhitespace(fLine.charAt(idx))) { 136 idx++; 137 } 138 return idx; 139 } 140 } 141 | Popular Tags |