KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > text > correction > QuickTemplateProcessor


1 /*******************************************************************************
2  * Copyright (c) 2000, 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.jdt.internal.ui.text.correction;
12
13 import com.ibm.icu.text.Collator;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Collection JavaDoc;
17 import java.util.Collections JavaDoc;
18 import java.util.Comparator JavaDoc;
19
20 import org.eclipse.core.runtime.CoreException;
21 import org.eclipse.core.runtime.IStatus;
22
23 import org.eclipse.core.resources.IFile;
24
25 import org.eclipse.swt.graphics.Image;
26
27 import org.eclipse.jface.text.BadLocationException;
28 import org.eclipse.jface.text.Document;
29 import org.eclipse.jface.text.DocumentEvent;
30 import org.eclipse.jface.text.IDocument;
31 import org.eclipse.jface.text.IRegion;
32 import org.eclipse.jface.text.Region;
33 import org.eclipse.jface.text.templates.GlobalTemplateVariables;
34 import org.eclipse.jface.text.templates.Template;
35
36 import org.eclipse.ui.part.FileEditorInput;
37
38 import org.eclipse.jdt.core.ICompilationUnit;
39 import org.eclipse.jdt.core.JavaModelException;
40 import org.eclipse.jdt.core.dom.Statement;
41
42 import org.eclipse.jdt.internal.corext.template.java.CompilationUnitContext;
43 import org.eclipse.jdt.internal.corext.template.java.CompilationUnitContextType;
44 import org.eclipse.jdt.internal.corext.template.java.JavaContextType;
45 import org.eclipse.jdt.internal.corext.util.Messages;
46
47 import org.eclipse.jdt.ui.JavaUI;
48 import org.eclipse.jdt.ui.text.java.IInvocationContext;
49 import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
50 import org.eclipse.jdt.ui.text.java.IProblemLocation;
51 import org.eclipse.jdt.ui.text.java.IQuickAssistProcessor;
52
53 import org.eclipse.jdt.internal.ui.JavaPlugin;
54 import org.eclipse.jdt.internal.ui.JavaPluginImages;
55 import org.eclipse.jdt.internal.ui.JavaUIStatus;
56 import org.eclipse.jdt.internal.ui.text.template.contentassist.SurroundWithTemplateProposal;
57 import org.eclipse.jdt.internal.ui.text.template.contentassist.TemplateProposal;
58
59
60 /**
61  * Quick template processor.
62  */

