KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > ui > actions > FindStringsToExternalizeAction


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 package org.eclipse.jdt.ui.actions;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Arrays JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18
19 import org.eclipse.core.runtime.CoreException;
20 import org.eclipse.core.runtime.IProgressMonitor;
21 import org.eclipse.core.runtime.IStatus;
22 import org.eclipse.core.runtime.OperationCanceledException;
23 import org.eclipse.core.runtime.Status;
24 import org.eclipse.core.runtime.SubProgressMonitor;
25
26 import org.eclipse.swt.SWT;
27 import org.eclipse.swt.events.SelectionAdapter;
28 import org.eclipse.swt.events.SelectionEvent;
29 import org.eclipse.swt.graphics.Image;
30 import org.eclipse.swt.graphics.Point;
31 import org.eclipse.swt.widgets.Button;
32 import org.eclipse.swt.widgets.Composite;
33 import org.eclipse.swt.widgets.Control;
34 import org.eclipse.swt.widgets.Shell;
35
36 import org.eclipse.jface.dialogs.IDialogConstants;
37 import org.eclipse.jface.dialogs.MessageDialog;
38 import org.eclipse.jface.operation.IRunnableWithProgress;
39 import org.eclipse.jface.viewers.ArrayContentProvider;
40 import org.eclipse.jface.viewers.ISelection;
41 import org.eclipse.jface.viewers.ISelectionChangedListener;
42 import org.eclipse.jface.viewers.IStructuredSelection;
43 import org.eclipse.jface.viewers.LabelProvider;
44 import org.eclipse.jface.viewers.SelectionChangedEvent;
45
46 import org.eclipse.ui.IWorkbenchSite;
47 import org.eclipse.ui.PlatformUI;
48
49 import org.eclipse.jdt.core.ICompilationUnit;
50 import org.eclipse.jdt.core.IJavaElement;
51 import org.eclipse.jdt.core.IJavaProject;
52 import org.eclipse.jdt.core.IPackageFragment;
53 import org.eclipse.jdt.core.IPackageFragmentRoot;
54 import org.eclipse.jdt.core.JavaModelException;
55 import org.eclipse.jdt.core.compiler.InvalidInputException;
56
57 import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement;
58 import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine;
59 import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
60 import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner;
61 import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
62 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
63 import org.eclipse.jdt.internal.corext.util.Messages;
64
65 import org.eclipse.jdt.ui.JavaElementLabelProvider;
66
67 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
68 import org.eclipse.jdt.internal.ui.JavaPlugin;
69 import org.eclipse.jdt.internal.ui.actions.ActionMessages;
70 import org.eclipse.jdt.internal.ui.refactoring.RefactoringSaveHelper;
71 import org.eclipse.jdt.internal.ui.refactoring.actions.ListDialog;
72 import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
73 import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
74 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
75
76 /**
77  * Find all strings in a package or project that are not externalized yet.
78  * <p>
79  * The action is applicable to selections containing projects or packages.
80  *
81  * <p>
82  * This class may be instantiated; it is not intended to be subclassed.
83  * </p>
84  *
85  * @since 2.0
86  * @deprecated use {@link ExternalizeStringsAction} instead
87  */

88 public class FindStringsToExternalizeAction extends SelectionDispatchAction {
89
90     private NonNLSElement[] fElements;
91     
92     /**
93      * Creates a new <code>FindStringsToExternalizeAction</code>. The action
94      * requires that the selection provided by the site's selection provider is of type
95      * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
96      *
97      * @param site the site providing context information for this action
98      */

99     public FindStringsToExternalizeAction(IWorkbenchSite site) {
100         super(site);
101         setText(ActionMessages.FindStringsToExternalizeAction_label);
102         PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_STRINGS_TO_EXTERNALIZE_ACTION);
103     }
104         
105     /* (non-Javadoc)
106      * Method declared on SelectionDispatchAction.
107      */

