KickJava   Java API By Example, From Geeks To Geeks.

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


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 // AW
12
package org.eclipse.jdt.internal.ui.preferences;
13
14 import java.io.UnsupportedEncodingException JavaDoc;
15 import java.net.URLDecoder JavaDoc;
16 import java.net.URLEncoder JavaDoc;
17 import java.util.ArrayList JavaDoc;
18 import java.util.NoSuchElementException JavaDoc;
19 import java.util.StringTokenizer JavaDoc;
20
21 import org.eclipse.core.resources.IProject;
22 import org.eclipse.core.resources.IResource;
23 import org.eclipse.core.resources.IWorkspace;
24 import org.eclipse.core.runtime.IPath;
25 import org.eclipse.core.runtime.IStatus;
26 import org.eclipse.core.runtime.Path;
27 import org.eclipse.core.runtime.Status;
28
29 import org.eclipse.swt.SWT;
30 import org.eclipse.swt.events.ModifyEvent;
31 import org.eclipse.swt.events.ModifyListener;
32 import org.eclipse.swt.events.SelectionEvent;
33 import org.eclipse.swt.events.SelectionListener;
34 import org.eclipse.swt.layout.GridData;
35 import org.eclipse.swt.layout.GridLayout;
36 import org.eclipse.swt.widgets.Button;
37 import org.eclipse.swt.widgets.Combo;
38 import org.eclipse.swt.widgets.Composite;
39 import org.eclipse.swt.widgets.Control;
40 import org.eclipse.swt.widgets.Group;
41 import org.eclipse.swt.widgets.Label;
42 import org.eclipse.swt.widgets.Text;
43 import org.eclipse.swt.widgets.Widget;
44
45 import org.eclipse.jface.dialogs.Dialog;
46 import org.eclipse.jface.dialogs.IDialogConstants;
47 import org.eclipse.jface.preference.IPreferenceStore;
48 import org.eclipse.jface.preference.PreferencePage;
49
50 import org.eclipse.ui.IWorkbench;
51 import org.eclipse.ui.IWorkbenchPreferencePage;
52 import org.eclipse.ui.PlatformUI;
53
54 import org.eclipse.jdt.core.IClasspathEntry;
55 import org.eclipse.jdt.core.JavaConventions;
56 import org.eclipse.jdt.core.JavaCore;
57
58 import org.eclipse.jdt.internal.corext.util.Messages;
59
60 import org.eclipse.jdt.ui.JavaUI;
61 import org.eclipse.jdt.ui.PreferenceConstants;
62
63 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
64 import org.eclipse.jdt.internal.ui.JavaPlugin;
65 import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
66 import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
67     
68 /*
69  * The page for defaults for classpath entries in new java projects.
70  * See PreferenceConstants to access or change these values through public API.
71  */

72 public class NewJavaProjectPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
73
74     public static final String JavaDoc ID= "org.eclipse.jdt.ui.preferences.BuildPathPreferencePage"; //$NON-NLS-1$
75

76     private static final String JavaDoc SRCBIN_FOLDERS_IN_NEWPROJ= PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ;
77     private static final String JavaDoc SRCBIN_SRCNAME= PreferenceConstants.SRCBIN_SRCNAME;
78     private static final String JavaDoc SRCBIN_BINNAME= PreferenceConstants.SRCBIN_BINNAME;
79
80     private static final String JavaDoc CLASSPATH_JRELIBRARY_INDEX= PreferenceConstants.NEWPROJECT_JRELIBRARY_INDEX;
81     private static final String JavaDoc CLASSPATH_JRELIBRARY_LIST= PreferenceConstants.NEWPROJECT_JRELIBRARY_LIST;
82
83     
84     private static String JavaDoc fgDefaultEncoding= System.getProperty("file.encoding"); //$NON-NLS-1$
85

86     public static IClasspathEntry[] getDefaultJRELibrary() {
87         IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
88         
89         String JavaDoc str= store.getString(CLASSPATH_JRELIBRARY_LIST);
90         int index= store.getInt(CLASSPATH_JRELIBRARY_INDEX);
91         
92         StringTokenizer JavaDoc tok= new StringTokenizer JavaDoc(str, ";"); //$NON-NLS-1$
93
while (tok.hasMoreTokens() && index > 0) {
94             tok.nextToken();
95             index--;
96         }
97         
98         if (tok.hasMoreTokens()) {
99             IClasspathEntry[] res= decodeJRELibraryClasspathEntries(tok.nextToken());
100             if (res.length > 0) {
101                 return res;
102             }
103         }
104         return new IClasspathEntry[] { getJREContainerEntry() };
105     }
106     
107     // JRE Entry
108

