Java Code Examples for org.eclipse.jface.text.source.IAnnotationModel#getAnnotationIterator()

The following examples show how to use org.eclipse.jface.text.source.IAnnotationModel#getAnnotationIterator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavaCompilationParticipantTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private List<GWTJavaProblem> getGWTProblemsInEditor(CompilationUnitEditor editor)
    throws Exception {
  List<GWTJavaProblem> problems = new ArrayList<GWTJavaProblem>();

  Field annotationProblemField = CompilationUnitDocumentProvider.ProblemAnnotation.class.getDeclaredField("fProblem");
  annotationProblemField.setAccessible(true);

  IEditorInput editorInput = editor.getEditorInput();
  IDocumentProvider documentProvider = editor.getDocumentProvider();
  IAnnotationModel annotationModel = documentProvider.getAnnotationModel(editorInput);
  Iterator<?> iter = annotationModel.getAnnotationIterator();
  while (iter.hasNext()) {
    Object annotation = iter.next();
    if (annotation instanceof CompilationUnitDocumentProvider.ProblemAnnotation) {
      CompilationUnitDocumentProvider.ProblemAnnotation problemAnnotation = (ProblemAnnotation) annotation;
      if (problemAnnotation.getMarkerType().equals(GWTJavaProblem.MARKER_ID)) {
        GWTJavaProblem problem = (GWTJavaProblem) annotationProblemField.get(problemAnnotation);
        problems.add(problem);
      }
    }
  }

  return problems;
}
 
Example 2
Source File: CorrectionMarkerResolutionGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: ScriptValidator.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 );
			}
		}
	}
}
 
Example 5
Source File: ProblemsLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: JsonQuickAssistProcessor.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example 7
Source File: AbstractASTResolution.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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;
  }
 
Example 8
Source File: ContributionAnnotationManager.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method is only called if an annotation with length &gt; 1 should be inserted, because if
 * text is pasted at a position that already contains an annotation, the content change on the
 * {@link IDocument} that is performed by the caller of {@link #insertAnnotation} leads to an
 * internal change of the annotation model.
 *
 * <p>The annotation with length &gt; 1 is removed, because the new annotation is subsequently
 * added by {@link #insertAnnotation}
 *
 * <p>Therefore, this methods works against the internal mechanisms of eclipse in order to enforce
 * the invariant of annotations with have a length &lt;= 1.
 *
 * @param model The model that could contain a violation of the invariant.
 */
private void enforceAnnotationsWithLengthOne(IAnnotationModel model) {
  List<ContributionAnnotation> annotationsToRemove = new ArrayList<>();

  Iterator<Annotation> i = model.getAnnotationIterator();
  while (i.hasNext()) {
    Annotation annotation = i.next();

    if (!(annotation instanceof ContributionAnnotation)) continue;

    ContributionAnnotation contrAnnotation = (ContributionAnnotation) annotation;
    Position p = model.getPosition(contrAnnotation);
    if (p.getLength() > 1) {
      annotationsToRemove.add(contrAnnotation);

      // Expect only one annotation with length > 1 created by
      // callers content change.
      break;
    }
  }
  annotationModelHelper.replaceAnnotationsInModel(
      model, annotationsToRemove, Collections.emptyMap());
}
 
Example 9
Source File: ModulaSpellingHover.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
private HoverInfoWithSpellingAnnotation getSpellingHover(ITextViewer textViewer, IRegion hoverRegion) {
    IAnnotationModel model= null;
    if (textViewer instanceof ISourceViewerExtension2) {
        model = ((ISourceViewerExtension2)textViewer).getVisualAnnotationModel();
    } else if (textViewer instanceof SourceViewer) {
        model= ((SourceViewer)textViewer).getAnnotationModel();
    }
    if (model != null) {
        @SuppressWarnings("rawtypes")
        Iterator e= model.getAnnotationIterator();
        while (e.hasNext()) {
            Annotation a= (Annotation) e.next();
            if (a instanceof SpellingAnnotation) {
                Position p= model.getPosition(a);
                if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
                    return new HoverInfoWithSpellingAnnotation((SpellingAnnotation)a, textViewer, p.getOffset());
                }
            }
        }
    }
    return null;
}
 
Example 10
Source File: XtextEditor.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example 11
Source File: ModulaOccurrencesMarker.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private Annotation[] findExistentAnnotations(Set<String> types) {
    final IAnnotationModel model = viewer.getAnnotationModel();
    final List<Annotation> annotations = new ArrayList<Annotation>();
    if (model != null) {
        final Iterator<?> it = model.getAnnotationIterator();
        while (it.hasNext()) {
            final Annotation annotation = (Annotation) it.next();
            String type = annotation.getType();
            if (types.contains(type)) {
                annotations.add(annotation);
            }
        }
    }
    return annotations.toArray(new Annotation[annotations.size()]);
}
 
Example 12
Source File: TexAnnotationHover.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find a problem marker from the given line and return its error message.
 * 
 * @param sourceViewer the source viewer
 * @param lineNumber line number in the file, starting from zero
 * @return the message of the marker of null, if no marker at the specified line
 */
public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) {
    IDocument document= sourceViewer.getDocument();
    IAnnotationModel model= sourceViewer.getAnnotationModel();
    
    if (model == null)
        return null;
    
    List<String> lineMarkers = null;

    Iterator<Annotation> e= model.getAnnotationIterator();
    while (e.hasNext()) {
        Annotation o= e.next();
        if (o instanceof MarkerAnnotation) {
            MarkerAnnotation a= (MarkerAnnotation) o;
            if (isRulerLine(model.getPosition(a), document, lineNumber)) {
                if (lineMarkers == null)
                    lineMarkers = new LinkedList<String>();
                lineMarkers.add(a.getMarker().getAttribute(IMarker.MESSAGE, null));
            }
        }
    }
    if (lineMarkers != null)
        return getMessage(lineMarkers);
    
    return null;
}
 
