int l = t.length();
int max = l / 2;
int min = 0;
int mid = (max + min) / 2 - 1;
if (mid <= 0) return t;
TextLayout layout = new TextLayout(Display.getDefault());
layout.setText(t);
mid = validateOffset(layout, mid);
while (min < mid && mid < max)
{
String s1 = t.substring(0, mid);
String s2 = t.substring(validateOffset(layout, l - mid), l);
int l1 = gc.textExtent(s1, drawFlags).x;
int l2 = gc.textExtent(s2, drawFlags).x;
if (l1 + w + l2 > width)
{
max = mid;
mid = validateOffset(layout, (max + min) / 2);
}
else if (l1 + w + l2 < width)
{
min = mid;
mid = validateOffset(layout, (max + min) / 2);
}
else
{
min = max;
}
}
String result = mid == 0 ? t : t.substring(0, mid) + ELLIPSIS
+ t.substring(validateOffset(layout, l - mid), l);
layout.dispose();
return result;
}