KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > api > java > source > UiUtils


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 package org.netbeans.api.java.source;
20
21 import com.sun.source.tree.ClassTree;
22 import com.sun.source.tree.CompilationUnitTree;
23 import com.sun.source.tree.MethodTree;
24 import com.sun.source.tree.Tree;
25 import com.sun.source.tree.VariableTree;
26 import com.sun.source.util.TreePath;
27 import com.sun.source.util.TreePathScanner;
28 import com.sun.tools.javac.util.Context;
29 import java.io.IOException JavaDoc;
30 import java.util.Collection JavaDoc;
31 import javax.lang.model.element.Element;
32 import javax.lang.model.element.ElementKind;
33 import javax.lang.model.element.Modifier;
34 import javax.swing.Icon JavaDoc;
35 import javax.swing.text.StyledDocument JavaDoc;
36 import org.netbeans.modules.java.source.pretty.VeryPretty;
37 import org.netbeans.modules.java.ui.Icons;
38 import org.openide.ErrorManager;
39 import org.openide.cookies.EditorCookie;
40 import org.openide.cookies.LineCookie;
41 import org.openide.cookies.OpenCookie;
42 import org.openide.filesystems.FileObject;
43 import org.openide.loaders.DataObject;
44 import org.openide.text.Line;
45 import org.openide.text.NbDocument;
46
47 /** This class contains various methods bound to visualization of Java model
48  * elements. It was formerly included under SourceUtils
49  *
50  * XXX - needs cleanup
51  *
52  * @author Jan Lahoda
53  */