Example 13
Source File: AnnotationModelHelper.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private static Iterable<Annotation> toIterable(final IAnnotationModel model) {
  return new Iterable<Annotation>() {
    @Override
    public Iterator<Annotation> iterator() {
      return model.getAnnotationIterator();
    }
  };
}
 
Example 14
Source File: XtextEditorErrorTickUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: OccurrenceMarker.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
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);
}
 
Example 16
Source File: ContributionAnnotationManagerTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private int getAnnotationCount(final IAnnotationModel model) {
  int count = 0;

  final Iterator<Annotation> it = model.getAnnotationIterator();

  while (it.hasNext()) {
    count++;
    it.next();
  }

  return count;
}
 
Example 17
Source File: PyEditBreakpointSync.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private void updateAnnotations() {
    if (edit == null) {
        return;
    }
    IDocumentProvider provider = edit.getDocumentProvider();
    if (provider == null) {
        return;
    }
    IAnnotationModel model = provider.getAnnotationModel(edit.getEditorInput());
    if (model == null) {
        return;
    }

    IAnnotationModelExtension modelExtension = (IAnnotationModelExtension) model;

    List<Annotation> existing = new ArrayList<Annotation>();
    Iterator<Annotation> it = model.getAnnotationIterator();
    if (it == null) {
        return;
    }
    while (it.hasNext()) {
        existing.add(it.next());
    }

    IDocument doc = edit.getDocument();
    IResource resource = PyMarkerUIUtils.getResourceForTextEditor(edit);
    IEditorInput externalFileEditorInput = AbstractBreakpointRulerAction.getExternalFileEditorInput(edit);
    List<IMarker> markers = AbstractBreakpointRulerAction.getMarkersFromEditorResource(resource, doc,
            externalFileEditorInput, 0, false, model);

    Map<Annotation, Position> annotationsToAdd = new HashMap<Annotation, Position>();
    for (IMarker m : markers) {
        Position pos = PyMarkerUIUtils.getMarkerPosition(doc, m, model);
        MarkerAnnotation newAnnotation = new MarkerAnnotation(m);
        annotationsToAdd.put(newAnnotation, pos);
    }

    //update all in a single step
    modelExtension.replaceAnnotations(existing.toArray(new Annotation[0]), annotationsToAdd);
}
 
