KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > fix > CleanUpRefactoringWizard


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.fix;
12
13 import java.io.ByteArrayInputStream JavaDoc;
14 import java.io.ByteArrayOutputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.InputStream JavaDoc;
17 import java.io.UnsupportedEncodingException JavaDoc;
18 import java.util.ArrayList JavaDoc;
19 import java.util.Arrays JavaDoc;
20 import java.util.Hashtable JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.List JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import org.eclipse.core.runtime.CoreException;
26 import org.eclipse.core.runtime.IStatus;
27 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
28 import org.eclipse.core.runtime.preferences.InstanceScope;
29
30 import org.eclipse.core.resources.ProjectScope;
31
32 import org.eclipse.swt.SWT;
33 import org.eclipse.swt.events.SelectionAdapter;
34 import org.eclipse.swt.events.SelectionEvent;
35 import org.eclipse.swt.graphics.Image;
36 import org.eclipse.swt.layout.GridData;
37 import org.eclipse.swt.layout.GridLayout;
38 import org.eclipse.swt.widgets.Button;
39 import org.eclipse.swt.widgets.Composite;
40 import org.eclipse.swt.widgets.Control;
41 import org.eclipse.swt.widgets.Link;
42 import org.eclipse.swt.widgets.Shell;
43 import org.eclipse.swt.widgets.Table;
44
45 import org.eclipse.jface.dialogs.ControlEnableState;
46 import org.eclipse.jface.dialogs.Dialog;
47 import org.eclipse.jface.viewers.ColumnLayoutData;
48 import org.eclipse.jface.viewers.ColumnWeightData;
49 import org.eclipse.jface.viewers.ITableLabelProvider;
50 import org.eclipse.jface.viewers.LabelProvider;
51 import org.eclipse.jface.viewers.StructuredSelection;
52 import org.eclipse.jface.viewers.ViewerComparator;
53 import org.eclipse.jface.wizard.IWizardPage;
54
55 import org.eclipse.ui.dialogs.PreferencesUtil;
56
57 import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
58 import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
59
60 import org.eclipse.jdt.core.ICompilationUnit;
61 import org.eclipse.jdt.core.IJavaProject;
62
63 import org.eclipse.jdt.internal.corext.fix.CleanUpConstants;
64 import org.eclipse.jdt.internal.corext.fix.CleanUpPreferenceUtil;
65 import org.eclipse.jdt.internal.corext.fix.CleanUpRefactoring;
66 import org.eclipse.jdt.internal.corext.util.Messages;
67
68 import org.eclipse.jdt.ui.JavaUI;
69
70 import org.eclipse.jdt.internal.ui.JavaPlugin;
71 import org.eclipse.jdt.internal.ui.JavaPluginImages;
72 import org.eclipse.jdt.internal.ui.preferences.BulletListBlock;
73 import org.eclipse.jdt.internal.ui.preferences.CleanUpPreferencePage;
74 import org.eclipse.jdt.internal.ui.preferences.cleanup.CleanUpProfileVersioner;
75 import org.eclipse.jdt.internal.ui.preferences.cleanup.CleanUpTabPage;
76 import org.eclipse.jdt.internal.ui.preferences.cleanup.CodeFormatingTabPage;
77 import org.eclipse.jdt.internal.ui.preferences.cleanup.CodeStyleTabPage;
78 import org.eclipse.jdt.internal.ui.preferences.cleanup.MemberAccessesTabPage;
79 import org.eclipse.jdt.internal.ui.preferences.cleanup.MissingCodeTabPage;
80 import org.eclipse.jdt.internal.ui.preferences.cleanup.UnnecessaryCodeTabPage;
81 import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager;
82 import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileStore;
83 import org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage.IModificationListener;
84 import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
85 import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.Profile;
86 import org.eclipse.jdt.internal.ui.util.SWTUtil;
87 import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
88 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
89 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
90 import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
91 import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
92
93 import org.xml.sax.InputSource JavaDoc;
94
95 public class CleanUpRefactoringWizard extends RefactoringWizard {
96     
97     private static final String JavaDoc USE_CUSTOM_PROFILE_KEY= "org.eclipse.jdt.ui.cleanup.use_dialog_profile"; //$NON-NLS-1$
98
private static final String JavaDoc CUSTOM_PROFILE_KEY= "org.eclipse.jdt.ui.cleanup.custom_profile"; //$NON-NLS-1$
99

100     private static class ProjectProfileLableProvider extends LabelProvider implements ITableLabelProvider {
101
102         private Hashtable JavaDoc fProfileIdsTable;
103
104         /**
105          * {@inheritDoc}
106          */

107         public Image getColumnImage(Object JavaDoc element, int columnIndex) {
108             return null;
109         }
110
111         /**
112          * {@inheritDoc}
113          */

114         public String JavaDoc getColumnText(Object JavaDoc element, int columnIndex) {
115             if (columnIndex == 0) {
116                 return ((IJavaProject)element).getProject().getName();
117             } else if (columnIndex == 1) {
118                 
119                 if (fProfileIdsTable == null)
120                     fProfileIdsTable= loadProfiles();
121                 
122                 InstanceScope instanceScope= new InstanceScope();
123                 IEclipsePreferences instancePreferences= instanceScope.getNode(JavaUI.ID_PLUGIN);
124     
125                 final String JavaDoc workbenchProfileId;
126                 if (instancePreferences.get(CleanUpConstants.CLEANUP_PROFILE, null) != null) {
127                     workbenchProfileId= instancePreferences.get(CleanUpConstants.CLEANUP_PROFILE, null);
128                 } else {
129                     workbenchProfileId= CleanUpConstants.DEFAULT_PROFILE;
130                 }
131                 
132                 return getProjectProfileName((IJavaProject)element, fProfileIdsTable, workbenchProfileId);
133             }
134             return null;
135         }
136         
137         private Hashtable JavaDoc loadProfiles() {
138             List JavaDoc list= CleanUpPreferenceUtil.loadProfiles(new InstanceScope());
139             
140             Hashtable JavaDoc profileIdsTable= new Hashtable JavaDoc();
141             for (Iterator JavaDoc iterator= list.iterator(); iterator.hasNext();) {
142                 Profile profile= (Profile)iterator.next();
143                 profileIdsTable.put(profile.getID(), profile);
144             }
145          
146             return profileIdsTable;
147         }
148
149         private String JavaDoc getProjectProfileName(final IJavaProject project, Hashtable JavaDoc profileIdsTable, String JavaDoc workbenchProfileId) {
150             ProjectScope projectScope= new ProjectScope(project.getProject());
151             IEclipsePreferences node= projectScope.getNode(JavaUI.ID_PLUGIN);
152             String JavaDoc id= node.get(CleanUpConstants.CLEANUP_PROFILE, null);
153             if (id == null) {
154                 Profile profile= (Profile)profileIdsTable.get(workbenchProfileId);
155                 if (profile != null) {
156                     return profile.getName();
157                 } else {
158                     return MultiFixMessages.CleanUpRefactoringWizard_unknownProfile_Name;
159                 }
160             } else {
161                 Profile profile= (Profile)profileIdsTable.get(id);
162                 if (profile != null) {
163                     return profile.getName();
164                 } else {
165                     return Messages.format(MultiFixMessages.CleanUpRefactoringWizard_UnmanagedProfileWithName_Name, id.substring(ProfileManager.ID_PREFIX.length()));
166                 }
167             }
168         }
169
170         public void reset() {
171             fProfileIdsTable= null;
172         }
173     }
174     
175     private static class CleanUpConfigurationPage extends UserInputWizardPage implements IModificationListener {
176
177         private static final class ProfileTableAdapter implements IListAdapter {
178             private final ProjectProfileLableProvider fProvider;
179             private final Shell fShell;
180
181             private ProfileTableAdapter(ProjectProfileLableProvider provider, Shell shell) {
182                 fProvider= provider;
183                 fShell= shell;
184             }
185
186             public void customButtonPressed(ListDialogField field, int index) {
187                 openPropertyDialog(field);
188             }
189
190             public void doubleClicked(ListDialogField field) {
191                 openPropertyDialog(field);
192             }
193             
194             private void openPropertyDialog(ListDialogField field) {
195                 IJavaProject project= (IJavaProject)field.getSelectedElements().get(0);
196                 PreferencesUtil.createPropertyDialogOn(fShell, project, CleanUpPreferencePage.PROP_ID, null, null).open();
197                 List JavaDoc selectedElements= field.getSelectedElements();
198                 fProvider.reset();
199                 field.refresh();
200                 field.selectElements(new StructuredSelection(selectedElements));
201             }
202
203             public void selectionChanged(ListDialogField field) {
204                 if (field.getSelectedElements().size() != 1) {
205                     field.enableButton(0, false);
206                 } else {
207                     field.enableButton(0, true);
208                 }
209             }
210         }
211
212         private static final String JavaDoc ENCODING= "UTF-8"; //$NON-NLS-1$
213

214         private final CleanUpRefactoring fCleanUpRefactoring;
215         private Map JavaDoc fCustomSettings;
216         private SelectionButtonDialogField fUseCustomField;
217         
218         private ControlEnableState fEnableState;
219
220         public CleanUpConfigurationPage(CleanUpRefactoring refactoring) {
221             super(MultiFixMessages.CleanUpRefactoringWizard_CleanUpConfigurationPage_title);
222             fCleanUpRefactoring= refactoring;
223             ICompilationUnit[] cus= fCleanUpRefactoring.getCompilationUnits();
224             IJavaProject[] projects= fCleanUpRefactoring.getProjects();
225             if (cus.length == 1) {
226                 setMessage(MultiFixMessages.CleanUpRefactoringWizard_CleaningUp11_Title);
227             } else if (projects.length == 1) {
228                 setMessage(Messages.format(MultiFixMessages.CleanUpRefactoringWizard_CleaningUpN1_Title, new Integer JavaDoc(cus.length)));
229             } else {
230                 setMessage(Messages.format(MultiFixMessages.CleanUpRefactoringWizard_CleaningUpNN_Title, new Object JavaDoc[] {new Integer JavaDoc(cus.length), new Integer JavaDoc(projects.length)}));
231             }
232         }
233
234         /**
235          * {@inheritDoc}
236          */

237         public void createControl(Composite parent) {
238             boolean isCustom= getDialogSettings().getBoolean(USE_CUSTOM_PROFILE_KEY);
239             
240             final Composite composite= new Composite(parent, SWT.NONE);
241             composite.setLayout(new GridLayout(2, false));
242             composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
243             composite.setFont(parent.getFont());
244             
245             SelectionButtonDialogField useProfile= new SelectionButtonDialogField(SWT.RADIO);
246             useProfile.setLabelText(MultiFixMessages.CleanUpRefactoringWizard_use_configured_radio);
247             useProfile.setSelection(!isCustom);
248             useProfile.doFillIntoGrid(composite, 2);
249             
250             ProjectProfileLableProvider tableLabelProvider= new ProjectProfileLableProvider();
251             IListAdapter listAdapter= new ProfileTableAdapter(tableLabelProvider, getShell());
252             String JavaDoc[] buttons= new String JavaDoc[] {
253                 MultiFixMessages.CleanUpRefactoringWizard_Configure_Button
254             };
255             final ListDialogField settingsField= new ListDialogField(listAdapter, buttons, tableLabelProvider);
256             
257             String JavaDoc[] headerNames= new String JavaDoc[] {
258                     MultiFixMessages.CleanUpRefactoringWizard_Project_TableHeader,
259                     MultiFixMessages.CleanUpRefactoringWizard_Profile_TableHeader
260             };
261             ColumnLayoutData[] columns = new ColumnLayoutData[] {
262                     new ColumnWeightData(1, 100, true),
263                     new ColumnWeightData(2, 20, true)
264             };
265             settingsField.setTableColumns(new ListDialogField.ColumnsDescription(columns , headerNames, true));
266             settingsField.setViewerComparator(new ViewerComparator());
267             
268             settingsField.doFillIntoGrid(composite, 3);
269             
270             Table table= settingsField.getTableViewer().getTable();
271             GridData data= (GridData)settingsField.getListControl(null).getLayoutData();
272             data.horizontalIndent= 15;
273             data.grabExcessVerticalSpace= false;
274             data.heightHint= SWTUtil.getTableHeightHint(table, Math.min(5, fCleanUpRefactoring.getProjects().length + 1));
275             data.grabExcessHorizontalSpace= true;
276             data.verticalAlignment= GridData.BEGINNING;
277             
278             data= (GridData)settingsField.getButtonBox(null).getLayoutData();
279             data.grabExcessVerticalSpace= false;
280             data.verticalAlignment= GridData.BEGINNING;
281
282             data= (GridData)settingsField.getLabelControl(null).getLayoutData();
283             data.exclude= true;
284                         
285             settingsField.setElements(Arrays.asList(fCleanUpRefactoring.getProjects()));
286             settingsField.selectFirstElement();
287             
288             fUseCustomField= new SelectionButtonDialogField(SWT.RADIO);
289             fUseCustomField.setLabelText(MultiFixMessages.CleanUpRefactoringWizard_use_custom_radio);
290             fUseCustomField.setSelection(isCustom);
291             fUseCustomField.doFillIntoGrid(composite, 2);
292             
293             String JavaDoc settings= getDialogSettings().get(CUSTOM_PROFILE_KEY);
294             if (settings == null) {
295                 fCustomSettings= CleanUpConstants.getEclipseDefaultSettings();
296             } else {
297                 try {
298                     fCustomSettings= decodeSettings(settings);
299                 } catch (CoreException e) {
300                     JavaPlugin.log(e);
301                     fCustomSettings= CleanUpConstants.getEclipseDefaultSettings();
302                 }
303             }
304             
305             final BulletListBlock bulletListBlock= new BulletListBlock();
306             Control bulletList= bulletListBlock.createControl(composite);
307             GridData layoutData= (GridData)bulletList.getLayoutData();
308             (layoutData).horizontalIndent= 15;
309             layoutData.grabExcessVerticalSpace= true;
310             
311             final Button configure= new Button(composite, SWT.NONE);
312             configure.setText(MultiFixMessages.CleanUpRefactoringWizard_ConfigureCustomProfile_button);
313             
314             data= new GridData(SWT.TOP, SWT.LEAD, false, false);
315             data.widthHint= SWTUtil.getButtonWidthHint(configure);
316             configure.setLayoutData(data);
317             
318             showCustomSettings(bulletListBlock);
319             configure.addSelectionListener(new SelectionAdapter() {
320                 /**
321                  * {@inheritDoc}
322                  */

323                 public void widgetSelected(SelectionEvent e) {
324                     CleanUpSaveParticipantConfigurationModifyDialog dialog= new CleanUpSaveParticipantConfigurationModifyDialog(getShell(), fCustomSettings, MultiFixMessages.CleanUpRefactoringWizard_CustomCleanUpsDialog_title) {
325                         protected CleanUpTabPage[] createTabPages(Map JavaDoc workingValues) {
326                             CleanUpTabPage[] result= new CleanUpTabPage[5];
327                             result[0]= new CodeStyleTabPage(this, workingValues, false);
328                             result[1]= new MemberAccessesTabPage(this, workingValues, false);
329                             result[2]= new UnnecessaryCodeTabPage(this, workingValues, false);
330                             result[3]= new MissingCodeTabPage(this, workingValues, false);
331                             result[4]= new CodeFormatingTabPage(this, workingValues, false);
332                             
333                             addTabPage(MultiFixMessages.CleanUpRefactoringWizard_code_style_tab, result[0]);
334                             addTabPage(MultiFixMessages.CleanUpRefactoringWizard_member_accesses_tab, result[1]);
335                             addTabPage(MultiFixMessages.CleanUpRefactoringWizard_unnecessary_code_tab, result[2]);
336                             addTabPage(MultiFixMessages.CleanUpRefactoringWizard_missing_code_tab, result[3]);
337                             addTabPage(MultiFixMessages.CleanUpRefactoringWizard_code_organizing_tab, result[4]);
338                             
339                             return result;
340                         }
341                     };
342                     dialog.open();
343                     showCustomSettings(bulletListBlock);
344                 }
345             });
346             
347             updateEnableState(isCustom, settingsField, configure, bulletListBlock);
348             
349             fUseCustomField.setDialogFieldListener(new IDialogFieldListener() {
350                 public void dialogFieldChanged(DialogField field) {
351                     updateEnableState(fUseCustomField.isSelected(), settingsField, configure, bulletListBlock);
352                 }
353             });
354             
355             Link preferencePageLink= new Link(composite, SWT.WRAP);
356             preferencePageLink.setText(MultiFixMessages.CleanUpRefactoringWizard_HideWizard_Link);
357             preferencePageLink.setFont(parent.getFont());
358             GridData gridData= new GridData(SWT.FILL, SWT.FILL, true, false);
359             gridData.widthHint= convertWidthInCharsToPixels(300);
360             gridData.horizontalSpan= 2;
361             preferencePageLink.setLayoutData(gridData);
362             preferencePageLink.addSelectionListener(new SelectionAdapter() {
363                 /**
364                  * {@inheritDoc}
365                  */

366                 public void widgetSelected(SelectionEvent e) {
367                     PreferencesUtil.createPreferenceDialogOn(composite.getShell(), CleanUpPreferencePage.PREF_ID, null, null).open();
368                 }
369             });
370             
371             setControl(composite);
372             
373             Dialog.applyDialogFont(composite);
374         }
375
376         private void updateEnableState(boolean isCustom, final ListDialogField settingsField, Button configureCustom, BulletListBlock bulletListBlock) {
377             settingsField.getListControl(null).setEnabled(!isCustom);
378             if (isCustom) {
379                 fEnableState= ControlEnableState.disable(settingsField.getButtonBox(null));
380             } else if (fEnableState != null) {
381                 fEnableState.restore();
382                 fEnableState= null;
383             }
384             bulletListBlock.setEnabled(isCustom);
385             configureCustom.setEnabled(isCustom);
386         }
387         
388         private void showCustomSettings(BulletListBlock bulletListBlock) {
389             StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
390             
391             final ICleanUp[] cleanUps= CleanUpRefactoring.createCleanUps(fCustomSettings);
392             for (int i= 0; i < cleanUps.length; i++) {
393                 String JavaDoc[] descriptions= cleanUps[i].getDescriptions();
394                 if (descriptions != null) {
395                     for (int j= 0; j < descriptions.length; j++) {
396                         if (buf.length() > 0) {
397                             buf.append('\n');
398                         }
399                         buf.append(descriptions[j]);
400                     }
401                 }
402             }
403             bulletListBlock.setText(buf.toString());
404         }
405         
406         protected boolean performFinish() {
407             initializeRefactoring();
408             storeSettings();
409             return super.performFinish();
410         }
411
412         public IWizardPage getNextPage() {
413             initializeRefactoring();
414             storeSettings();
415             return super.getNextPage();
416         }
417         
418         private void storeSettings() {
419             getDialogSettings().put(USE_CUSTOM_PROFILE_KEY, fUseCustomField.isSelected());
420             try {
421                 getDialogSettings().put(CUSTOM_PROFILE_KEY, encodeSettings(fCustomSettings));
422             } catch (CoreException e) {
423                 JavaPlugin.log(e);
424             }
425         }
426
427         private void initializeRefactoring() {
428             ICleanUp[] cleanups;
429             if (fUseCustomField.isSelected()) {
430                 cleanups= CleanUpRefactoring.createCleanUps(fCustomSettings);
431             } else {
432                 cleanups= CleanUpRefactoring.createCleanUps();
433             }
434
435             CleanUpRefactoring refactoring= (CleanUpRefactoring)getRefactoring();
436             refactoring.clearCleanUps();
437             for (int i= 0; i < cleanups.length; i++) {
438                 refactoring.addCleanUp(cleanups[i]);
439             }
440         }
441         
442         public String JavaDoc encodeSettings(Map JavaDoc settings) throws CoreException {
443             ByteArrayOutputStream JavaDoc stream= new ByteArrayOutputStream JavaDoc(2000);
444             try {
445                 CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
446                 CustomProfile profile= new ProfileManager.CustomProfile("custom", settings, versioner.getCurrentVersion(), versioner.getProfileKind()); //$NON-NLS-1$
447
ArrayList JavaDoc profiles= new ArrayList JavaDoc();
448                 profiles.add(profile);
449                 ProfileStore.writeProfilesToStream(profiles, stream, ENCODING, versioner);
450                 try {
451                     return stream.toString(ENCODING);
452                 } catch (UnsupportedEncodingException JavaDoc e) {
453                     return stream.toString();
454                 }
455             } finally {
456                 try { stream.close(); } catch (IOException JavaDoc e) { /* ignore */ }
457             }
458         }
459         
460         public Map JavaDoc decodeSettings(String JavaDoc settings) throws CoreException {
461             byte[] bytes;
462             try {
463                 bytes= settings.getBytes(ENCODING);
464             } catch (UnsupportedEncodingException JavaDoc e) {
465                 bytes= settings.getBytes();
466             }
467             InputStream JavaDoc is= new ByteArrayInputStream JavaDoc(bytes);
468             try {
469                 List JavaDoc res= ProfileStore.readProfilesFromStream(new InputSource JavaDoc(is));
470                 if (res == null || res.size() == 0)
471                     return CleanUpConstants.getEclipseDefaultSettings();
472                 
473                 CustomProfile profile= (CustomProfile)res.get(0);
474                 new CleanUpProfileVersioner().update(profile);
475                 return profile.getSettings();
476             } finally {
477                 try { is.close(); } catch (IOException JavaDoc e) { /* ignore */ }
478             }
479         }
480
481         /**
482          * {@inheritDoc}
483          */

484         public void updateStatus(IStatus status) {}
485
486         /**
487          * {@inheritDoc}
488          */

489         public void valuesModified() {}
490     }
491     
492     public CleanUpRefactoringWizard(CleanUpRefactoring refactoring, int flags) {
493         super(refactoring, flags);
494         setDefaultPageTitle(MultiFixMessages.CleanUpRefactoringWizard_PageTitle);
495         setWindowTitle(MultiFixMessages.CleanUpRefactoringWizard_WindowTitle);
496         setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_CLEAN_UP);
497     }
498
499     /* (non-Javadoc)
500      * @see org.eclipse.ltk.ui.refactoring.RefactoringWizard#addUserInputPages()
501      */

502     protected void addUserInputPages() {
503         addPage(new CleanUpConfigurationPage((CleanUpRefactoring)getRefactoring()));
504     }
505
506 }
507
Popular Tags