54 public final class UiUtils {
55     
56     private UiUtils() {}
57     
58     /** Gets correct icon for given ElementKind.
59      *@param modifiers Can be null for empty modifiers collection
60      */

61     public static Icon JavaDoc getElementIcon( ElementKind elementKind, Collection JavaDoc<Modifier> modifiers ) {
62         return Icons.getElementIcon(elementKind, modifiers);
63     }
64     
65     // XXX Remove
66
@Deprecated JavaDoc
67     public static Icon JavaDoc getDeclarationIcon(Element element) {
68         return getElementIcon(element.getKind(), element.getModifiers());
69     }
70     
71     
72     /**
73      * Opens given {@link Element}.
74      *
75      * @param cpInfo fileobject whose {@link ClasspathInfo} will be used
76      * @param el declaration to open
77      * @return true if and only if the declaration was correctly opened,
78      * false otherwise
79      */

80     public static boolean open(final ClasspathInfo cpInfo, final Element el) {
81     Object JavaDoc[] openInfo = getOpenInfo (cpInfo, el);
82     if (openInfo != null) {
83         assert openInfo[0] instanceof FileObject;
84         assert openInfo[1] instanceof Integer JavaDoc;
85         return doOpen((FileObject)openInfo[0],(Integer JavaDoc)openInfo[1]);
86     }
87     return false;
88     }
89     
90     public static boolean open(final FileObject toSearch, final ElementHandle<? extends Element> toOpen) {
91         if (toSearch == null || toOpen == null) {
92             throw new IllegalArgumentException JavaDoc("null not supported");
93         }
94         
95         Object JavaDoc[] openInfo = getOpenInfo (toSearch, toOpen);
96         if (openInfo != null) {
97             assert openInfo[0] instanceof FileObject;
98             assert openInfo[1] instanceof Integer JavaDoc;
99             return doOpen((FileObject)openInfo[0],(Integer JavaDoc)openInfo[1]);
100         }
101         return false;
102     }
103     
104     private static String JavaDoc getMethodHeader(MethodTree tree, CompilationInfo info, String JavaDoc s) {
105         Context context = info.getJavacTask().getContext();
106         VeryPretty veryPretty = new VeryPretty(context);
107         return veryPretty.getMethodHeader(tree, s);
108     }
109
110     private static String JavaDoc getClassHeader(ClassTree tree, CompilationInfo info, String JavaDoc s) {
111         Context context = info.getJavacTask().getContext();
112         VeryPretty veryPretty = new VeryPretty(context);
113         return veryPretty.getClassHeader(tree, s);
114     }
115     private static String JavaDoc getVariableHeader(VariableTree tree, CompilationInfo info, String JavaDoc s) {
116         Context context = info.getJavacTask().getContext();
117         VeryPretty veryPretty = new VeryPretty(context);
118         return veryPretty.getVariableHeader(tree, s);
119     }
120     
121     public static final class PrintPart {
122         private PrintPart() {}
123         public static final String JavaDoc ANNOTATIONS = "%annotations"; //NOI18N
124
public static final String JavaDoc NAME = "%name%"; //NOI18N
125
public static final String JavaDoc TYPE = "%type%"; //NOI18N
126
public static final String JavaDoc THROWS = "%throws%"; //NOI18N
127
public static final String JavaDoc IMPLEMENTS = "%implements%"; //NOI18N
128
public static final String JavaDoc EXTENDS = "%extends%"; //NOI18N
129
public static final String JavaDoc TYPEPARAMETERS = "%typeparameters%"; //NOI18N
130
public static final String JavaDoc FLAGS = "%flags%"; //NOI18N
131
public static final String JavaDoc PARAMETERS = "%parameters%"; //NOI18N
132
}
133     
134     /**
135      * example of formatString:
136      * "method " + PrintPart.NAME + PrintPart.PARAMETERS + " has return type " + PrintPart.TYPE
137      */

138     public static String JavaDoc getHeader(TreePath treePath, CompilationInfo info, String JavaDoc formatString) {
139         assert info != null;
140         assert treePath != null;
141         Element element = info.getTrees().getElement(treePath);
142         if (element!=null)
143             return getHeader(element, info, formatString);
144         return null;
145     }
146
147     /**
148      * example of formatString:
149      * "method " + PrintPart.NAME + PrintPart.PARAMETERS + " has return type " + PrintPart.TYPE
150      */

151     public static String JavaDoc getHeader(Element element, CompilationInfo info, String JavaDoc formatString) {
152         assert element != null;
153         assert info != null;
154         assert formatString != null;
155         Tree tree = SourceUtils.treeFor(info, element);
156         if (tree != null) {
157             if (tree.getKind() == Tree.Kind.METHOD) {
158                 return getMethodHeader((MethodTree) tree, info, formatString);
159             } else if (tree.getKind() == Tree.Kind.CLASS) {
160                 return getClassHeader((ClassTree)tree, info, formatString);
161             } else if (tree.getKind() == Tree.Kind.VARIABLE) {
162                 return getVariableHeader((VariableTree)tree, info, formatString);
163             }
164         }
165         return formatString.replaceAll(PrintPart.NAME, element.getSimpleName().toString()).replaceAll("%[a-z]*%", ""); //NOI18N
166
}
167     
168     /**
169      * Opens given {@link Element}.
170      *
171      * @param fo fileobject whose {@link ClasspathInfo} will be used
172      * @param offset offset with fileobject
173      * @return true if and only if the declaration was correctly opened,
174      * false otherwise
175      */

176     public @Deprecated JavaDoc static boolean open(final FileObject fo, final int offset) {
177         return doOpen(fo, offset);
178     }
179     
180     static Object JavaDoc[] getOpenInfo (final ClasspathInfo cpInfo, final Element el) {
181         FileObject fo = SourceUtils.getFile(el, cpInfo);
182         if (fo != null) {
183             return getOpenInfo(fo, ElementHandle.create(el));
184         } else {
185             return null;
186         }
187     }
188     
189     static Object JavaDoc[] getOpenInfo(final FileObject fo, final ElementHandle<? extends Element> handle) {
190         assert fo != null;
191         
192         try {
193             int offset = getOffset(fo, handle);
194             return new Object JavaDoc[] {fo, offset};
195         } catch (IOException JavaDoc e) {
196             ErrorManager.getDefault().notify(e);
197             return null;
198         }
199     }
200     
201     /** Computes dostance between strings
202      */

203     public static int getDistance(String JavaDoc s, String JavaDoc t) {
204         int d[][]; // matrix
205
int n; // length of s
206
int m; // length of t
207
int i; // iterates through s
208
int j; // iterates through t
209
char s_i; // ith character of s
210
char t_j; // jth character of t
211
int cost; // cost
212

213         // Step 1
214

215         n = s.length ();
216         m = t.length ();
217         if (n == 0) {
218           return m;
219         }
220         if (m == 0) {
221           return n;
222         }
223         d = new int[n+1][m+1];
224
225         // Step 2
226

227         for (i = 0; i <= n; i++) {
228           d[i][0] = i;
229         }
230
231         for (j = 0; j <= m; j++) {
232           d[0][j] = j;
233         }
234
235         // Step 3
236

237         for (i = 1; i <= n; i++) {
238
239           s_i = s.charAt (i - 1);
240
241           // Step 4
242

243           for (j = 1; j <= m; j++) {
244
245             t_j = t.charAt (j - 1);
246
247             // Step 5
248

249             if (s_i == t_j) {
250               cost = 0;
251             }
252             else {
253               cost = 1;
254             }
255
256             // Step 6
257
d[i][j] = min (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);
258
259           }
260
261         }
262
263         // Step 7
264

265         return d[n][m];
266     }
267   
268     private static int min (int a, int b, int c) {
269         int mi;
270                
271         mi = a;
272         if (b < mi) {
273           mi = b;
274         }
275         if (c < mi) {
276           mi = c;
277         }
278         return mi;
279
280    }
281     
282     // Private methods ---------------------------------------------------------
283

284     private static boolean doOpen(FileObject fo, int offset) {
285         try {
286             DataObject od = DataObject.find(fo);
287             EditorCookie ec = (EditorCookie) od.getCookie(EditorCookie.class);
288             LineCookie lc = (LineCookie) od.getCookie(LineCookie.class);
289             
290             if (ec != null && lc != null && offset != -1) {
291                 StyledDocument JavaDoc doc = ec.openDocument();
292                 if (doc != null) {
293                     int line = NbDocument.findLineNumber(doc, offset);
294                     int lineOffset = NbDocument.findLineOffset(doc, line);
295                     int column = offset - lineOffset;
296                     
297                     if (line != -1) {
298                         Line l = lc.getLineSet().getCurrent(line);
299                         
300                         if (l != null) {
301                             l.show(Line.SHOW_GOTO, column);
302                             return true;
303                         }
304                     }
305                 }
306             }
307             
308             OpenCookie oc = (OpenCookie) od.getCookie(OpenCookie.class);
309             
310             if (oc != null) {
311                 oc.open();
312                 return true;
313             }
314         } catch (IOException JavaDoc e) {
315             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
316         }
317         
318         return false;
319     }
320     
321     private static int getOffset(FileObject fo, final ElementHandle<? extends Element> handle) throws IOException JavaDoc {
322         final int[] result = new int[] {-1};
323         
324         
325         JavaSource js = JavaSource.forFileObject(fo);
326         js.runUserActionTask(new CancellableTask<CompilationController>() {
327             
328             public void cancel() {
329             }
330             
331             public void run(CompilationController info) {
332                 try {
333                     info.toPhase(JavaSource.Phase.RESOLVED);
334                 } catch (IOException JavaDoc ioe) {
335                     ErrorManager.getDefault().notify(ioe);
336                 }
337                 Element el = handle.resolve(info);
338                 if (el == null)
339                     throw new IllegalArgumentException JavaDoc();
340                 
341                 FindDeclarationVisitor v = new FindDeclarationVisitor(el, info);
342                 
343                 CompilationUnitTree cu = info.getCompilationUnit();
344
345                 v.scan(cu, null);
346                 Tree elTree = v.declTree;
347                 
348                 if (elTree != null)
349                     result[0] = (int)info.getTrees().getSourcePositions().getStartPosition(cu, elTree);
350             }
351         },true);
352         return result[0];
353     }
354     
355     // Private innerclasses ----------------------------------------------------
356

357     private static class FindDeclarationVisitor extends TreePathScanner<Void JavaDoc, Void JavaDoc> {
358         
359         private Element element;
360         private Tree declTree;
361         private CompilationInfo info;
362         
363         public FindDeclarationVisitor(Element element, CompilationInfo info) {
364             this.element = element;
365             this.info = info;
366         }
367         
368     @Override JavaDoc
369         public Void JavaDoc visitClass(ClassTree tree, Void JavaDoc d) {
370             handleDeclaration();
371             super.visitClass(tree, d);
372             return null;
373         }
374         
375     @Override JavaDoc
376         public Void JavaDoc visitMethod(MethodTree tree, Void JavaDoc d) {
377             handleDeclaration();
378             super.visitMethod(tree, d);
379             return null;
380         }
381         
382     @Override JavaDoc
383         public Void JavaDoc visitVariable(VariableTree tree, Void JavaDoc d) {
384             handleDeclaration();
385             super.visitVariable(tree, d);
386             return null;
387         }
388     
389         public void handleDeclaration() {
390             Element found = info.getTrees().getElement(getCurrentPath());
391             
392             if ( element.equals( found ) ) {
393                 declTree = getCurrentPath().getLeaf();
394             }
395         }
396     
397     }
398     
399         //JL: will anybody need this?:
400
// public static Action createOpenAction(FileObject context, Declaration el) {
401
// return new OpenAction(context, el);
402
// }
403
//
404
// private static final class OpenAction extends AbstractAction {
405
//
406
// private FileObject context;
407
// private Declaration el;
408
//
409
// public OpenAction(FileObject context, Declaration el) {
410
// this.context = context;
411
// this.el = el;
412
//
413
// putValue(NAME, getDisplayName(el));
414
// }
415
//
416
// public void actionPerformed(ActionEvent e) {
417
// open(context, el);
418
// }
419
//
420
// }
421

422     
423     
424 }
425
Popular Tags