KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > editor > contentassist > TypePackageCompletionProcessor


1 /*******************************************************************************
2  * Copyright (c) 2006, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.pde.internal.ui.editor.contentassist;
12
13 import java.util.Arrays JavaDoc;
14 import java.util.Collection JavaDoc;
15 import java.util.Comparator JavaDoc;
16
17 import org.eclipse.core.resources.IProject;
18 import org.eclipse.core.runtime.CoreException;
19 import org.eclipse.core.runtime.NullProgressMonitor;
20 import org.eclipse.jdt.core.CompletionProposal;
21 import org.eclipse.jdt.core.CompletionRequestor;
22 import org.eclipse.jdt.core.Flags;
23 import org.eclipse.jdt.core.IBuffer;
24 import org.eclipse.jdt.core.ICompilationUnit;
25 import org.eclipse.jdt.core.IJavaElement;
26 import org.eclipse.jdt.core.IPackageFragment;
27 import org.eclipse.jdt.core.IPackageFragmentRoot;
28 import org.eclipse.jdt.core.JavaCore;
29 import org.eclipse.jdt.core.JavaModelException;
30 import org.eclipse.jdt.core.search.IJavaSearchConstants;
31 import org.eclipse.jdt.core.search.IJavaSearchScope;
32 import org.eclipse.jdt.core.search.SearchEngine;
33 import org.eclipse.jdt.core.search.SearchPattern;
34 import org.eclipse.jdt.core.search.TypeNameRequestor;
35 import org.eclipse.jface.text.ITextViewer;
36 import org.eclipse.jface.text.contentassist.ICompletionProposal;
37 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
38 import org.eclipse.jface.text.contentassist.IContextInformation;
39 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
40 import org.eclipse.pde.internal.core.util.PDEJavaHelper;
41 import org.eclipse.pde.internal.ui.PDEPluginImages;
42 import org.eclipse.swt.graphics.Image;
43
44 public abstract class TypePackageCompletionProcessor implements IContentAssistProcessor {
45     
46     private String JavaDoc fErrorMessage;
47     private SearchEngine fSearchEngine;
48     private Comparator JavaDoc fComparator;
49     
50     abstract class ProposalGenerator {
51         abstract protected ICompletionProposal generateClassCompletion(String JavaDoc pName, String JavaDoc cName, boolean isClass);
52         abstract protected ICompletionProposal generatePackageCompletion(String JavaDoc pName);
53     }
54     
55     public TypePackageCompletionProcessor() {
56         fSearchEngine = new SearchEngine();
57     }
58
59     public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
60         return null;
61     }
62
63     public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
64         return null;
65     }
66
67     public char[] getCompletionProposalAutoActivationCharacters() {
68         return null;
69     }
70
71     public char[] getContextInformationAutoActivationCharacters() {
72         return null;
73     }
74
75     public IContextInformationValidator getContextInformationValidator() {
76         return null;
77     }
78
79     public String JavaDoc getErrorMessage() {
80         return fErrorMessage;
81     }
82     
83     protected void generateTypePackageProposals(String JavaDoc currentContent, IProject project, Collection JavaDoc c,
84             int startOffset, int typeScope) {
85         generateTypePackageProposals(currentContent, project, c, startOffset, typeScope, false);
86     }
87     
88     protected void generateTypePackageProposals(String JavaDoc currentContent, IProject project, Collection JavaDoc c,
89             int startOffset, int typeScope, boolean replaceEntireContents) {
90         currentContent = removeLeadingSpaces(currentContent);
91         if (c == null || currentContent.length() == 0)
92             return;
93         int length = (replaceEntireContents) ? -1 : currentContent.length();
94         generateProposals(currentContent, project, c, startOffset, length, typeScope);
95     }
96     
97     private void generateProposals(String JavaDoc currentContent, IProject project, final Collection JavaDoc c,
98             final int startOffset, final int length, final int typeScope) {
99         try {
100             ICompilationUnit unit = getWorkingCopy(project);
101             if (unit == null) {
102                 generateTypeProposals(currentContent, project, c, startOffset, length, 1);
103                 return;
104             }
105             IBuffer buff = unit.getBuffer();
106             buff.setContents("class Dummy2 { " + currentContent); //$NON-NLS-1$
107
CompletionRequestor req = new CompletionRequestor() {
108
109                 public void accept(CompletionProposal proposal) {
110                     if (proposal.getKind() == CompletionProposal.PACKAGE_REF) {
111                         String JavaDoc pkgName = new String JavaDoc(proposal.getCompletion());
112                         addProposalToCollection(c, startOffset, length, pkgName,
113                                 pkgName, PDEPluginImages.get(PDEPluginImages.OBJ_DESC_PACKAGE));
114                     } else {
115                         boolean isInterface = Flags.isInterface(proposal.getFlags());
116                         String JavaDoc completion = new String JavaDoc(proposal.getCompletion());
117                         if (isInterface && typeScope == IJavaSearchConstants.CLASS ||
118                                 completion.equals("Dummy2")) //$NON-NLS-1$
119
// don't want Dummy class showing up as option.
120
return;
121                         int period = completion.lastIndexOf('.');
122                         String JavaDoc cName = null, pName = null;
123                         if (period == -1) {
124                             cName = completion;
125                         } else {
126                             cName = completion.substring(period + 1 );
127                             pName = completion.substring(0, period);
128                         }
129                         Image image = isInterface ? PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_INTERFACE) :
130                             PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS);
131                         addProposalToCollection(c, startOffset, length, cName + " - " + pName, //$NON-NLS-1$
132
completion, image);
133                     }
134                 }
135
136             };
137             for (int i = 1; i <= 20; i++)
138                 if (i != CompletionProposal.PACKAGE_REF && i != CompletionProposal.TYPE_REF) // ignore everything but class and package references
139
req.setIgnored(i, true);
140             unit.codeComplete(15 + currentContent.length(), req);
141             unit.discardWorkingCopy();
142         } catch (JavaModelException e) {
143         }
144     }
145     
146     private ICompilationUnit getWorkingCopy(IProject project) throws JavaModelException {
147         IPackageFragmentRoot[] roots = JavaCore.create(project).getPackageFragmentRoots();
148         if (roots.length > 0) {
149             IPackageFragment frag = null;
150             for (int i = 0; i < roots.length; i++)
151                 if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE
152                         || project.equals(roots[i].getCorrespondingResource())
153                         || (roots[i].isArchive() && !roots[i].isExternal())) {
154                     IJavaElement[] elems = roots[i].getChildren();
155                     if (elems.length > 0 && elems[i] instanceof IPackageFragment) {
156                         frag = (IPackageFragment)elems[i];
157                         break;
158                     }
159                 }
160             if (frag != null)
161                 return frag.getCompilationUnit("Dummy2.java").getWorkingCopy(new NullProgressMonitor()); //$NON-NLS-1$
162
}
163         return null;
164     }
165     
166     protected void generateTypeProposals(String JavaDoc currentContent, IProject project, final Collection JavaDoc c,
167             final int startOffset, final int length, int typeScope) {
168         // Dynamically adjust the search scope depending on the current
169
// state of the project
170
IJavaSearchScope scope = PDEJavaHelper.getSearchScope(project);
171         char[] packageName = null;
172         char[] typeName = null;
173         int index = currentContent.lastIndexOf('.');
174         
175         if (index == -1) {
176             // There is no package qualification
177
// Perform the search only on the type name
178
typeName = currentContent.toCharArray();
179         } else if ((index + 1) == currentContent.length()) {
180             // There is a package qualification and the last character is a
181
// dot
182
// Perform the search for all types under the given package
183
// Pattern for all types
184
typeName = "".toCharArray(); //$NON-NLS-1$
185
// Package name without the trailing dot
186
packageName = currentContent.substring(0, index).toCharArray();
187         } else {
188             // There is a package qualification, followed by a dot, and
189
// a type fragment
190
// Type name without the package qualification
191
typeName = currentContent.substring(index + 1).toCharArray();
192             // Package name without the trailing dot
193
packageName = currentContent.substring(0, index).toCharArray();
194         }
195         
196         try {
197             TypeNameRequestor req = new TypeNameRequestor() {
198                 public void acceptType(int modifiers, char[] packageName,
199                         char[] simpleTypeName, char[][] enclosingTypeNames, String JavaDoc path) {
200                     // Accept search results from the JDT SearchEngine
201
String JavaDoc cName = new String JavaDoc(simpleTypeName);
202                     String JavaDoc pName = new String JavaDoc(packageName);
203                     String JavaDoc label = cName + " - " + pName; //$NON-NLS-1$
204
String JavaDoc content = pName + "." + cName; //$NON-NLS-1$
205
Image image = (Flags.isInterface(modifiers)) ? PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS) :
206                         PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS);
207                     addProposalToCollection(c, startOffset, length, label,
208                             content, image);
209                 }
210             };
211             // Note: Do not use the search() method, its performance is
212
// bad compared to the searchAllTypeNames() method
213
fSearchEngine.searchAllTypeNames(
214                     packageName,
215                     SearchPattern.R_EXACT_MATCH,
216                     typeName,
217                     SearchPattern.R_PREFIX_MATCH,
218                     typeScope,
219                     scope,
220                     req,
221                     IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
222                     null);
223         } catch (CoreException e) {
224             fErrorMessage = e.getMessage();
225         }
226     }
227
228     public void sortCompletions(ICompletionProposal[] proposals) {
229         Arrays.sort(proposals, getComparator());
230     }
231     
232     private Comparator JavaDoc getComparator() {
233         if (fComparator == null) {
234             fComparator = new Comparator JavaDoc() {
235                 /* (non-Javadoc)
236                  * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
237                  */

