KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > javaeditor > AddImportOnSelectionAction


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 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
12 package org.eclipse.jdt.internal.ui.javaeditor;
13
14
15 import com.ibm.icu.text.Collator;
16
17 import java.lang.reflect.InvocationTargetException JavaDoc;
18 import java.util.Comparator JavaDoc;
19
20 import org.eclipse.core.runtime.IStatus;
21 import org.eclipse.core.runtime.jobs.ISchedulingRule;
22
23 import org.eclipse.core.resources.ResourcesPlugin;
24
25 import org.eclipse.swt.widgets.Composite;
26 import org.eclipse.swt.widgets.Shell;
27
28 import org.eclipse.jface.action.Action;
29 import org.eclipse.jface.action.IStatusLineManager;
30 import org.eclipse.jface.viewers.ISelection;
31 import org.eclipse.jface.window.Window;
32
33 import org.eclipse.jface.text.DocumentEvent;
34 import org.eclipse.jface.text.IEditingSupport;
35 import org.eclipse.jface.text.IEditingSupportRegistry;
36 import org.eclipse.jface.text.IRegion;
37 import org.eclipse.jface.text.ITextSelection;
38 import org.eclipse.jface.text.source.ISourceViewer;
39
40 import org.eclipse.ui.PlatformUI;
41 import org.eclipse.ui.dialogs.ElementListSelectionDialog;
42 import org.eclipse.ui.dialogs.FilteredList;
43 import org.eclipse.ui.progress.IProgressService;
44 import org.eclipse.ui.texteditor.IUpdate;
45
46 import org.eclipse.jdt.core.ICompilationUnit;
47 import org.eclipse.jdt.core.search.TypeNameMatch;
48
49 import org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation;
50 import org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation.IChooseImportQuery;
51 import org.eclipse.jdt.internal.corext.util.History;
52 import org.eclipse.jdt.internal.corext.util.QualifiedTypeNameHistory;
53
54 import org.eclipse.jdt.ui.IWorkingCopyManager;
55
56 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
57 import org.eclipse.jdt.internal.ui.JavaPlugin;
58 import org.eclipse.jdt.internal.ui.actions.ActionUtil;
59 import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
60 import org.eclipse.jdt.internal.ui.util.ElementValidator;
61 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
62 import org.eclipse.jdt.internal.ui.util.TypeNameMatchLabelProvider;
63
64
65 public class AddImportOnSelectionAction extends Action implements IUpdate {
66     
67     private static final AddImportComparator ADD_IMPORT_COMPARATOR= new AddImportComparator();
68     
69     private static final class AddImportComparator implements Comparator JavaDoc {
70         
71         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
72             if (((String JavaDoc)o1).equals(o2))
73                 return 0;
74             
75             History history= QualifiedTypeNameHistory.getDefault();
76             
77             int pos1= history.getPosition(o1);
78             int pos2= history.getPosition(o2);
79             
80             if (pos1 == pos2)
81                 return Collator.getInstance().compare(o1, o2);
82             
83             if (pos1 > pos2) {
84                 return -1;
85             } else {
86                 return 1;
87             }
88         }
89         
90     }
91
92     private CompilationUnitEditor fEditor;
93
94     public AddImportOnSelectionAction(CompilationUnitEditor editor) {
95         super(JavaEditorMessages.AddImportOnSelection_label);
96         setToolTipText(JavaEditorMessages.AddImportOnSelection_tooltip);
97         setDescription(JavaEditorMessages.AddImportOnSelection_description);
98         fEditor= editor;
99         PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_IMPORT_ON_SELECTION_ACTION);
100         setEnabled(getCompilationUnit() != null);
101     }
102
103     public void update() {
104         setEnabled(fEditor != null && getCompilationUnit() != null);
105     }
106
107     private ICompilationUnit getCompilationUnit () {
108         if (fEditor == null) {
109             return null;
110         }
111         IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
112         return manager.getWorkingCopy(fEditor.getEditorInput());
113     }
114
115     /*
116      * @see org.eclipse.jface.action.IAction#run()
117      */

