下面列出了怎么用org.eclipse.jface.text.source.IAnnotationModel的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Sets annotations related to selections made by remote users.
*
* @param newAnnotation {@link SarosAnnotation} that is set during this call.
* @param position {@link Position} at which the annotation is replaced, removed, or updated.
* @param model {@link IAnnotationModel} that maintains the annotations for the opened document.
*/
private void setAnnotationForSelection(
final SarosAnnotation newAnnotation, Position position, IAnnotationModel model) {
if (newAnnotation == null || position == null) {
throw new IllegalArgumentException("Both newAnnotation and position must not be null");
}
Predicate<Annotation> predicate =
new Predicate<Annotation>() {
@Override
public boolean evaluate(Annotation annotation) {
return annotation.getType().equals(newAnnotation.getType())
&& ((SarosAnnotation) annotation).getSource().equals(newAnnotation.getSource());
}
};
Map<Annotation, Position> replacement =
Collections.singletonMap((Annotation) newAnnotation, position);
annotationModelHelper.replaceAnnotationsInModel(model, predicate, replacement);
}
/**
* updateAnnotations
*
* @param selection
*/
protected void updateAnnotations(ISelection selection) {
if (findOccurrencesJob != null) {
findOccurrencesJob.cancel();
}
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
IDocument document = getDocument();
IAnnotationModel annotationModel = getAnnotationModel();
if (document != null && annotationModel != null) {
findOccurrencesJob = new FindOccurrencesJob(document, textSelection, annotationModel);
findOccurrencesJob.schedule();
}
}
}
private MarkerAnnotation getMarkerAnnotation(IAnnotationModel annotationModel, IMarker marker) {
Iterator<Annotation> it = annotationModel.getAnnotationIterator();
while (it.hasNext()) {
Annotation tmp = it.next();
if (tmp instanceof MarkerAnnotation) {
IMarker theMarker = ((MarkerAnnotation) tmp).getMarker();
if (theMarker.equals(marker)) {
return (MarkerAnnotation) tmp;
}
}
}
return null;
}
/**
* Same as {@link #isMarkerStillValid(IMarker, IAnnotationModel)}, but obtains the annotation model from the
* marker's editor.
*/
@SuppressWarnings("deprecation")
private boolean isMarkerStillValid(IMarker marker) {
if (marker == null)
return false;
if (marker.getResource() instanceof IProject) {
// This happens with IssueCodes.NODE_MODULES_OUT_OF_SYNC
return true;
}
final XtextEditor editor = getEditor(marker.getResource());
if (editor == null)
return false;
final IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(
editor.getEditorInput());
if (annotationModel == null)
return false;
return isMarkerStillValid(marker, annotationModel);
}
public ExternalBreakpointWatcher(IEditorInput input, IDocument document, IAnnotationModel annotationModel) {
this.location = EditorUtils.getLocationOrNull(input);
this.document = assertNotNull(document);
this.annotationModel = assertNotNull(annotationModel);
if(annotationModel instanceof IAnnotationModelExtension) {
this.annotationModelExt = (IAnnotationModelExtension) annotationModel;
} else {
this.annotationModelExt = null;
}
if(location != null) {
ResourceUtils.connectResourceListener(resourceListener, this::initializeFromResources,
getWorkspaceRoot(), owned);
}
}
@Override
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
owned.disposeOwned(breakpointWatcher);
breakpointWatcher = null;
if(input == null) {
return;
}
IAnnotationModel annotationModel = getDocumentProvider().getAnnotationModel(input);
IFile file = EditorUtils.getAssociatedFile(input);
if(file != null || annotationModel == null) {
return; // No need for external breakpoint watching
}
breakpointWatcher = new ExternalBreakpointWatcher(input, getDocument(), annotationModel);
owned.bind(breakpointWatcher);
}
@SuppressWarnings("rawtypes")
private Annotation getAnnotation(final int offset, final int length) {
final IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
if (model == null || length < 0)
return null;
Iterator iterator;
if (model instanceof IAnnotationModelExtension2) {
iterator = ((IAnnotationModelExtension2) model).getAnnotationIterator(offset, length, true, true);
} else {
iterator = model.getAnnotationIterator();
}
while (iterator.hasNext()) {
final Annotation a = (Annotation) iterator.next();
final Position p = model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Creates an annotation model derived from the given class file editor input.
*
* @param classFileEditorInput the editor input from which to query the annotations
* @return the created annotation model
* @exception CoreException if the editor input could not be accessed
*/
protected IAnnotationModel createClassFileAnnotationModel(IClassFileEditorInput classFileEditorInput) throws CoreException {
IResource resource= null;
IClassFile classFile= classFileEditorInput.getClassFile();
IResourceLocator locator= (IResourceLocator) classFile.getAdapter(IResourceLocator.class);
if (locator != null)
resource= locator.getContainingResource(classFile);
if (resource != null) {
ClassFileMarkerAnnotationModel model= new ClassFileMarkerAnnotationModel(resource);
model.setClassFile(classFile);
return model;
}
return null;
}
private int getErrorTicksFromAnnotationModel(IAnnotationModel model, ISourceReference sourceElement) throws CoreException {
int info= 0;
Iterator<Annotation> iter= model.getAnnotationIterator();
while ((info != ERRORTICK_ERROR) && iter.hasNext()) {
Annotation annot= iter.next();
IMarker marker= isAnnotationInRange(model, annot, sourceElement);
if (marker != null) {
int priority= marker.getAttribute(IMarker.SEVERITY, -1);
if (priority == IMarker.SEVERITY_WARNING) {
info= ERRORTICK_WARNING;
} else if (priority == IMarker.SEVERITY_ERROR) {
info= ERRORTICK_ERROR;
}
}
}
return info;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
if (model == null)
return null;
Iterator<Annotation> parent;
if (model instanceof IAnnotationModelExtension2)
parent= ((IAnnotationModelExtension2)model).getAnnotationIterator(offset, length, true, true);
else
parent= model.getAnnotationIterator();
Iterator<Annotation> e= new JavaAnnotationIterator(parent, false);
while (e.hasNext()) {
Annotation a= e.next();
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
private static IProblemLocation findProblemLocation(IEditorInput input, IMarker marker) {
IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(input);
if (model != null) { // open in editor
Iterator<Annotation> iter= model.getAnnotationIterator();
while (iter.hasNext()) {
Annotation curr= iter.next();
if (curr instanceof JavaMarkerAnnotation) {
JavaMarkerAnnotation annot= (JavaMarkerAnnotation) curr;
if (marker.equals(annot.getMarker())) {
Position pos= model.getPosition(annot);
if (pos != null) {
return new ProblemLocation(pos.getOffset(), pos.getLength(), annot);
}
}
}
}
} else { // not open in editor
ICompilationUnit cu= getCompilationUnit(marker);
return createFromMarker(marker, cu);
}
return null;
}
/**
* Clears all annotations.
*/
private void clearAnnotations( )
{
IAnnotationModel annotationModel = scriptViewer.getAnnotationModel( );
if ( annotationModel != null )
{
for ( Iterator iterator = annotationModel.getAnnotationIterator( ); iterator.hasNext( ); )
{
Annotation annotation = (Annotation) iterator.next( );
if ( annotation != null &&
IReportGraphicConstants.ANNOTATION_ERROR.equals( annotation.getType( ) ) )
{
annotationModel.removeAnnotation( annotation );
}
}
}
}
/**
* Creates contribution annotations with length 1 for each char contained in the range defined by
* {@code offset} and {@code length}.
*
* @param model the model that is assigned to the created contribution annotations.
* @param offset start of the annotation range.
* @param length length of the annotation range.
* @param source of the annotation.
* @return a map containing the annotations and their positions
*/
private Map<ContributionAnnotation, Position> createAnnotationsForContributionRange(
final IAnnotationModel model, final int offset, final int length, final User source) {
final Map<ContributionAnnotation, Position> annotationsToAdd = new HashMap<>();
for (int i = 0; i < length; i++) {
final Pair<ContributionAnnotation, Position> positionedAnnotation =
createPositionedAnnotation(model, offset + i, source);
if (positionedAnnotation == null) continue;
annotationsToAdd.put(positionedAnnotation.getKey(), positionedAnnotation.getValue());
}
return annotationsToAdd;
}
@Override
@SuppressWarnings("PMD.UseVarargs")
public IMarker[] findOtherMarkers(final IMarker[] markers) {
final List<IMarker> result = Lists.newArrayList();
for (final IMarker marker : markers) {
if (!resolutionMarker.equals(marker) && markerCode.equals(getIssueUtil().getCode(marker))) {
XtextEditor editor = null;
if (Display.getCurrent() != null) {
editor = findEditor(marker.getResource());
}
if (editor != null) {
// if the resource is in an open editor compare the annotation with the marker
final IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
if (annotationModel != null && isMarkerStillValid(marker, annotationModel)) {
result.add(marker);
}
} else {
result.add(marker);
}
}
}
return result.toArray(new IMarker[result.size()]);
}
@Override
public void setDocument(IDocument document, IAnnotationModel annotationModel, int modelRangeOffset,
int modelRangeLength) {
// partial fix for:
// https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=1970
// when our document is set, especially to null during close,
// immediately uninstall the reconciler.
// this is to avoid an unnecessary final "reconcile"
// that blocks display thread
if (document == null) {
if (fReconciler != null) {
fReconciler.uninstall();
}
}
super.setDocument(document, annotationModel, modelRangeOffset, modelRangeLength);
}
protected List<IMarker> getMarkersFor(ISourceViewer sourceViewer, int lineOffset, int lineLength) {
List<IMarker> result = new ArrayList<>();
IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
Iterator<?> annotationIter = annotationModel.getAnnotationIterator();
while (annotationIter.hasNext()) {
Object annotation = annotationIter.next();
if (annotation instanceof MarkerAnnotation) {
MarkerAnnotation markerAnnotation = (MarkerAnnotation) annotation;
IMarker marker = markerAnnotation.getMarker();
Position markerPosition = annotationModel.getPosition(markerAnnotation);
if (markerPosition != null && markerPosition.overlapsWith(lineOffset, lineLength)) {
result.add(marker);
}
}
}
return result;
}
/**
* Removes annotations and replaces them in one step.
*
* @param model The {@link IAnnotationModel} that should be cleaned.
* @param annotationsToRemove The annotations to remove.
* @param annotationsToAdd The annotations to add.
*/
public void replaceAnnotationsInModel(
IAnnotationModel model,
Collection<? extends Annotation> annotationsToRemove,
Map<? extends Annotation, Position> annotationsToAdd) {
if (model instanceof IAnnotationModelExtension) {
IAnnotationModelExtension extension = (IAnnotationModelExtension) model;
extension.replaceAnnotations(
annotationsToRemove.toArray(new Annotation[annotationsToRemove.size()]),
annotationsToAdd);
} else {
if (log.isTraceEnabled())
log.trace("AnnotationModel " + model + " does not support IAnnotationModelExtension");
for (Annotation annotation : annotationsToRemove) {
model.removeAnnotation(annotation);
}
for (Entry<? extends Annotation, Position> entry : annotationsToAdd.entrySet()) {
model.addAnnotation(entry.getKey(), entry.getValue());
}
}
}
public RevisionInformation getRevisionInformation(IResource resource, ITextViewer viewer, ITextEditor textEditor) {
for (IRevisionInformationProvider provider : providers) {
if (provider.canApply(resource)) {
RevisionInformation info = provider.getRevisionInformation(resource);
if (info != null) {
ILineDiffer differ = provider.getDocumentLineDiffer(viewer, textEditor);
// Connect line differ
IAnnotationModelExtension ext = (IAnnotationModelExtension) ((ISourceViewer) viewer).getAnnotationModel();
ext.addAnnotationModel(RevisionInformationSupport.MY_QUICK_DIFF_MODEL_ID, (IAnnotationModel) differ);
return info;
}
}
}
return null;
}
@Override
public void annotationDefaultSelected(VerticalRulerEvent event) {
Annotation annotation= event.getSelectedAnnotation();
IAnnotationModel model= getAnnotationModel();
if (isOverrideIndicator(annotation)) {
((OverrideIndicatorManager.OverrideIndicator)annotation).open();
return;
}
if (isBreakpoint(annotation))
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK, event.getEvent());
Position position= model.getPosition(annotation);
if (position == null)
return;
if (isQuickFixTarget(annotation)) {
ITextOperationTarget operation= (ITextOperationTarget) getTextEditor().getAdapter(ITextOperationTarget.class);
final int opCode= ISourceViewer.QUICK_ASSIST;
if (operation != null && operation.canDoOperation(opCode)) {
getTextEditor().selectAndReveal(position.getOffset(), position.getLength());
operation.doOperation(opCode);
return;
}
}
// default:
super.annotationDefaultSelected(event);
}
private void uninstallSelectionListener() {
if (fListener != null) {
SelectionListenerWithASTManager.getDefault().removeListener(fEditor, fListener);
fListener= null;
}
IAnnotationModel model= getAnnotationModel();
if (model != null) {
removeLightBulb(model);
}
}
@Test public void testMarkOccurrences() throws Exception {
String model = "Foo { Bar(Foo) {} Baz(Foo Bar) {} }";
IFile modelFile = IResourcesSetupUtil.createFile("MarkOccurrencesTest/src/Test.outlinetestlanguage", model);
XtextEditor editor = openEditor(modelFile);
ISelectionProvider selectionProvider = editor.getSelectionProvider();
selectionProvider.setSelection(new TextSelection(0, 1));
IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
ExpectationBuilder listener = new ExpectationBuilder(editor, annotationModel).added(DECLARATION_ANNOTATION_TYPE, 0, 3)
.added(OCCURRENCE_ANNOTATION_TYPE, model.indexOf("Foo", 3), 3)
.added(OCCURRENCE_ANNOTATION_TYPE, model.lastIndexOf("Foo"), 3);
listener.start();
annotationModel.addAnnotationModelListener(listener);
setMarkOccurrences(true);
listener.verify(TIMEOUT);
listener.start();
listener.removed(DECLARATION_ANNOTATION_TYPE, 0, 3)
.removed(OCCURRENCE_ANNOTATION_TYPE, model.indexOf("Foo", 3), 3)
.removed(OCCURRENCE_ANNOTATION_TYPE, model.lastIndexOf("Foo"), 3)
.added(DECLARATION_ANNOTATION_TYPE, model.indexOf("Bar"), 3)
.added(OCCURRENCE_ANNOTATION_TYPE, model.lastIndexOf("Bar"), 3);
selectionProvider.setSelection(new TextSelection(model.lastIndexOf("Bar"), 1));
listener.verify(TIMEOUT);
listener.start();
listener.removed(DECLARATION_ANNOTATION_TYPE, model.indexOf("Bar"), 3).removed(OCCURRENCE_ANNOTATION_TYPE,
model.lastIndexOf("Bar"), 3);
setMarkOccurrences(false);
listener.verify(TIMEOUT);
}
/**
* @since 2.14
*/
public MarkerIssueProcessor(IResource resource, IAnnotationModel annotationModel, MarkerCreator markerCreator,
MarkerTypeProvider markerTypeProvider) {
super();
this.resource = resource;
this.annotationModel = annotationModel;
this.markerCreator = markerCreator;
this.markerTypeProvider = markerTypeProvider;
}
/**
* @since 2.14
*/
public AddMarkersOperation(IResource resource, List<Issue> issues, Set<String> markerIds, boolean deleteMarkers,
IAnnotationModel annotationModel, MarkerCreator markerCreator, MarkerTypeProvider markerTypeProvider) {
super(ResourcesPlugin.getWorkspace().getRuleFactory().markerRule(resource));
this.issues = issues;
this.annotationModel = annotationModel;
this.markerTypeProvider = markerTypeProvider;
this.markerIds = ImmutableList.copyOf(markerIds);
this.resource = resource;
this.deleteMarkers = deleteMarkers;
this.markerCreator = markerCreator;
}
public OverrideIndicatorManager(IAnnotationModel annotationModel, ITypeRoot javaElement, CompilationUnit ast) {
Assert.isNotNull(annotationModel);
Assert.isNotNull(javaElement);
fJavaElement= javaElement;
fAnnotationModel=annotationModel;
fAnnotationModelLockObject= getLockObject(fAnnotationModel);
updateAnnotations(ast, new NullProgressMonitor());
}
@Override
protected IStatus run(IProgressMonitor monitor) {
final XtextEditor editor = initialEditor;
final boolean isMarkOccurrences = initialIsMarkOccurrences;
final ITextSelection selection = initialSelection;
final SubMonitor progress = SubMonitor.convert(monitor, 2);
if (!progress.isCanceled()) {
final Map<Annotation, Position> annotations = (isMarkOccurrences) ? occurrenceComputer.createAnnotationMap(editor, selection,
progress.newChild(1)) : Collections.<Annotation, Position>emptyMap();
if (!progress.isCanceled()) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (!progress.isCanceled()) {
final IAnnotationModel annotationModel = getAnnotationModel(editor);
if (annotationModel instanceof IAnnotationModelExtension)
((IAnnotationModelExtension) annotationModel).replaceAnnotations(
getExistingOccurrenceAnnotations(annotationModel), annotations);
else if(annotationModel != null)
throw new IllegalStateException(
"AnnotationModel does not implement IAnnotationModelExtension"); //$NON-NLS-1$
}
}
});
return Status.OK_STATUS;
}
}
return Status.CANCEL_STATUS;
}
private IAnnotationModel getAnnotationModel() {
if (fTextEditor == null) {
return null;
}
final IDocumentProvider documentProvider = fTextEditor.getDocumentProvider();
if (documentProvider == null) {
return null;
}
return documentProvider.getAnnotationModel(fTextEditor.getEditorInput());
}
protected Annotation[] getExistingOccurrenceAnnotations(IAnnotationModel annotationModel) {
Set<Annotation> removeSet = newHashSet();
for (Iterator<Annotation> annotationIter = annotationModel.getAnnotationIterator(); annotationIter
.hasNext();) {
Annotation annotation = annotationIter.next();
if (occurrenceComputer.hasAnnotationType(annotation.getType())) {
removeSet.add(annotation);
}
}
return toArray(removeSet, Annotation.class);
}
@Override
protected IAnnotationModel createAnnotationModel(Object element) throws CoreException {
if (element instanceof IFileEditorInput) {
IFileEditorInput input = (IFileEditorInput) element;
return new XtextResourceMarkerAnnotationModel(input.getFile(), issueResolutionProvider, issueUtil);
} else if (element instanceof IURIEditorInput) {
return new AnnotationModel();
}
return super.createAnnotationModel(element);
}
protected Severity getSeverity(XtextEditor xtextEditor) {
if (xtextEditor == null || xtextEditor.getInternalSourceViewer() == null)
return null;
IAnnotationModel model = xtextEditor.getInternalSourceViewer().getAnnotationModel();
if (model != null) {
Iterator<Annotation> iterator = model.getAnnotationIterator();
boolean hasWarnings = false;
boolean hasInfos = false;
while (iterator.hasNext()) {
Annotation annotation = iterator.next();
if (!annotation.isMarkedDeleted()) {
Issue issue = issueUtil.getIssueFromAnnotation(annotation);
if (issue != null) {
if (issue.getSeverity() == Severity.ERROR) {
return Severity.ERROR;
} else if (issue.getSeverity() == Severity.WARNING) {
hasWarnings = true;
} else if (issue.getSeverity() == Severity.INFO) {
hasInfos = true;
}
}
}
}
if (hasWarnings)
return Severity.WARNING;
if (hasInfos)
return Severity.INFO;
}
return null;
}
private IAnnotationModel isInJavaAnnotationModel(ICompilationUnit original) {
if (original.isWorkingCopy()) {
FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource());
return JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput);
}
return null;
}