109     public static String JavaDoc decodeJRELibraryDescription(String JavaDoc encoded) {
110         int end= encoded.indexOf(' ');
111         if (end != -1) {
112             return decode(encoded.substring(0, end));
113         }
114         return ""; //$NON-NLS-1$
115
}
116     
117     private static String JavaDoc decode(String JavaDoc str) {
118         try {
119             return URLDecoder.decode(str, fgDefaultEncoding);
120         } catch (UnsupportedEncodingException JavaDoc e) {
121             JavaPlugin.log(e);
122         }
123         return ""; //$NON-NLS-1$
124
}
125     
126     private static String JavaDoc encode(String JavaDoc str) {
127         try {
128             return URLEncoder.encode(str, fgDefaultEncoding);
129         } catch (UnsupportedEncodingException JavaDoc e) {
130             JavaPlugin.log(e);
131         }
132         return ""; //$NON-NLS-1$
133
}
134     
135     public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String JavaDoc encoded) {
136         StringTokenizer JavaDoc tok= new StringTokenizer JavaDoc(encoded, " "); //$NON-NLS-1$
137
ArrayList JavaDoc res= new ArrayList JavaDoc();
138         while (tok.hasMoreTokens()) {
139             try {
140                 tok.nextToken(); // desc: ignore
141
int kind= Integer.parseInt(tok.nextToken());
142                 IPath path= decodePath(tok.nextToken());
143                 IPath attachPath= decodePath(tok.nextToken());
144                 IPath attachRoot= decodePath(tok.nextToken());
145                 boolean isExported= Boolean.valueOf(tok.nextToken()).booleanValue();
146                 switch (kind) {
147                     case IClasspathEntry.CPE_SOURCE:
148                         res.add(JavaCore.newSourceEntry(path));
149                         break;
150                     case IClasspathEntry.CPE_LIBRARY:
151                         res.add(JavaCore.newLibraryEntry(path, attachPath, attachRoot, isExported));
152                         break;
153                     case IClasspathEntry.CPE_VARIABLE:
154                         res.add(JavaCore.newVariableEntry(path, attachPath, attachRoot, isExported));
155                         break;
156                     case IClasspathEntry.CPE_PROJECT:
157                         res.add(JavaCore.newProjectEntry(path, isExported));
158                         break;
159                     case IClasspathEntry.CPE_CONTAINER:
160                         res.add(JavaCore.newContainerEntry(path, isExported));
161                         break;
162                 }
163             } catch (NumberFormatException JavaDoc e) {
164                 String JavaDoc message= PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
165                 JavaPlugin.log(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, e));
166             } catch (NoSuchElementException JavaDoc e) {
167                 String JavaDoc message= PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
168                 JavaPlugin.log(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, e));
169             }
170         }
171         return (IClasspathEntry[]) res.toArray(new IClasspathEntry[res.size()]);
172     }
173     
174     
175     public static String JavaDoc encodeJRELibrary(String JavaDoc desc, IClasspathEntry[] cpentries) {
176         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
177         for (int i= 0; i < cpentries.length; i++) {
178             IClasspathEntry entry= cpentries[i];
179             buf.append(encode(desc));
180             buf.append(' ');
181             buf.append(entry.getEntryKind());
182             buf.append(' ');
183             buf.append(encodePath(entry.getPath()));
184             buf.append(' ');
185             buf.append(encodePath(entry.getSourceAttachmentPath()));
186             buf.append(' ');
187             buf.append(encodePath(entry.getSourceAttachmentRootPath()));
188             buf.append(' ');
189             buf.append(entry.isExported());
190             buf.append(' ');
191         }
192         return buf.toString();
193     }
194     
195     private static String JavaDoc encodePath(IPath path) {
196         if (path == null) {
197             return "#"; //$NON-NLS-1$
198
} else if (path.isEmpty()) {
199             return "&"; //$NON-NLS-1$
200
} else {
201             return encode(path.toPortableString());
202         }
203     }
204     
205     private static IPath decodePath(String JavaDoc str) {
206         if ("#".equals(str)) { //$NON-NLS-1$
207
return null;
208         } else if ("&".equals(str)) { //$NON-NLS-1$
209
return Path.EMPTY;
210         } else {
211             return Path.fromPortableString(decode(str));
212         }
213     }
214     
215     
216     private ArrayList JavaDoc fCheckBoxes;
217     private ArrayList JavaDoc fRadioButtons;
218     private ArrayList JavaDoc fTextControls;
219     
220     private SelectionListener fSelectionListener;
221     private ModifyListener fModifyListener;
222     
223     private Text fBinFolderNameText;
224     private Text fSrcFolderNameText;
225
226     private Combo fJRECombo;
227
228     private Button fProjectAsSourceFolder;
229     private Button fFoldersAsSourceFolder;
230
231     private Label fSrcFolderNameLabel;
232     private Label fBinFolderNameLabel;
233
234     public NewJavaProjectPreferencePage() {
235         super();
236         setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
237         setDescription(PreferencesMessages.NewJavaProjectPreferencePage_description);
238     
239         // title used when opened programatically
240
setTitle(PreferencesMessages.NewJavaProjectPreferencePage_title);
241         
242         fRadioButtons= new ArrayList JavaDoc();
243         fCheckBoxes= new ArrayList JavaDoc();
244         fTextControls= new ArrayList JavaDoc();
245         
246         fSelectionListener= new SelectionListener() {
247             public void widgetDefaultSelected(SelectionEvent e) {}
248
249             public void widgetSelected(SelectionEvent e) {
250                 controlChanged(e.widget);
251             }
252         };
253         
254         fModifyListener= new ModifyListener() {
255             public void modifyText(ModifyEvent e) {
256                 controlModified(e.widget);
257             }
258         };
259         
260     }
261
262     public static void initDefaults(IPreferenceStore store) {
263         store.setDefault(SRCBIN_FOLDERS_IN_NEWPROJ, true);
264         store.setDefault(SRCBIN_SRCNAME, "src"); //$NON-NLS-1$
265
store.setDefault(SRCBIN_BINNAME, "bin"); //$NON-NLS-1$
266

267         store.setDefault(CLASSPATH_JRELIBRARY_LIST, getDefaultJRELibraries());
268         store.setDefault(CLASSPATH_JRELIBRARY_INDEX, 0);
269     }
270     
271     private static String JavaDoc getDefaultJRELibraries() {
272         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
273         IClasspathEntry cntentry= getJREContainerEntry();
274         buf.append(encodeJRELibrary(PreferencesMessages.NewJavaProjectPreferencePage_jre_container_description, new IClasspathEntry[] { cntentry} ));
275         buf.append(';');
276         IClasspathEntry varentry= getJREVariableEntry();
277         buf.append(encodeJRELibrary(PreferencesMessages.NewJavaProjectPreferencePage_jre_variable_description, new IClasspathEntry[] { varentry }));
278         buf.append(';');
279         return buf.toString();
280     }
281     
282     private static IClasspathEntry getJREContainerEntry() {
283         return JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); //$NON-NLS-1$
284
}
285     
286     private static IClasspathEntry getJREVariableEntry() {
287         return JavaCore.newVariableEntry(new Path("JRE_LIB"), new Path("JRE_SRC"), new Path("JRE_SRCROOT")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
288
}
289
290     /*
291      * @see IWorkbenchPreferencePage#init(IWorkbench)
292      */

293     public void init(IWorkbench workbench) {
294     }
295     
296     /**
297      * @see PreferencePage#createControl(Composite)
298      */

299     public void createControl(Composite parent) {
300         super.createControl(parent);
301         PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.NEW_JAVA_PROJECT_PREFERENCE_PAGE);
302     }
303
304
305     private Button addRadioButton(Composite parent, String JavaDoc label, String JavaDoc key, String JavaDoc value, int indent) {
306         GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
307         gd.horizontalSpan= 2;
308         gd.horizontalIndent= indent;
309         
310         Button button= new Button(parent, SWT.RADIO);
311         button.setText(label);
312         button.setData(new String JavaDoc[] { key, value });
313         button.setLayoutData(gd);
314
315         button.setSelection(value.equals(getPreferenceStore().getString(key)));
316         
317         fRadioButtons.add(button);
318         return button;
319     }
320     
321     private Text addTextControl(Composite parent, Label labelControl, String JavaDoc key, int indent) {
322         GridData gd= new GridData();
323         gd.horizontalIndent= indent;
324         
325         labelControl.setLayoutData(gd);
326         
327         gd= new GridData(GridData.FILL_HORIZONTAL);
328         gd.widthHint= convertWidthInCharsToPixels(30);
329         
330         Text text= new Text(parent, SWT.SINGLE | SWT.BORDER);
331         text.setText(getPreferenceStore().getString(key));
332         text.setData(key);
333         text.setLayoutData(gd);
334         
335         fTextControls.add(text);
336         return text;
337     }
338     
339     
340     protected Control createContents(Composite parent) {
341         initializeDialogUnits(parent);
342         
343         Composite result= new Composite(parent, SWT.NONE);
344         GridLayout layout= new GridLayout();
345         layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
346         layout.marginWidth= 0;
347         layout.verticalSpacing= convertVerticalDLUsToPixels(10);
348         layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
349         layout.numColumns= 2;
350         result.setLayout(layout);
351         
352         GridData gd= new GridData(GridData.FILL_HORIZONTAL);
353         gd.horizontalSpan= 2;
354         
355         Group sourceFolderGroup= new Group(result, SWT.NONE);
356         layout= new GridLayout();
357         layout.numColumns= 2;
358         sourceFolderGroup.setLayout(layout);
359         sourceFolderGroup.setLayoutData(gd);
360         sourceFolderGroup.setText(PreferencesMessages.NewJavaProjectPreferencePage_sourcefolder_label);
361         
362         int indent= 0;
363         
364         fProjectAsSourceFolder= addRadioButton(sourceFolderGroup, PreferencesMessages.NewJavaProjectPreferencePage_sourcefolder_project, SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.FALSE, indent);
365         fProjectAsSourceFolder.addSelectionListener(fSelectionListener);
366
367         fFoldersAsSourceFolder= addRadioButton(sourceFolderGroup, PreferencesMessages.NewJavaProjectPreferencePage_sourcefolder_folder, SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.TRUE, indent);
368         fFoldersAsSourceFolder.addSelectionListener(fSelectionListener);
369         
370         indent= convertWidthInCharsToPixels(4);
371
372         fSrcFolderNameLabel= new Label(sourceFolderGroup, SWT.NONE);
373         fSrcFolderNameLabel.setText(PreferencesMessages.NewJavaProjectPreferencePage_folders_src);
374         fSrcFolderNameText= addTextControl(sourceFolderGroup, fSrcFolderNameLabel, SRCBIN_SRCNAME, indent);
375         fSrcFolderNameText.addModifyListener(fModifyListener);
376
377         fBinFolderNameLabel= new Label(sourceFolderGroup, SWT.NONE);
378         fBinFolderNameLabel.setText(PreferencesMessages.NewJavaProjectPreferencePage_folders_bin);
379         fBinFolderNameText= addTextControl(sourceFolderGroup, fBinFolderNameLabel, SRCBIN_BINNAME, indent);
380         fBinFolderNameText.addModifyListener(fModifyListener);
381
382         String JavaDoc[] jreNames= getJRENames();
383         if (jreNames.length > 0) {
384             Label jreSelectionLabel= new Label(result, SWT.NONE);
385             jreSelectionLabel.setText(PreferencesMessages.NewJavaProjectPreferencePage_jrelibrary_label);
386             jreSelectionLabel.setLayoutData(new GridData());
387         
388             int index= getPreferenceStore().getInt(CLASSPATH_JRELIBRARY_INDEX);
389             fJRECombo= new Combo(result, SWT.READ_ONLY);
390             fJRECombo.setItems(jreNames);
391             fJRECombo.select(index);
392             fJRECombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
393         }
394                     
395         validateFolders();
396     
397         Dialog.applyDialogFont(result);
398         return result;
399     }
400     
401     private void validateFolders() {
402         boolean useFolders= fFoldersAsSourceFolder.getSelection();
403         
404         fSrcFolderNameText.setEnabled(useFolders);
405         fBinFolderNameText.setEnabled(useFolders);
406         fSrcFolderNameLabel.setEnabled(useFolders);
407         fBinFolderNameLabel.setEnabled(useFolders);
408         if (useFolders) {
409             String JavaDoc srcName= fSrcFolderNameText.getText();
410             String JavaDoc binName= fBinFolderNameText.getText();
411             if (srcName.length() + binName.length() == 0) {
412                 updateStatus(new StatusInfo(IStatus.ERROR, PreferencesMessages.NewJavaProjectPreferencePage_folders_error_namesempty));
413                 return;
414             }
415             IWorkspace workspace= JavaPlugin.getWorkspace();
416             IProject dmy= workspace.getRoot().getProject("project"); //$NON-NLS-1$
417

418             IStatus status;
419             IPath srcPath= dmy.getFullPath().append(srcName);
420             if (srcName.length() != 0) {
421                 status= workspace.validatePath(srcPath.toString(), IResource.FOLDER);
422                 if (!status.isOK()) {
423                     String JavaDoc message= Messages.format(PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidsrcname, status.getMessage());
424                     updateStatus(new StatusInfo(IStatus.ERROR, message));
425                     return;
426                 }
427             }
428             IPath binPath= dmy.getFullPath().append(binName);
429             if (binName.length() != 0) {
430                 status= workspace.validatePath(binPath.toString(), IResource.FOLDER);
431                 if (!status.isOK()) {
432                     String JavaDoc message= Messages.format(PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidbinname, status.getMessage());
433                     updateStatus(new StatusInfo(IStatus.ERROR, message));
434                     return;
435                 }
436             }
437             IClasspathEntry entry= JavaCore.newSourceEntry(srcPath);
438             status= JavaConventions.validateClasspath(JavaCore.create(dmy), new IClasspathEntry[] { entry }, binPath);
439             if (!status.isOK()) {
440                 String JavaDoc message= PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidcp;
441                 updateStatus(new StatusInfo(IStatus.ERROR, message));
442                 return;
443             }
444         }
445         updateStatus(new StatusInfo()); // set to OK
446
}
447         
448     private void updateStatus(IStatus status) {
449         setValid(!status.matches(IStatus.ERROR));
450         StatusUtil.applyToStatusLine(this, status);
451     }
452     
453     private void controlChanged(Widget widget) {
454         if (widget == fFoldersAsSourceFolder || widget == fProjectAsSourceFolder) {
455             validateFolders();
456         }
457     }
458     
459     private void controlModified(Widget widget) {
460         if (widget == fSrcFolderNameText || widget == fBinFolderNameText) {
461             validateFolders();
462         }
463     }
464     
465     /*
466      * @see PreferencePage#performDefaults()
467      */

