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