108     public void selectionChanged(IStructuredSelection selection) {
109         try {
110             setEnabled(computeEnablementState(selection));
111         } catch (JavaModelException e) {
112             if (JavaModelUtil.isExceptionToBeLogged(e))
113                 JavaPlugin.log(e);
114             setEnabled(false);//no UI - happens on selection changes
115
}
116     }
117     
118     private boolean computeEnablementState(IStructuredSelection selection) throws JavaModelException {
119         if (selection.isEmpty())
120             return false;
121         for (Iterator JavaDoc iter= selection.iterator(); iter.hasNext();) {
122             Object JavaDoc element= iter.next();
123             if (!(element instanceof IJavaElement))
124                 return false;
125             IJavaElement javaElement= (IJavaElement)element;
126             if (! javaElement.exists() || javaElement.isReadOnly())
127                 return false;
128             int elementType= javaElement.getElementType();
129             if (elementType != IJavaElement.PACKAGE_FRAGMENT &&
130                 elementType != IJavaElement.PACKAGE_FRAGMENT_ROOT &&
131                 elementType != IJavaElement.JAVA_PROJECT)
132                 return false;
133             if (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT){
134                 IPackageFragmentRoot root= (IPackageFragmentRoot)javaElement;
135                 if (root.isExternal() || ReorgUtils.isClassFolder(root))
136                     return false;
137             }
138         }
139         return true;
140     }
141     
142     /* (non-Javadoc)
143      * Method declared on SelectionDispatchAction.
144      */

145     public void run(final IStructuredSelection selection) {
146         try {
147             PlatformUI.getWorkbench().getProgressService().run(true, true, createRunnable(selection));
148         } catch(InvocationTargetException JavaDoc e) {
149             ExceptionHandler.handle(e, getShell(),
150                 ActionMessages.FindStringsToExternalizeAction_dialog_title,
151                 ActionMessages.FindStringsToExternalizeAction_error_message);
152             return;
153         } catch(InterruptedException JavaDoc e) {
154             // OK
155
return;
156         }
157         showResults();
158     }
159     
160     private IRunnableWithProgress createRunnable(final IStructuredSelection selection) {
161         return new IRunnableWithProgress() {
162             public void run(IProgressMonitor pm) throws InvocationTargetException JavaDoc {
163                 try {
164                     fElements= doRun(selection, pm);
165                 } catch (CoreException e) {
166                     throw new InvocationTargetException JavaDoc(e);
167                 }
168             }
169         };
170     }
171
172     private NonNLSElement[] doRun(IStructuredSelection selection, IProgressMonitor pm) throws CoreException {
173         List JavaDoc elements= getSelectedElementList(selection);
174         if (elements == null || elements.isEmpty())
175             return new NonNLSElement[0];
176
177         pm.beginTask(ActionMessages.FindStringsToExternalizeAction_find_strings, elements.size());
178                     
179         try{
180             List JavaDoc l= new ArrayList JavaDoc();
181             for (Iterator JavaDoc iter= elements.iterator(); iter.hasNext();) {
182                 IJavaElement element= (IJavaElement) iter.next();
183                 if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
184                     l.addAll(analyze((IPackageFragment) element, new SubProgressMonitor(pm, 1)));
185                 else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT)
186                     l.addAll(analyze((IPackageFragmentRoot) element, new SubProgressMonitor(pm, 1)));
187                 if (element.getElementType() == IJavaElement.JAVA_PROJECT)
188                     l.addAll(analyze((IJavaProject) element, new SubProgressMonitor(pm, 1)));
189             }
190             return (NonNLSElement[]) l.toArray(new NonNLSElement[l.size()]);
191         } finally{
192             pm.done();
193         }
194     }
195
196     private void showResults() {
197         if (noStrings())
198             MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.FindStringsToExternalizeAction_noStrings);
199         else
200             new NonNLSListDialog(getShell(), fElements, countStrings()).open();
201     }
202
203     private boolean noStrings() {
204         if (fElements != null) {
205             for (int i= 0; i < fElements.length; i++) {
206                 if (fElements[i].count != 0)
207                     return false;
208             }
209         }
210         return true;
211     }
212
213     /*
214      * returns List of Strings
215      */