468     protected void performDefaults() {
469         IPreferenceStore store= getPreferenceStore();
470         for (int i= 0; i < fCheckBoxes.size(); i++) {
471             Button button= (Button) fCheckBoxes.get(i);
472             String JavaDoc key= (String JavaDoc) button.getData();
473             button.setSelection(store.getDefaultBoolean(key));
474         }
475         for (int i= 0; i < fRadioButtons.size(); i++) {
476             Button button= (Button) fRadioButtons.get(i);
477             String JavaDoc[] info= (String JavaDoc[]) button.getData();
478             button.setSelection(info[1].equals(store.getDefaultString(info[0])));
479         }
480         for (int i= 0; i < fTextControls.size(); i++) {
481             Text text= (Text) fTextControls.get(i);
482             String JavaDoc key= (String JavaDoc) text.getData();
483             text.setText(store.getDefaultString(key));
484         }
485         if (fJRECombo != null) {
486             fJRECombo.select(store.getDefaultInt(CLASSPATH_JRELIBRARY_INDEX));
487         }
488         
489         validateFolders();
490         super.performDefaults();
491     }
492
493     /*
494      * @see IPreferencePage#performOk()
495      */

496     public boolean performOk() {
497         IPreferenceStore store= getPreferenceStore();
498         for (int i= 0; i < fCheckBoxes.size(); i++) {
499             Button button= (Button) fCheckBoxes.get(i);
500             String JavaDoc key= (String JavaDoc) button.getData();
501             store.setValue(key, button.getSelection());
502         }
503         for (int i= 0; i < fRadioButtons.size(); i++) {
504             Button button= (Button) fRadioButtons.get(i);
505             if (button.getSelection()) {
506                 String JavaDoc[] info= (String JavaDoc[]) button.getData();
507                 store.setValue(info[0], info[1]);
508             }
509         }
510         for (int i= 0; i < fTextControls.size(); i++) {
511             Text text= (Text) fTextControls.get(i);
512             String JavaDoc key= (String JavaDoc) text.getData();
513             store.setValue(key, text.getText());
514         }
515         
516         if (fJRECombo != null) {
517             store.setValue(CLASSPATH_JRELIBRARY_INDEX, fJRECombo.getSelectionIndex());
518         }
519         
520         JavaPlugin.getDefault().savePluginPreferences();
521         return super.performOk();
522     }
523     
524     private String JavaDoc[] getJRENames() {
525         String JavaDoc prefString= getPreferenceStore().getString(CLASSPATH_JRELIBRARY_LIST);
526         ArrayList JavaDoc list= new ArrayList JavaDoc();
527         StringTokenizer JavaDoc tok= new StringTokenizer JavaDoc(prefString, ";"); //$NON-NLS-1$
528
while (tok.hasMoreTokens()) {
529             list.add(decodeJRELibraryDescription(tok.nextToken()));
530         }
531         return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
532     }
533
534 }
535
536
537
Popular Tags