if (string.length() == 0) {
return 0;
}
FontMetrics metrics = getFontMetrics(font);
BreakIterator breakItr = BreakIterator.getLineInstance();
breakItr.setText(string);
int MIN, min, max;
if (avg == 0.0) {
avg = metrics.getAverageCharWidth();
}
int firstBreak = breakItr.next();
int winNL = string.indexOf("\r\n"); //$NON-NLS-1$
int macNL = string.indexOf('\r');
int unixNL = string.indexOf('\n');
MIN = min = (wrapping == CSSTextLayout.WORD_WRAP_HARD) ? firstBreak : 1;
if (macNL == winNL) {
macNL = -1; // If the Mac newline is just the prefix to the win NL,
// ignore it
}
max = string.length() + 1;
if (winNL != -1) {
max = Math.min(max, winNL);
min = Math.min(min, winNL);
}
if (unixNL != -1) {
max = Math.min(max, unixNL);
min = Math.min(min, unixNL);
}
if (macNL != -1) {
max = Math.min(max, macNL);
min = Math.min(min, macNL);
}
int origMax = max;
// The size of the current guess
int guess = 0, guessSize = 0;
while ((max - min) > 1) {
// Pick a new guess size
// New guess is the last guess plus the missing width in pixels
// divided by the average character size in pixels
guess = guess + (int) ((availableWidth - guessSize) / avg);
if (guess >= max) {
guess = max - 1;
}
if (guess <= min) {
guess = min + 1;
}
// Measure the current guess
guessSize = getStringExtents2(string.substring(0, guess), font).width;
if (guessSize <= availableWidth) {
// We did not use the available width
min = guess;
} else {
// We exceeded the available width
max = guess;
}
}
int result = string.length();
switch (wrapping) {
case CSSTextLayout.WORD_WRAP_HARD:
if (min == string.length() || min == winNL || min == unixNL
|| min == macNL) {
result = min;
} else if (max == origMax
&& getStringExtents2(string.substring(0, max), font).width <= availableWidth) {
result = max;
} else {
result = Math.max(MIN, breakItr.preceding(Math.min(max, string
.length() - 1)));
}
break;
case CSSTextLayout.WORD_WRAP_SOFT:
if (min == string.length() || min == winNL || min == unixNL
|| min == macNL) {
result = min;
} else if (max == origMax
&& getStringExtents2(string.substring(0, max), font).width <= availableWidth) {
result = max;
} else if (breakItr.isBoundary(min)) {
result = min;
} else if (breakItr.isBoundary(Math.min(max, string.length() - 1))) {
result = max;
} else {
result = breakItr.preceding(Math.min(max, string.length() - 1));
}
if (result <= 0) {
result = min;
}
break;