216     private List JavaDoc analyze(IPackageFragment pack, IProgressMonitor pm) throws CoreException {
217         try{
218             if (pack == null)
219                 return new ArrayList JavaDoc(0);
220                 
221             ICompilationUnit[] cus= pack.getCompilationUnits();
222     
223             pm.beginTask("", cus.length); //$NON-NLS-1$
224
pm.setTaskName(pack.getElementName());
225             
226             List JavaDoc l= new ArrayList JavaDoc(cus.length);
227             for (int i= 0; i < cus.length; i++){
228                 pm.subTask(cus[i].getElementName());
229                 NonNLSElement element= analyze(cus[i]);
230                 if (element != null)
231                     l.add(element);
232                 pm.worked(1);
233                 if (pm.isCanceled())
234                     throw new OperationCanceledException();
235             }
236             return l;
237         } finally {
238             pm.done();
239         }
240     }
241
242     /*
243      * returns List of Strings
244      */

245     private List JavaDoc analyze(IPackageFragmentRoot sourceFolder, IProgressMonitor pm) throws CoreException {
246         try{
247             IJavaElement[] children= sourceFolder.getChildren();
248             pm.beginTask("", children.length); //$NON-NLS-1$
249
pm.setTaskName(sourceFolder.getElementName());
250             List JavaDoc result= new ArrayList JavaDoc();
251             for (int i= 0; i < children.length; i++) {
252                 IJavaElement iJavaElement= children[i];
253                 if (iJavaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT){
254                     IPackageFragment pack= (IPackageFragment)iJavaElement;
255                     if (! pack.isReadOnly())
256                         result.addAll(analyze(pack, new SubProgressMonitor(pm, 1)));
257                     else
258                         pm.worked(1);
259                 } else
260                     pm.worked(1);
261             }
262             return result;
263         } finally{
264             pm.done();
265         }
266     }
267     
268     /*
269      * returns List of Strings
270      */

271     private List JavaDoc analyze(IJavaProject project, IProgressMonitor pm) throws CoreException {
272         try{
273             IPackageFragment[] packs= project.getPackageFragments();
274             pm.beginTask("", packs.length); //$NON-NLS-1$
275
List JavaDoc result= new ArrayList JavaDoc();
276             for (int i= 0; i < packs.length; i++) {
277                 if (! packs[i].isReadOnly())
278                     result.addAll(analyze(packs[i], new SubProgressMonitor(pm, 1)));
279                 else
280                     pm.worked(1);
281             }
282             return result;
283         } finally{
284             pm.done();
285         }
286     }
287
288     private int countStrings() {
289         int found= 0;
290         if (fElements != null) {
291             for (int i= 0; i < fElements.length; i++)
292                 found+= fElements[i].count;
293         }
294         return found;
295     }
296
297     private NonNLSElement analyze(ICompilationUnit cu) throws CoreException {
298         int count= countNonExternalizedStrings(cu);
299         if (count == 0)
300             return null;
301         else
302             return new NonNLSElement(cu, count);
303     }
304     
305     private int countNonExternalizedStrings(ICompilationUnit cu) throws CoreException {
306         try{
307             NLSLine[] lines= NLSScanner.scan(cu);
308             int result= 0;
309             for (int i= 0; i < lines.length; i++) {
310                 result += countNonExternalizedStrings(lines[i]);
311             }
312             return result;
313         } catch (InvalidInputException e) {
314             throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
315                 Messages.format(ActionMessages.FindStringsToExternalizeAction_error_cannotBeParsed, cu.getElementName()),
316                 e));
317         }
318     }
319
320     private int countNonExternalizedStrings(NLSLine line){
321         int result= 0;
322         NLSElement[] elements= line.getElements();
323         for (int i= 0; i < elements.length; i++){
324             if (! elements[i].hasTag())
325                 result++;
326         }
327         return result;
328     }
329
330     /**
331      * returns <code>List</code> of <code>IPackageFragments</code>, <code>IPackageFragmentRoots</code> or
332      * <code>IJavaProjects</code> (all entries are of the same kind)
333      */

334     private static List JavaDoc getSelectedElementList(IStructuredSelection selection) {
335         if (selection == null)
336             return null;
337             
338         return selection.toList();
339     }
340             
341     //-------private classes --------------
342

