1 11 package org.eclipse.jface.text; 12 13 import java.util.Iterator ; 14 15 import org.eclipse.core.runtime.Assert; 16 17 import org.eclipse.jface.text.source.Annotation; 18 import org.eclipse.jface.text.source.IAnnotationModel; 19 import org.eclipse.jface.text.source.ISourceViewer; 20 import org.eclipse.jface.text.source.ISourceViewerExtension2; 21 22 27 public class DefaultTextHover implements ITextHover { 28 29 30 private ISourceViewer fSourceViewer; 31 32 37 public DefaultTextHover(ISourceViewer sourceViewer) { 38 Assert.isNotNull(sourceViewer); 39 fSourceViewer= sourceViewer; 40 } 41 42 45 public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { 46 IAnnotationModel model= getAnnotationModel(fSourceViewer); 47 if (model == null) 48 return null; 49 50 Iterator e= model.getAnnotationIterator(); 51 while (e.hasNext()) { 52 Annotation a= (Annotation) e.next(); 53 if (isIncluded(a)) { 54 Position p= model.getPosition(a); 55 if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { 56 String msg= a.getText(); 57 if (msg != null && msg.trim().length() > 0) 58 return msg; 59 } 60 } 61 } 62 63 return null; 64 } 65 66 69 public IRegion getHoverRegion(ITextViewer textViewer, int offset) { 70 return findWord(textViewer.getDocument(), offset); 71 } 72 73 80 protected boolean isIncluded(Annotation annotation) { 81 return true; 82 } 83 84 private IAnnotationModel getAnnotationModel(ISourceViewer viewer) { 85 if (viewer instanceof ISourceViewerExtension2) { 86 ISourceViewerExtension2 extension= (ISourceViewerExtension2) viewer; 87 return extension.getVisualAnnotationModel(); 88 } 89 return viewer.getAnnotationModel(); 90 } 91 92 private IRegion findWord(IDocument document, int offset) { 93 int start= -1; 94 int end= -1; 95 96 try { 97 98 int pos= offset; 99 char c; 100 101 while (pos >= 0) { 102 c= document.getChar(pos); 103 if (!Character.isUnicodeIdentifierPart(c)) 104 break; 105 --pos; 106 } 107 108 start= pos; 109 110 pos= offset; 111 int length= document.getLength(); 112 113 while (pos < length) { 114 c= document.getChar(pos); 115 if (!Character.isUnicodeIdentifierPart(c)) 116 break; 117 ++pos; 118 } 119 120 end= pos; 121 122 } catch (BadLocationException x) { 123 } 124 125 if (start > -1 && end > -1) { 126 if (start == offset && end == offset) 127 return new Region(offset, 0); 128 else if (start == offset) 129 return new Region(start, end - start); 130 else 131 return new Region(start + 1, end - start - 1); 132 } 133 134 return null; 135 } 136 } 137 | Popular Tags |