KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > compare > JavaHistoryActionImpl


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.compare;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14 import java.util.Map JavaDoc;
15
16 import org.eclipse.text.edits.MultiTextEdit;
17 import org.eclipse.text.edits.TextEdit;
18
19 import org.eclipse.core.runtime.CoreException;
20 import org.eclipse.core.runtime.IProgressMonitor;
21 import org.eclipse.core.runtime.NullProgressMonitor;
22
23 import org.eclipse.core.filebuffers.ITextFileBuffer;
24
25 import org.eclipse.core.resources.IFile;
26 import org.eclipse.core.resources.IFileState;
27
28 import org.eclipse.swt.widgets.Shell;
29
30 import org.eclipse.jface.action.IAction;
31 import org.eclipse.jface.dialogs.MessageDialog;
32 import org.eclipse.jface.operation.IRunnableWithProgress;
33 import org.eclipse.jface.viewers.ISelection;
34 import org.eclipse.jface.viewers.IStructuredSelection;
35 import org.eclipse.jface.viewers.StructuredSelection;
36
37 import org.eclipse.jface.text.BadLocationException;
38 import org.eclipse.jface.text.IDocument;
39 import org.eclipse.jface.text.RewriteSessionEditProcessor;
40
41 import org.eclipse.ui.IEditorPart;
42 import org.eclipse.ui.IWorkbench;
43 import org.eclipse.ui.IWorkbenchPage;
44 import org.eclipse.ui.IWorkbenchWindow;
45 import org.eclipse.ui.PlatformUI;
46 import org.eclipse.ui.part.FileEditorInput;
47 import org.eclipse.ui.texteditor.IDocumentProvider;
48
49 import org.eclipse.compare.HistoryItem;
50 import org.eclipse.compare.ITypedElement;
51 import org.eclipse.compare.ResourceNode;
52
53 import org.eclipse.jdt.core.ICompilationUnit;
54 import org.eclipse.jdt.core.IJavaElement;
55 import org.eclipse.jdt.core.IJavaProject;
56 import org.eclipse.jdt.core.IMember;
57 import org.eclipse.jdt.core.ISourceRange;
58 import org.eclipse.jdt.core.JavaModelException;
59 import org.eclipse.jdt.core.dom.AST;
60 import org.eclipse.jdt.core.dom.ASTNode;
61 import org.eclipse.jdt.core.dom.ASTParser;
62 import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration;
63 import org.eclipse.jdt.core.dom.CompilationUnit;
64 import org.eclipse.jdt.core.dom.EnumDeclaration;
65 import org.eclipse.jdt.core.dom.TypeDeclaration;
66 import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
67
68 import org.eclipse.jdt.internal.corext.dom.NodeFinder;
69 import org.eclipse.jdt.internal.corext.util.Strings;
70
71 import org.eclipse.jdt.internal.ui.JavaPlugin;
72 import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
73 import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
74
75 /**
76  * Base class for the "Replace with local history"
77  * and "Add from local history" actions.
78  */