Example 18
Source File: AbstractAnnotationHover.java    From typescript.java with MIT License 4 votes vote down vote up
@Override
public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
	IPath path;
	IAnnotationModel model;
	if (textViewer instanceof ISourceViewer) {
		path = null;
		model = ((ISourceViewer) textViewer).getAnnotationModel();
	} else {
		// Get annotation model from file buffer manager
		path = getEditorInputPath();
		model = getAnnotationModel(path);
	}
	if (model == null)
		return null;

	try {
		Iterator<Annotation> parent;
		if (model instanceof IAnnotationModelExtension2)
			parent = ((IAnnotationModelExtension2) model).getAnnotationIterator(hoverRegion.getOffset(),
					hoverRegion.getLength() > 0 ? hoverRegion.getLength() : 1, true, true);
		else
			parent = model.getAnnotationIterator();
		Iterator<Annotation> e = new TypeScriptAnnotationIterator(parent, fAllAnnotations);

		int layer = -1;
		Annotation annotation = null;
		Position position = null;
		while (e.hasNext()) {
			Annotation a = e.next();

			AnnotationPreference preference = getAnnotationPreference(a);
			if (preference == null || !(preference.getTextPreferenceKey() != null
			/*
			 * && fStore.getBoolean(preference.getTextPreferenceKey()) ||
			 * (preference.getHighlightPreferenceKey() != null &&
			 * fStore.getBoolean(preference.getHighlightPreferenceKey()))
			 */))
				continue;

			Position p = model.getPosition(a);

			int l = fAnnotationAccess.getLayer(a);

			if (l > layer && p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
				String msg = a.getText();
				if (msg != null && msg.trim().length() > 0) {
					layer = l;
					annotation = a;
					position = p;
				}
			}
		}
		if (layer > -1)
			return createAnnotationInfo(annotation, position, textViewer);

	} finally {
		try {
			if (path != null) {
				ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
				manager.disconnect(path, LocationKind.NORMALIZE, null);
			}
		} catch (CoreException ex) {
			TypeScriptUIPlugin.log(ex.getStatus());
		}
	}

	return null;
}
 
Example 19
Source File: AbstractAnnotationHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
	IPath path;
	IAnnotationModel model;
	if (textViewer instanceof ISourceViewer) {
		path= null;
		model= ((ISourceViewer)textViewer).getAnnotationModel();
	} else {
		// Get annotation model from file buffer manager
		path= getEditorInputPath();
		model= getAnnotationModel(path);
	}
	if (model == null)
		return null;

	try {
		Iterator<Annotation> parent;
		if (model instanceof IAnnotationModelExtension2)
			parent= ((IAnnotationModelExtension2)model).getAnnotationIterator(hoverRegion.getOffset(), hoverRegion.getLength(), true, true);
		else
			parent= model.getAnnotationIterator();
		Iterator<Annotation> e= new JavaAnnotationIterator(parent, fAllAnnotations);

		int layer= -1;
		Annotation annotation= null;
		Position position= null;
		while (e.hasNext()) {
			Annotation a= e.next();

			AnnotationPreference preference= getAnnotationPreference(a);
			if (preference == null || !(preference.getTextPreferenceKey() != null && fStore.getBoolean(preference.getTextPreferenceKey()) || (preference.getHighlightPreferenceKey() != null && fStore.getBoolean(preference.getHighlightPreferenceKey()))))
				continue;

			Position p= model.getPosition(a);

			int l= fAnnotationAccess.getLayer(a);

			if (l > layer && p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
				String msg= a.getText();
				if (msg != null && msg.trim().length() > 0) {
					layer= l;
					annotation= a;
					position= p;
				}
			}
		}
		if (layer > -1)
			return createAnnotationInfo(annotation, position, textViewer);

	} finally {
		try {
			if (path != null) {
				ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
				manager.disconnect(path, LocationKind.NORMALIZE, null);
			}
		} catch (CoreException ex) {
			JavaPlugin.log(ex.getStatus());
		}
	}

	return null;
}
 