343     private static class NonNLSListDialog extends ListDialog {
344         
345         private static final int OPEN_BUTTON_ID= IDialogConstants.CLIENT_ID + 1;
346         
347         private Button fOpenButton;
348         
349         NonNLSListDialog(Shell parent, NonNLSElement[] input, int count) {
350             super(parent);
351             setInput(Arrays.asList(input));
352             setTitle(ActionMessages.FindStringsToExternalizeAction_dialog_title);
353             setMessage(Messages.format(ActionMessages.FindStringsToExternalizeAction_non_externalized, new Object JavaDoc[] {new Integer JavaDoc(count)} ));
354             setContentProvider(new ArrayContentProvider());
355             setLabelProvider(createLabelProvider());
356         }
357
358         public void create() {
359             setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN);
360             super.create();
361         }
362
363         protected Point getInitialSize() {
364             return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
365         }
366
367         protected Control createDialogArea(Composite parent) {
368             Composite result= (Composite)super.createDialogArea(parent);
369             getTableViewer().addSelectionChangedListener(new ISelectionChangedListener(){
370                 public void selectionChanged(SelectionChangedEvent event){
371                     if (fOpenButton != null){
372                         fOpenButton.setEnabled(! getTableViewer().getSelection().isEmpty());
373                     }
374                 }
375             });
376             getTableViewer().getTable().addSelectionListener(new SelectionAdapter(){
377                 public void widgetDefaultSelected(SelectionEvent e) {
378                     NonNLSElement element= (NonNLSElement)e.item.getData();
379                     openWizard(element.cu);
380                 }
381             });
382             getTableViewer().getTable().setFocus();
383             applyDialogFont(result);
384             return result;
385         }
386         
387         protected void createButtonsForButtonBar(Composite parent) {
388             fOpenButton= createButton(parent, OPEN_BUTTON_ID, ActionMessages.FindStringsToExternalizeAction_button_label, true);
389             fOpenButton.setEnabled(false);
390             
391             //looks like a 'close' but it a 'cancel'
392
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CLOSE_LABEL, false);
393         }
394
395         protected void buttonPressed(int buttonId) {
396             if (buttonId != OPEN_BUTTON_ID){
397                 super.buttonPressed(buttonId);
398                 return;
399             }
400             ISelection s= getTableViewer().getSelection();
401             if (s instanceof IStructuredSelection){
402                 IStructuredSelection ss= (IStructuredSelection)s;
403                 if (ss.getFirstElement() instanceof NonNLSElement)
404                     openWizard(((NonNLSElement)ss.getFirstElement()).cu);
405             }
406         }
407
408         private void openWizard(ICompilationUnit unit) {
409             try {
410                 if (unit != null && unit.exists()) {
411                     NLSRefactoring refactoring= NLSRefactoring.create(unit);
412                     if (refactoring != null)
413                         new RefactoringStarter().activate(refactoring, new ExternalizeWizard(refactoring), getShell(), ActionMessages.ExternalizeStringsAction_dialog_title, RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES);
414                 }
415             } catch (JavaModelException e) {
416                 ExceptionHandler.handle(e,
417                     ActionMessages.FindStringsToExternalizeAction_dialog_title,
418                     ActionMessages.FindStringsToExternalizeAction_error_message);
419             }
420         }
421         
422         private static LabelProvider createLabelProvider() {
423             return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT){
424                 public String JavaDoc getText(Object JavaDoc element) {
425                     NonNLSElement nlsel= (NonNLSElement)element;
426                     String JavaDoc elementName= nlsel.cu.getResource().getFullPath().toString();
427                     return Messages.format(
428                         ActionMessages.FindStringsToExternalizeAction_foundStrings,
429                         new Object JavaDoc[] {new Integer JavaDoc(nlsel.count), elementName} );
430                 }
431                 public Image getImage(Object JavaDoc element) {
432                     return super.getImage(((NonNLSElement)element).cu);
433                 }
434             };
435         }
436         
437         /*
438          * @see org.eclipse.jface.window.Window#configureShell(Shell)
439          */

440         protected void configureShell(Shell newShell) {
441             super.configureShell(newShell);
442             PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.NONNLS_DIALOG);
443         }
444
445
446     }
447         
448     private static class NonNLSElement{
449         ICompilationUnit cu;
450         int count;
451         NonNLSElement(ICompilationUnit cu, int count){
452             this.cu= cu;
453             this.count= count;
454         }
455     }
456     
457     private String JavaDoc getDialogTitle() {
458         return ActionMessages.FindStringsToExternalizeAction_dialog_title;
459     }
460 }
461
Popular Tags