118     public void run() {
119         final ICompilationUnit cu= getCompilationUnit();
120         if (cu == null || fEditor == null)
121             return;
122         if (!ElementValidator.checkValidateEdit(cu, getShell(), JavaEditorMessages.AddImportOnSelection_error_title))
123             return;
124         if (!ActionUtil.isEditable(fEditor))
125             return;
126
127         ISelection selection= fEditor.getSelectionProvider().getSelection();
128         if (selection instanceof ITextSelection) {
129             final ITextSelection textSelection= (ITextSelection) selection;
130             AddImportOnSelectionAction.SelectTypeQuery query= new SelectTypeQuery(getShell());
131             AddImportsOperation op= new AddImportsOperation(cu, textSelection.getOffset(), textSelection.getLength(), query, false);
132             IEditingSupport helper= createViewerHelper(textSelection, query);
133             try {
134                 registerHelper(helper);
135                 IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
136                 progressService.runInUI(fEditor.getSite().getWorkbenchWindow(), new WorkbenchRunnableAdapter(op, op.getScheduleRule()), op.getScheduleRule());
137                 IStatus status= op.getStatus();
138                 if (!status.isOK()) {
139                     IStatusLineManager manager= getStatusLineManager();
140                     if (manager != null) {
141                         manager.setMessage(status.getMessage());
142                     }
143                 }
144             } catch (InvocationTargetException JavaDoc e) {
145                 ExceptionHandler.handle(e, getShell(), JavaEditorMessages.AddImportOnSelection_error_title, null);
146             } catch (InterruptedException JavaDoc e) {
147                 // Do nothing. Operation has been canceled.
148
} finally {
149                 deregisterHelper(helper);
150             }
151         }
152     }
153
154     private IEditingSupport createViewerHelper(final ITextSelection selection, final SelectTypeQuery query) {
155         return new IEditingSupport() {
156
157             public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) {
158                 return subjectRegion.getOffset() <= selection.getOffset() + selection.getLength() && selection.getOffset() <= subjectRegion.getOffset() + subjectRegion.getLength();
159             }
160
161             public boolean ownsFocusShell() {
162                 return query.isShowing();
163             }
164
165         };
166     }
167
168     private void registerHelper(IEditingSupport helper) {
169         ISourceViewer viewer= fEditor.getViewer();
170         if (viewer instanceof IEditingSupportRegistry) {
171             IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
172             registry.register(helper);
173         }
174     }
175
176     private void deregisterHelper(IEditingSupport helper) {
177         ISourceViewer viewer= fEditor.getViewer();
178         if (viewer instanceof IEditingSupportRegistry) {
179             IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
180             registry.unregister(helper);
181         }
182     }
183
184     private Shell getShell() {
185         return fEditor.getSite().getShell();
186     }
187
188     private static class SelectTypeQuery implements IChooseImportQuery {
189
190         private final Shell fShell;
191         private boolean fIsShowing;
192
193         public SelectTypeQuery(Shell shell) {
194             fShell= shell;
195         }
196
197         /* (non-Javadoc)
198          * @see org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation.IChooseImportQuery#chooseImport(org.eclipse.jdt.internal.corext.util.TypeInfo[], java.lang.String)
199          */

200         public TypeNameMatch chooseImport(TypeNameMatch[] results, String JavaDoc containerName) {
201             int nResults= results.length;
202
203             if (nResults == 0) {
204                 return null;
205             } else if (nResults == 1) {
206                 return results[0];
207             }
208
209             if (containerName.length() != 0) {
210                 for (int i= 0; i < nResults; i++) {
211                     TypeNameMatch curr= results[i];
212                     if (containerName.equals(curr.getTypeContainerName())) {
213                         return curr;
214                     }
215                 }
216             }
217             fIsShowing= true;
218             ElementListSelectionDialog dialog= new ElementListSelectionDialog(fShell, new TypeNameMatchLabelProvider(TypeNameMatchLabelProvider.SHOW_FULLYQUALIFIED)) {
219                 protected FilteredList createFilteredList(Composite parent) {
220                     FilteredList filteredList= super.createFilteredList(parent);
221                     filteredList.setComparator(ADD_IMPORT_COMPARATOR);
222                     return filteredList;
223                 }
224             };
225             dialog.setTitle(JavaEditorMessages.AddImportOnSelection_dialog_title);
226             dialog.setMessage(JavaEditorMessages.AddImportOnSelection_dialog_message);
227             dialog.setElements(results);
228             if (dialog.open() == Window.OK) {
229                 fIsShowing= false;
230                 TypeNameMatch result= (TypeNameMatch) dialog.getFirstResult();
231                 QualifiedTypeNameHistory.remember(result.getFullyQualifiedName());
232                 return result;
233             }
234             fIsShowing= false;
235             return null;
236         }
237
238         boolean isShowing() {
239             return fIsShowing;
240         }
241     }
242
243     private IStatusLineManager getStatusLineManager() {
244         return fEditor.getEditorSite().getActionBars().getStatusLineManager();
245     }
246
247     /**
248      * @return Returns the scheduling rule for this operation
249      */

250     public ISchedulingRule getScheduleRule() {
251         return ResourcesPlugin.getWorkspace().getRoot();
252     }
253
254 }
255
Popular Tags