KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > preferences > ImportOrganizeConfigurationBlock


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.internal.ui.preferences;
12
13 import java.io.FileInputStream JavaDoc;
14 import java.io.FileOutputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Properties JavaDoc;
19
20 import org.eclipse.core.runtime.IStatus;
21
22 import org.eclipse.core.resources.IProject;
23
24 import org.eclipse.swt.SWT;
25 import org.eclipse.swt.graphics.Image;
26 import org.eclipse.swt.layout.GridData;
27 import org.eclipse.swt.layout.GridLayout;
28 import org.eclipse.swt.widgets.Composite;
29 import org.eclipse.swt.widgets.Control;
30 import org.eclipse.swt.widgets.FileDialog;
31
32 import org.eclipse.jface.dialogs.Dialog;
33 import org.eclipse.jface.dialogs.IDialogSettings;
34 import org.eclipse.jface.dialogs.MessageDialog;
35 import org.eclipse.jface.viewers.LabelProvider;
36 import org.eclipse.jface.window.Window;
37
38 import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
39
40 import org.eclipse.jdt.core.JavaConventions;
41 import org.eclipse.jdt.core.JavaCore;
42
43 import org.eclipse.jdt.ui.JavaElementImageDescriptor;
44 import org.eclipse.jdt.ui.JavaUI;
45 import org.eclipse.jdt.ui.PreferenceConstants;
46
47 import org.eclipse.jdt.internal.ui.JavaPlugin;
48 import org.eclipse.jdt.internal.ui.JavaPluginImages;
49 import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
50 import org.eclipse.jdt.internal.ui.util.PixelConverter;
51 import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
52 import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
53 import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
54 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
55 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
56 import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
57 import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
58 import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
59 import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
60
61 /*
62  * The page for setting the organize import settings
63  */