238                 public int compare(Object JavaDoc arg0, Object JavaDoc arg1) {
239                     ICompletionProposal p1 = (ICompletionProposal) arg0;
240                     ICompletionProposal p2 = (ICompletionProposal) arg1;
241
242                     return getSortKey(p1).compareToIgnoreCase(getSortKey(p2));
243                 }
244
245                 protected String JavaDoc getSortKey(ICompletionProposal p) {
246                     return p.getDisplayString();
247                 }
248             };
249         }
250         return fComparator;
251     }
252     
253     protected final String JavaDoc removeLeadingSpaces(String JavaDoc value) {
254         char[] valueArray = value.toCharArray();
255         int i = 0;
256         for (; i < valueArray.length; i++)
257             if (!Character.isWhitespace(valueArray[i]))
258                 break;
259         return (i == valueArray.length) ? "" : new String JavaDoc(valueArray, i, valueArray.length - i); //$NON-NLS-1$
260
}
261
262     /**
263      * @param c
264      * @param startOffset
265      * @param length
266      * @param label
267      * @param content
268      * @param image
269      */

270     protected void addProposalToCollection(final Collection JavaDoc c,
271             final int startOffset, final int length, String JavaDoc label,
272             String JavaDoc content, Image image) {
273         TypeCompletionProposal proposal = new TypeCompletionProposal(content, image, label,
274                 startOffset, length);
275         c.add(proposal);
276     }
277
278 }
279
Popular Tags