int topPixel = -1;
// store the pixel coordinates to prevent the ui from flickering
StyledText widget = viewer.getTextWidget();
if (widget != null)
topPixel = widget.getTopPixel();
ITextViewerExtension viewerExtension = null;
if (viewer instanceof ITextViewerExtension) {
viewerExtension = (ITextViewerExtension) viewer;
viewerExtension.setRedraw(false);
}
DocumentRewriteSession rewriteSession = null;
try {
if (document instanceof IDocumentExtension4) {
rewriteSession = ((IDocumentExtension4) document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED_SMALL);
}
// compute import statement's offset
int offset = 0;
boolean startWithLineBreak = true;
boolean endWithLineBreak = false;
if (file.getImports().isEmpty()) {
startWithLineBreak = false;
if (clazz == null) {
offset = document.getLength();
} else {
ICompositeNode node = NodeModelUtils.getNode(clazz);
offset = node.getOffset();
endWithLineBreak = true;
}
} else {
ICompositeNode node = NodeModelUtils.getNode(file.getImports().get(file.getImports().size() - 1));
offset = node.getOffset() + node.getLength();
}
offset = Math.min(proposal.getReplacementOffset(), offset);
// apply short proposal
String escapedShortname = shortName;
if (valueConverter != null) {
escapedShortname = valueConverter.toString(shortName);
}
proposal.setCursorPosition(escapedShortname.length());
document.replace(proposal.getReplacementOffset(), proposal.getReplacementLength(), escapedShortname);
if( ! found ) {
// add import statement
String importStatement = (startWithLineBreak ? "\nimport " : "import ") + importConverter.toString(typeName);
if (endWithLineBreak)
importStatement += "\n\n";
document.replace(offset, 0, importStatement.toString());
proposal.setCursorPosition(proposal.getCursorPosition() + importStatement.length());
}
// set the pixel coordinates
if (widget != null) {
int additionalTopPixel = 0;
if (startWithLineBreak)
additionalTopPixel += widget.getLineHeight();
if (endWithLineBreak)
additionalTopPixel += 2 * widget.getLineHeight();
widget.setTopPixel(topPixel + additionalTopPixel);
}
} finally {
if (rewriteSession != null) {
((IDocumentExtension4) document).stopRewriteSession(rewriteSession);
}
if (viewerExtension != null)
viewerExtension.setRedraw(true);
}
}