64 public class ImportOrganizeConfigurationBlock extends OptionsConfigurationBlock {
65
66     private static final Key PREF_IMPORTORDER= getJDTUIKey(PreferenceConstants.ORGIMPORTS_IMPORTORDER);
67     private static final Key PREF_ONDEMANDTHRESHOLD= getJDTUIKey(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD);
68     private static final Key PREF_IGNORELOWERCASE= getJDTUIKey(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
69     private static final Key PREF_STATICONDEMANDTHRESHOLD= getJDTUIKey(PreferenceConstants.ORGIMPORTS_STATIC_ONDEMANDTHRESHOLD);
70     
71     private static final String JavaDoc DIALOGSETTING_LASTLOADPATH= JavaUI.ID_PLUGIN + ".importorder.loadpath"; //$NON-NLS-1$
72
private static final String JavaDoc DIALOGSETTING_LASTSAVEPATH= JavaUI.ID_PLUGIN + ".importorder.savepath"; //$NON-NLS-1$
73

74     private static Key[] getAllKeys() {
75         return new Key[] {
76             PREF_IMPORTORDER, PREF_ONDEMANDTHRESHOLD, PREF_STATICONDEMANDTHRESHOLD, PREF_IGNORELOWERCASE
77         };
78     }
79     
80     public static class ImportOrderEntry {
81         
82         public final String JavaDoc name;
83         public final boolean isStatic;
84         
85         public ImportOrderEntry(String JavaDoc name, boolean isStatic) {
86             this.name= name;
87             this.isStatic= isStatic;
88         }
89         
90         public String JavaDoc serialize() {
91             return isStatic ? '#' + name : name;
92         }
93         
94         public static ImportOrderEntry fromSerialized(String JavaDoc str) {
95             if (str.length() > 0 && str.charAt(0) == '#') {
96                 return new ImportOrderEntry(str.substring(1), true);
97             }
98             return new ImportOrderEntry(str, false);
99         }
100         
101     }
102     
103     
104     private static class ImportOrganizeLabelProvider extends LabelProvider {
105         
106         private final Image PCK_ICON;
107         private final Image STATIC_CLASS_ICON;
108
109         public ImportOrganizeLabelProvider() {
110             PCK_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKAGE);
111             STATIC_CLASS_ICON= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
112         }
113         
114         public Image getImage(Object JavaDoc element) {
115             return ((ImportOrderEntry) element).isStatic ? STATIC_CLASS_ICON : PCK_ICON;
116         }
117
118         public String JavaDoc getText(Object JavaDoc element) {
119             ImportOrderEntry entry= (ImportOrderEntry) element;
120             String JavaDoc name= entry.name;
121             if (name.length() > 0) {
122                 return name;
123             }
124             if (entry.isStatic) {
125                 return PreferencesMessages.ImportOrganizeConfigurationBlock_other_static;
126             }
127             return PreferencesMessages.ImportOrganizeConfigurationBlock_other_normal;
128         }
129     }
130     
131     private class ImportOrganizeAdapter implements IListAdapter, IDialogFieldListener {
132
133         private boolean canEdit(ListDialogField field) {
134             List JavaDoc selected= field.getSelectedElements();
135             return selected.size() == 1;
136         }
137
138         public void customButtonPressed(ListDialogField field, int index) {
139             doButtonPressed(index);
140         }
141
142         public void selectionChanged(ListDialogField field) {
143             fOrderListField.enableButton(IDX_EDIT, canEdit(field));
144         }
145
146         public void dialogFieldChanged(DialogField field) {
147             doDialogFieldChanged(field);
148         }
149         
150         public void doubleClicked(ListDialogField field) {
151             if (canEdit(field)) {
152                 doButtonPressed(IDX_EDIT);
153             }
154         }
155     }
156     
157     private static final int IDX_ADD= 0;
158     private static final int IDX_ADD_STATIC= 1;
159     private static final int IDX_EDIT= 2;
160     private static final int IDX_REMOVE= 3;
161     private static final int IDX_UP= 5;
162     private static final int IDX_DOWN= 6;
163
164     private ListDialogField fOrderListField;
165     private StringDialogField fThresholdField;
166     private StringDialogField fStaticThresholdField;
167     private SelectionButtonDialogField fIgnoreLowerCaseTypesField;
168     private SelectionButtonDialogField fExportButton;
169     private SelectionButtonDialogField fImportButton;
170     
171     private PixelConverter fPixelConverter;
172     
173     public ImportOrganizeConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
174         super(context, project, getAllKeys(), container);
175     
176         String JavaDoc[] buttonLabels= new String JavaDoc[] {
177             PreferencesMessages.ImportOrganizeConfigurationBlock_order_add_button,
178             PreferencesMessages.ImportOrganizeConfigurationBlock_order_add_static_button,
179             PreferencesMessages.ImportOrganizeConfigurationBlock_order_edit_button,
180             PreferencesMessages.ImportOrganizeConfigurationBlock_order_remove_button,
181             /* 4 */ null,
182             PreferencesMessages.ImportOrganizeConfigurationBlock_order_up_button,
183             PreferencesMessages.ImportOrganizeConfigurationBlock_order_down_button,
184         };
185                 
186         ImportOrganizeAdapter adapter= new ImportOrganizeAdapter();
187         
188         fOrderListField= new ListDialogField(adapter, buttonLabels, new ImportOrganizeLabelProvider());
189         fOrderListField.setDialogFieldListener(adapter);
190         fOrderListField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_order_label);
191         fOrderListField.setUpButtonIndex(IDX_UP);
192         fOrderListField.setDownButtonIndex(IDX_DOWN);
193         fOrderListField.setRemoveButtonIndex(IDX_REMOVE);
194         
195         fOrderListField.enableButton(IDX_EDIT, false);
196         
197         fImportButton= new SelectionButtonDialogField(SWT.PUSH);
198         fImportButton.setDialogFieldListener(adapter);
199         fImportButton.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_order_load_button);
200         
201         fExportButton= new SelectionButtonDialogField(SWT.PUSH);
202         fExportButton.setDialogFieldListener(adapter);
203         fExportButton.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_order_save_button);
204         
205         fThresholdField= new StringDialogField();
206         fThresholdField.setDialogFieldListener(adapter);
207         fThresholdField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_threshold_label);
208
209         fStaticThresholdField= new StringDialogField();
210         fStaticThresholdField.setDialogFieldListener(adapter);
211         fStaticThresholdField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_staticthreshold_label);
212
213         fIgnoreLowerCaseTypesField= new SelectionButtonDialogField(SWT.CHECK);
214         fIgnoreLowerCaseTypesField.setDialogFieldListener(adapter);
215         fIgnoreLowerCaseTypesField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_ignoreLowerCase_label);
216     
217         updateControls();
218     }
219     
220     protected Control createContents(Composite parent) {
221         setShell(parent.getShell());
222         
223         fPixelConverter= new PixelConverter(parent);
224     
225         Composite composite= new Composite(parent, SWT.NONE);
226         composite.setFont(parent.getFont());
227         
228         GridLayout layout= new GridLayout();
229         layout.numColumns= 2;
230         layout.marginWidth= 0;
231         layout.marginHeight= 0;
232         
233         composite.setLayout(layout);
234         
235         fOrderListField.doFillIntoGrid(composite, 3);
236         LayoutUtil.setHorizontalSpan(fOrderListField.getLabelControl(null), 2);
237         LayoutUtil.setWidthHint(fOrderListField.getLabelControl(null), fPixelConverter.convertWidthInCharsToPixels(60));
238         LayoutUtil.setHorizontalGrabbing(fOrderListField.getListControl(null));
239         
240         Composite importExportComp= new Composite(composite, SWT.NONE);
241         importExportComp.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
242         layout= new GridLayout();
243         layout.numColumns= 2;
244         layout.marginWidth= 0;
245         layout.marginHeight= 0;
246         
247         importExportComp.setLayout(layout);
248         
249         fImportButton.doFillIntoGrid(importExportComp, 1);
250         fExportButton.doFillIntoGrid(importExportComp, 1);
251         
252         fThresholdField.doFillIntoGrid(composite, 2);
253         ((GridData) fThresholdField.getTextControl(null).getLayoutData()).grabExcessHorizontalSpace= false;
254         fStaticThresholdField.doFillIntoGrid(composite, 2);
255         fIgnoreLowerCaseTypesField.doFillIntoGrid(composite, 2);
256         
257         Dialog.applyDialogFont(composite);
258
259         return composite;
260     }
261     
262     private boolean doThresholdChanged(String JavaDoc thresholdString) {
263         StatusInfo status= new StatusInfo();
264         try {
265             int threshold= Integer.parseInt(thresholdString);
266             if (threshold < 0) {
267                 status.setError(PreferencesMessages.ImportOrganizeConfigurationBlock_error_invalidthreshold);
268             }
269         } catch (NumberFormatException JavaDoc e) {
270             status.setError(PreferencesMessages.ImportOrganizeConfigurationBlock_error_invalidthreshold);
271         }
272         updateStatus(status);
273         return status.isOK();
274     }
275         
276     private void doButtonPressed(int index) {
277         if (index == IDX_ADD || index == IDX_ADD_STATIC) { // add new
278
List JavaDoc existing= fOrderListField.getElements();
279             ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing, index == IDX_ADD_STATIC);
280             if (dialog.open() == Window.OK) {
281                 List JavaDoc selectedElements= fOrderListField.getSelectedElements();
282                 if (selectedElements.size() == 1) {
283                     int insertionIndex= fOrderListField.getIndexOfElement(selectedElements.get(0)) + 1;
284                     fOrderListField.addElement(dialog.getResult(), insertionIndex);
285                 } else {
286                     fOrderListField.addElement(dialog.getResult());
287                 }
288             }
289         } else if (index == IDX_EDIT) { // edit
290
List JavaDoc selected= fOrderListField.getSelectedElements();
291             if (selected.isEmpty()) {
292                 return;
293             }
294             ImportOrderEntry editedEntry= (ImportOrderEntry) selected.get(0);
295             
296             List JavaDoc existing= fOrderListField.getElements();
297             existing.remove(editedEntry);
298             
299             ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing, editedEntry.isStatic);
300             dialog.setInitialSelection(editedEntry);
301             if (dialog.open() == Window.OK) {
302                 fOrderListField.replaceElement(editedEntry, dialog.getResult());
303             }
304         }
305     }
306     
307     
308     /*
309      * The import order file is a property file. The keys are
310      * "0", "1" ... last entry. The values must be valid package names.
311      */