Example 20
Source File: IssueDataTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testIssueData() throws Exception {
	IFile dslFile = dslFile(getProjectName(), getFileName(), getFileExtension(), MODEL_WITH_LINKING_ERROR);
	XtextEditor xtextEditor = openEditor(dslFile);
	IXtextDocument document = xtextEditor.getDocument();
	IResource file = xtextEditor.getResource();
	List<Issue> issues = getAllValidationIssues(document);
	assertEquals(1, issues.size());
	Issue issue = issues.get(0);
	assertEquals(2, issue.getLineNumber().intValue());
	assertEquals(3, issue.getColumn().intValue());
	assertEquals(PREFIX.length(), issue.getOffset().intValue());
	assertEquals(QuickfixCrossrefTestLanguageValidator.TRIGGER_VALIDATION_ISSUE.length(), issue.getLength().intValue());
	String[] expectedIssueData = new String[]{ QuickfixCrossrefTestLanguageValidator.ISSUE_DATA_0,
		QuickfixCrossrefTestLanguageValidator.ISSUE_DATA_1};
	assertTrue(Arrays.equals(expectedIssueData, issue.getData()));
	Thread.sleep(1000);

	IAnnotationModel annotationModel = xtextEditor.getDocumentProvider().getAnnotationModel(
			xtextEditor.getEditorInput());
	AnnotationIssueProcessor annotationIssueProcessor = 
			new AnnotationIssueProcessor(document, annotationModel, new IssueResolutionProvider.NullImpl());
	annotationIssueProcessor.processIssues(issues, new NullProgressMonitor());
	Iterator<?> annotationIterator = annotationModel.getAnnotationIterator();
	// filter QuickDiffAnnotations
	List<Object> allAnnotations = Lists.newArrayList(annotationIterator);
	List<XtextAnnotation> annotations = newArrayList(filter(allAnnotations, XtextAnnotation.class));
	assertEquals(annotations.toString(), 1, annotations.size());
	XtextAnnotation annotation = annotations.get(0);
	assertTrue(Arrays.equals(expectedIssueData, annotation.getIssueData()));
	IssueUtil issueUtil = new IssueUtil();
	Issue issueFromAnnotation = issueUtil.getIssueFromAnnotation(annotation);
	assertTrue(Arrays.equals(expectedIssueData, issueFromAnnotation.getData()));

	new MarkerCreator().createMarker(issue, file, MarkerTypes.FAST_VALIDATION);
	IMarker[] markers = file.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_ZERO);
	String errorMessage = new AnnotatedTextToString().withFile(dslFile).withMarkers(markers).toString().trim();
	assertEquals(errorMessage, 1, markers.length);
	String attribute = (String) markers[0].getAttribute(Issue.DATA_KEY);
	assertNotNull(attribute);
	assertTrue(Arrays.equals(expectedIssueData, Strings.unpack(attribute)));

	Issue issueFromMarker = issueUtil.createIssue(markers[0]);
	assertEquals(issue.getColumn(), issueFromMarker.getColumn());
	assertEquals(issue.getLineNumber(), issueFromMarker.getLineNumber());
	assertEquals(issue.getOffset(), issueFromMarker.getOffset());
	assertEquals(issue.getLength(), issueFromMarker.getLength());
	assertTrue(Arrays.equals(expectedIssueData, issueFromMarker.getData()));
}