79 abstract class JavaHistoryActionImpl /* extends Action implements IActionDelegate*/ {
80     
81     private boolean fModifiesFile;
82     private ISelection fSelection;
83
84     JavaHistoryActionImpl(boolean modifiesFile) {
85         fModifiesFile= modifiesFile;
86     }
87     
88     ISelection getSelection() {
89         return fSelection;
90     }
91         
92     final IFile getFile(Object JavaDoc input) {
93         return JavaElementHistoryPageSource.getInstance().getFile(input);
94     }
95     
96     final ITypedElement[] buildEditions(ITypedElement target, IFile file) {
97
98         // setup array of editions
99
IFileState[] states= null;
100         // add available editions
101
try {
102             states= file.getHistory(null);
103         } catch (CoreException ex) {
104             JavaPlugin.log(ex);
105         }
106         
107         int count= 1;
108         if (states != null)
109             count+= states.length;
110
111         ITypedElement[] editions= new ITypedElement[count];
112         editions[0]= new ResourceNode(file);
113         if (states != null)
114             for (int i= 0; i < states.length; i++)
115                 editions[i+1]= new HistoryItem(target, states[i]);
116         return editions;
117     }
118     
119     final Shell getShell() {
120         if (fEditor != null)
121             return fEditor.getEditorSite().getShell();
122         return JavaPlugin.getActiveWorkbenchShell();
123     }
124     
125     /**
126      * Tries to find the given element in a working copy.
127      */

128     final IJavaElement getWorkingCopy(IJavaElement input) {
129         // TODO: With new working copy story: original == working copy.
130
// Note that the previous code could result in a reconcile as side effect. Should check if that
131
// is still required.
132
return input;
133     }
134     
135     final ASTNode getBodyContainer(CompilationUnit root, IMember parent) throws JavaModelException {
136         ISourceRange sourceRange= parent.getNameRange();
137         ASTNode parentNode= NodeFinder.perform(root, sourceRange);
138         do {
139             if (parentNode instanceof TypeDeclaration || parentNode instanceof EnumDeclaration || parentNode instanceof AnnotationTypeDeclaration)
140                 return parentNode;
141             parentNode= parentNode.getParent();
142         } while (parentNode != null);
143         return null;
144     }
145     
146     /**
147      * Returns true if the given file is open in an editor.
148      */

149     final boolean beingEdited(IFile file) {
150         IDocumentProvider dp= JavaPlugin.getDefault().getCompilationUnitDocumentProvider();
151         FileEditorInput input= new FileEditorInput(file);
152         return dp.getDocument(input) != null;
153     }
154
155     /**
156      * Returns an IMember or null.
157      */

158     final IMember getEditionElement(ISelection selection) {
159         
160         if (selection instanceof IStructuredSelection) {
161             IStructuredSelection ss= (IStructuredSelection) selection;
162             if (ss.size() == 1) {
163                 Object JavaDoc o= ss.getFirstElement();
164                 if (o instanceof IMember) {
165                     IMember m= (IMember) o;
166                     if (m.exists() && !m.isBinary() && JavaStructureCreator.hasEdition(m))
167                         return m;
168                 }
169             }
170         }
171         return null;
172     }
173     
174     final boolean isEnabled(IFile file) {
175         if (file == null || ! file.exists())
176             return false;
177         if (fModifiesFile) {
178             // without validate/edit we would do this:
179
// return !file.isReadOnly();
180
// with validate/edit we have to return true
181
return true;
182         }
183         return true;
184     }
185     
186     boolean isEnabled(ISelection selection) {
187         IMember m= getEditionElement(selection);
188         if (m == null)
189             return false;
190         IFile file= getFile(m);
191         if (!isEnabled(file))
192             return false;
193         return true;
194     }
195     
196     void applyChanges(ASTRewrite rewriter, final IDocument document, final ITextFileBuffer textFileBuffer, Shell shell, boolean inEditor, Map JavaDoc options)
197                             throws CoreException, InvocationTargetException JavaDoc, InterruptedException JavaDoc {
198
199         
200         MultiTextEdit edit= new MultiTextEdit();
201         try {
202             TextEdit res= rewriter.rewriteAST(document, options);
203             edit.addChildren(res.removeChildren());
204         } catch (IllegalArgumentException JavaDoc e) {
205             JavaPlugin.log(e);
206         }
207             
208         try {
209             new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits();
210         } catch (BadLocationException e) {
211             JavaPlugin.log(e);
212         }
213         
214         IRunnableWithProgress r= new IRunnableWithProgress() {
215             public void run(IProgressMonitor pm) throws InvocationTargetException JavaDoc {
216                 try {
217                     textFileBuffer.commit(pm, false);
218                 } catch (CoreException ex) {
219                     throw new InvocationTargetException JavaDoc(ex);
220                 }
221             }
222         };
223
224         if (inEditor) {
225             // we don't show progress
226
r.run(new NullProgressMonitor());
227         } else {
228             PlatformUI.getWorkbench().getProgressService().run(true, false, r);
229         }
230     }
231
232     static String JavaDoc trimTextBlock(String JavaDoc content, String JavaDoc delimiter, IJavaProject currentProject) {
233         if (content != null) {
234             String JavaDoc[] lines= Strings.convertIntoLines(content);
235             if (lines != null) {
236                 Strings.trimIndentation(lines, currentProject);
237                 return Strings.concatenate(lines, delimiter);
238             }
239         }
240         return null;
241     }
242     
243     final JavaEditor getEditor(IFile file) {
244         FileEditorInput fei= new FileEditorInput(file);
245         IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
246         IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
247         for (int i= 0; i < windows.length; i++) {
248             IWorkbenchPage[] pages= windows[i].getPages();
249             for (int x= 0; x < pages.length; x++) {
250                 IEditorPart[] editors= pages[x].getDirtyEditors();
251                 for (int z= 0; z < editors.length; z++) {
252                     IEditorPart ep= editors[z];
253                     if (ep instanceof JavaEditor) {
254                         JavaEditor je= (JavaEditor) ep;
255                         if (fei.equals(je.getEditorInput()))
256                             return (JavaEditor) ep;
257                     }
258                 }
259             }
260         }
261         return null;
262     }
263
264     /**
265      * Executes this action with the given selection.
266      */

267     public abstract void run(ISelection selection);
268
269     //---- Action
270

271     private JavaEditor fEditor;
272     private String JavaDoc fTitle;
273     private String JavaDoc fMessage;
274
275     void init(JavaEditor editor, String JavaDoc title, String JavaDoc message) {
276         fEditor= editor;
277         fTitle= title;
278         fMessage= message;
279     }
280     
281     final JavaEditor getEditor() {
282         return fEditor;
283     }
284
285     final public void runFromEditor(IAction uiProxy) {
286         
287         // this run is called from Editor
288
IJavaElement element= null;
289         try {
290             element= SelectionConverter.getElementAtOffset(fEditor);
291         } catch (JavaModelException e) {
292             // ignored
293
}
294         
295         fSelection= element != null
296                         ? new StructuredSelection(element)
297                         : StructuredSelection.EMPTY;
298         boolean isEnabled= isEnabled(fSelection);
299         uiProxy.setEnabled(isEnabled);
300         
301         if (!isEnabled) {
302             MessageDialog.openInformation(getShell(), fTitle, fMessage);
303             return;
304         }
305         run(fSelection);
306     }
307
308     boolean checkEnabled() {
309         ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(fEditor);
310         IFile file= getFile(unit);
311         return isEnabled(file);
312     }
313
314     final public void update(IAction uiProxy) {
315         uiProxy.setEnabled(checkEnabled());
316     }
317     
318     //---- IActionDelegate
319

320     final public void selectionChanged(IAction uiProxy, ISelection selection) {
321         fSelection= selection;
322         uiProxy.setEnabled(isEnabled(selection));
323     }
324     
325     final public void run(IAction action) {
326         run(fSelection);
327     }
328     
329     static CompilationUnit parsePartialCompilationUnit(ICompilationUnit unit) {
330                 
331         if (unit == null) {
332             throw new IllegalArgumentException JavaDoc();
333         }
334         try {
335             ASTParser c= ASTParser.newParser(AST.JLS3);
336             c.setSource(unit);
337             c.setFocalPosition(0);
338             c.setResolveBindings(false);
339             c.setWorkingCopyOwner(null);
340             ASTNode result= c.createAST(null);
341             return (CompilationUnit) result;
342         } catch (IllegalStateException JavaDoc e) {
343             // convert ASTParser's complaints into old form
344
throw new IllegalArgumentException JavaDoc();
345         }
346     }
347 }
348
Popular Tags