63 public class QuickTemplateProcessor implements IQuickAssistProcessor {
64
65     private static final String JavaDoc $_LINE_SELECTION= "${" + GlobalTemplateVariables.LineSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$
66

67     public QuickTemplateProcessor() {
68     }
69
70     /* (non-Javadoc)
71      * @see org.eclipse.jdt.internal.ui.text.correction.IAssistProcessor#hasAssists(org.eclipse.jdt.internal.ui.text.correction.IAssistContext)
72      */

73     public boolean hasAssists(IInvocationContext context) throws CoreException {
74         ICompilationUnit cu= context.getCompilationUnit();
75         IDocument document= getDocument(cu);
76
77         int offset= context.getSelectionOffset();
78         int length= context.getSelectionLength();
79         if (length == 0) {
80             return false;
81         }
82
83         try {
84             int startLine= document.getLineOfOffset(offset);
85             int endLine= document.getLineOfOffset(offset + length);
86             IRegion region= document.getLineInformation(endLine);
87             return startLine < endLine || length > 0 && offset == region.getOffset() && length == region.getLength();
88         } catch (BadLocationException e) {
89             return false;
90         }
91     }
92
93     /* (non-Javadoc)
94      * @see org.eclipse.jdt.internal.ui.text.correction.IAssistProcessor#getAssists(org.eclipse.jdt.internal.ui.text.correction.IAssistContext, org.eclipse.jdt.internal.ui.text.correction.IProblemLocation[])
95      */

96     public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
97         if (locations != null && locations.length > 0) {
98             return new IJavaCompletionProposal[0];
99         }
100
101         try {
102             int offset= context.getSelectionOffset();
103             int length= context.getSelectionLength();
104             if (length == 0) {
105                 return null;
106             }
107
108             ICompilationUnit cu= context.getCompilationUnit();
109             IDocument document= getDocument(cu);
110
111             // test if selection is either a full line or spans over multiple lines
112
int startLine= document.getLineOfOffset(offset);
113             int endLine= document.getLineOfOffset(offset + length);
114             IRegion endLineRegion= document.getLineInformation(endLine);
115             //if end position is at start of line, set it back to the previous line's end
116
if (endLine > startLine && endLineRegion.getOffset() == offset + length) {
117                 endLine--;
118                 endLineRegion= document.getLineInformation(endLine);
119                 length= endLineRegion.getOffset() + endLineRegion.getLength() - offset;
120             }
121             if (startLine == endLine) {
122                 if (length == 0 || offset != endLineRegion.getOffset() || length != endLineRegion.getLength()) {
123                     AssistContext invocationContext= new AssistContext(cu, offset, length);
124                     if (!SurroundWith.isApplicable(invocationContext))
125                         return null;
126                 }
127             } else {
128                 // expand selection
129
offset= document.getLineOffset(startLine);
130                 length= endLineRegion.getOffset() + endLineRegion.getLength() - offset;
131             }
132
133             ArrayList JavaDoc resultingCollections= new ArrayList JavaDoc();
134             collectSurroundTemplates(document, cu, offset, length, resultingCollections);
135             sort(resultingCollections);
136             return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
137         } catch (BadLocationException e) {
138             throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, "", e)); //$NON-NLS-1$
139
}
140     }
141
142     private void sort(ArrayList JavaDoc proposals) {
143         Collections.sort(proposals, new Comparator JavaDoc() {
144             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
145                 IJavaCompletionProposal p1= (IJavaCompletionProposal)o1;
146                 IJavaCompletionProposal p2= (IJavaCompletionProposal)o2;
147                 return Collator.getInstance().compare(p1.getDisplayString(), p2.getDisplayString());
148             }
149         });
150     }
151
152     private IDocument getDocument(ICompilationUnit cu) throws JavaModelException {
153         IFile file= (IFile) cu.getResource();
154         IDocument document= JavaUI.getDocumentProvider().getDocument(new FileEditorInput(file));
155         if (document == null) {
156             return new Document(cu.getSource()); // only used by test cases
157
}
158         return document;
159     }
160
161     private void collectSurroundTemplates(IDocument document, ICompilationUnit cu, int offset, int length, Collection JavaDoc result) throws BadLocationException, CoreException {
162         CompilationUnitContextType contextType= (CompilationUnitContextType) JavaPlugin.getDefault().getTemplateContextRegistry().getContextType(JavaContextType.NAME);
163         CompilationUnitContext context= contextType.createContext(document, offset, length, cu);
164         context.setVariable("selection", document.get(offset, length)); //$NON-NLS-1$
165
context.setForceEvaluation(true);
166
167         int start= context.getStart();
168         int end= context.getEnd();
169         IRegion region= new Region(start, end - start);
170
171         AssistContext invocationContext= new AssistContext(cu, start, end - start);
172         Statement[] selectedStatements= SurroundWith.getSelectedStatements(invocationContext);
173         
174         Template[] templates= JavaPlugin.getDefault().getTemplateStore().getTemplates();
175         for (int i= 0; i != templates.length; i++) {
176             Template currentTemplate= templates[i];
177             if (context.canEvaluate(currentTemplate) && currentTemplate.getContextTypeId().equals(JavaContextType.NAME) && currentTemplate.getPattern().indexOf($_LINE_SELECTION) != -1) {
178                 // TODO using jdt proposals for the moment, as jdt expects IJavaCompletionProposals
179

180                 if (selectedStatements != null) {
181                     Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
182                     TemplateProposal proposal= new SurroundWithTemplateProposal(cu, currentTemplate, context, region, image, selectedStatements);
183                     String JavaDoc[] arg= new String JavaDoc[] { currentTemplate.getName(), currentTemplate.getDescription() };
184                     proposal.setDisplayString(Messages.format(CorrectionMessages.QuickTemplateProcessor_surround_label, arg));
185                     result.add(proposal);
186                 } else {
187                     TemplateProposal proposal= new TemplateProposal(currentTemplate, context, region, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE)) {
188                         /**
189                          * {@inheritDoc}
190                          */

191                         public boolean validate(IDocument doc, int off, DocumentEvent event) {
192                             return false;
193                         }
194                     };
195                     String JavaDoc[] arg= new String JavaDoc[] { currentTemplate.getName(), currentTemplate.getDescription() };
196                     proposal.setDisplayString(Messages.format(CorrectionMessages.QuickTemplateProcessor_surround_label, arg));
197                     result.add(proposal);
198                 }
199             }
200         }
201     }
202
203 }
204
Popular Tags