312     private List JavaDoc loadFromProperties(Properties JavaDoc properties) {
313         ArrayList JavaDoc res= new ArrayList JavaDoc();
314         int nEntries= properties.size();
315         for (int i= 0 ; i < nEntries; i++) {
316             String JavaDoc curr= properties.getProperty(String.valueOf(i));
317             if (curr != null) {
318                 ImportOrderEntry entry= ImportOrderEntry.fromSerialized(curr);
319                 if (entry.name.length() == 0 || !JavaConventions.validatePackageName(entry.name, JavaCore.VERSION_1_3, JavaCore.VERSION_1_5).matches(IStatus.ERROR)) {
320                     res.add(entry);
321                 } else {
322                     return null;
323                 }
324             } else {
325                 return res;
326             }
327         }
328         return res;
329     }
330     
331     private List JavaDoc loadImportOrder() {
332         IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
333         
334         FileDialog dialog= new FileDialog(getShell(), SWT.OPEN);
335         dialog.setText(PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_title);
336         dialog.setFilterExtensions(new String JavaDoc[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$
337
String JavaDoc lastPath= dialogSettings.get(DIALOGSETTING_LASTLOADPATH);
338         if (lastPath != null) {
339             dialog.setFilterPath(lastPath);
340         }
341         String JavaDoc fileName= dialog.open();
342         if (fileName != null) {
343             dialogSettings.put(DIALOGSETTING_LASTLOADPATH, dialog.getFilterPath());
344                     
345             Properties JavaDoc properties= new Properties JavaDoc();
346             FileInputStream JavaDoc fis= null;
347             try {
348                 fis= new FileInputStream JavaDoc(fileName);
349                 properties.load(fis);
350                 List JavaDoc res= loadFromProperties(properties);
351                 if (res != null) {
352                     return res;
353                 }
354             } catch (IOException JavaDoc e) {
355                 JavaPlugin.log(e);
356             } finally {
357                 if (fis != null) {
358                     try { fis.close(); } catch (IOException JavaDoc e) {}
359                 }
360             }
361             String JavaDoc title= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_title;
362             String JavaDoc message= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_message;
363             MessageDialog.openError(getShell(), title, message);
364         }
365         return null;
366     }
367     
368     private void saveImportOrder(List JavaDoc elements) {
369         IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
370         
371         FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
372         dialog.setText(PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_title);
373         dialog.setFilterExtensions(new String JavaDoc[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$
374
dialog.setFileName("example.importorder"); //$NON-NLS-1$
375
String JavaDoc lastPath= dialogSettings.get(DIALOGSETTING_LASTSAVEPATH);
376         if (lastPath != null) {
377             dialog.setFilterPath(lastPath);
378         }
379         String JavaDoc fileName= dialog.open();
380         if (fileName != null) {
381             dialogSettings.put(DIALOGSETTING_LASTSAVEPATH, dialog.getFilterPath());
382             
383             Properties JavaDoc properties= new Properties JavaDoc();
384             for (int i= 0; i < elements.size(); i++) {
385                 ImportOrderEntry entry= (ImportOrderEntry) elements.get(i);
386                 properties.setProperty(String.valueOf(i), entry.serialize());
387             }
388             FileOutputStream JavaDoc fos= null;
389             try {
390                 fos= new FileOutputStream JavaDoc(fileName);
391                 properties.store(fos, "Organize Import Order"); //$NON-NLS-1$
392
} catch (IOException JavaDoc e) {
393                 JavaPlugin.log(e);
394                 String JavaDoc title= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_title;
395                 String JavaDoc message= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_message;
396                 MessageDialog.openError(getShell(), title, message);
397             } finally {
398                 if (fos != null) {
399                     try { fos.close(); } catch (IOException JavaDoc e) {}
400                 }
401             }
402         }
403     }
404
405     private void updateStatus(IStatus status) {
406         fContext.statusChanged(status);
407     }
408     
409     /* (non-Javadoc)
410      * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String)
411      */

412     protected void validateSettings(Key changedKey, String JavaDoc oldValue, String JavaDoc newValue) {
413         // no validation
414
}
415
416     /* (non-Javadoc)
417      * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls()
418      */

419     protected void updateControls() {
420         ImportOrderEntry[] importOrder= getImportOrderPreference();
421         int threshold= getImportNumberThreshold(PREF_ONDEMANDTHRESHOLD);
422         int staticThreshold= getImportNumberThreshold(PREF_STATICONDEMANDTHRESHOLD);
423         boolean ignoreLowerCase= Boolean.valueOf(getValue(PREF_IGNORELOWERCASE)).booleanValue();
424         
425         fOrderListField.removeAllElements();
426         for (int i= 0; i < importOrder.length; i++) {
427             fOrderListField.addElement(importOrder[i]);
428         }
429         fThresholdField.setText(String.valueOf(threshold));
430         fStaticThresholdField.setText(String.valueOf(staticThreshold));
431         fIgnoreLowerCaseTypesField.setSelection(ignoreLowerCase);
432     }
433     
434     
435     protected final void doDialogFieldChanged(DialogField field) {
436         // set values in working copy
437
if (field == fOrderListField) {
438             setValue(PREF_IMPORTORDER, packOrderList(fOrderListField.getElements()));
439         } else if (field == fThresholdField) {
440             if (doThresholdChanged(fThresholdField.getText())) {
441                 setValue(PREF_ONDEMANDTHRESHOLD, fThresholdField.getText());
442             }
443         } else if (field == fStaticThresholdField) {
444             if (doThresholdChanged(fStaticThresholdField.getText())) {
445                 setValue(PREF_STATICONDEMANDTHRESHOLD, fStaticThresholdField.getText());
446             }
447         } else if (field == fIgnoreLowerCaseTypesField) {
448             setValue(PREF_IGNORELOWERCASE, fIgnoreLowerCaseTypesField.isSelected());
449         } else if (field == fImportButton) {
450             List JavaDoc order= loadImportOrder();
451             if (order != null) {
452                 fOrderListField.setElements(order);
453             }
454         } else if (field == fExportButton) {
455             saveImportOrder(fOrderListField.getElements());
456         }
457     }
458     
459         
460     /* (non-Javadoc)
461      * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean)
462      */

463     protected String JavaDoc[] getFullBuildDialogStrings(boolean workspaceSettings) {
464         return null; // no build required
465
}
466
467     private static ImportOrderEntry[] unpackOrderList(String JavaDoc str) {
468         ArrayList JavaDoc res= new ArrayList JavaDoc();
469         int start= 0;
470         do {
471             int end= str.indexOf(';', start);
472             if (end == -1) {
473                 end= str.length();
474             }
475             res.add(ImportOrderEntry.fromSerialized(str.substring(start, end)));
476             start= end + 1;
477         } while (start < str.length());
478         
479         return (ImportOrderEntry[]) res.toArray(new ImportOrderEntry[res.size()]);
480     }
481     
482     private static String JavaDoc packOrderList(List JavaDoc orderList) {
483         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
484         for (int i= 0; i < orderList.size(); i++) {
485             ImportOrderEntry entry= (ImportOrderEntry) orderList.get(i);
486             buf.append(entry.serialize());
487             buf.append(';');
488         }
489         return buf.toString();
490     }
491     
492     private ImportOrderEntry[] getImportOrderPreference() {
493         String JavaDoc str= getValue(PREF_IMPORTORDER);
494         if (str != null) {
495             return unpackOrderList(str);
496         }
497         return new ImportOrderEntry[0];
498     }
499     
500     private int getImportNumberThreshold(Key key) {
501         String JavaDoc thresholdStr= getValue(key);
502         try {
503             int threshold= Integer.parseInt(thresholdStr);
504             if (threshold < 0) {
505                 threshold= Integer.MAX_VALUE;
506             }
507             return threshold;
508         } catch (NumberFormatException JavaDoc e) {
509             return Integer.MAX_VALUE;
510         }
511     }
512
513 }
514
515
516
Popular Tags