KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > wizards > buildpaths > BuildPathsBlock


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.wizards.buildpaths;
12
13 import java.net.URI JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.List JavaDoc;
17
18 import org.eclipse.core.runtime.CoreException;
19 import org.eclipse.core.runtime.IPath;
20 import org.eclipse.core.runtime.IProgressMonitor;
21 import org.eclipse.core.runtime.IStatus;
22 import org.eclipse.core.runtime.NullProgressMonitor;
23 import org.eclipse.core.runtime.OperationCanceledException;
24 import org.eclipse.core.runtime.Path;
25 import org.eclipse.core.runtime.SubProgressMonitor;
26
27 import org.eclipse.core.resources.IContainer;
28 import org.eclipse.core.resources.IFile;
29 import org.eclipse.core.resources.IFolder;
30 import org.eclipse.core.resources.IProject;
31 import org.eclipse.core.resources.IProjectDescription;
32 import org.eclipse.core.resources.IResource;
33 import org.eclipse.core.resources.IWorkspaceRoot;
34 import org.eclipse.core.resources.ResourcesPlugin;
35
36 import org.eclipse.swt.SWT;
37 import org.eclipse.swt.events.SelectionAdapter;
38 import org.eclipse.swt.events.SelectionEvent;
39 import org.eclipse.swt.graphics.Image;
40 import org.eclipse.swt.layout.GridData;
41 import org.eclipse.swt.layout.GridLayout;
42 import org.eclipse.swt.widgets.Composite;
43 import org.eclipse.swt.widgets.Control;
44 import org.eclipse.swt.widgets.Display;
45 import org.eclipse.swt.widgets.Shell;
46 import org.eclipse.swt.widgets.TabFolder;
47 import org.eclipse.swt.widgets.TabItem;
48 import org.eclipse.swt.widgets.Widget;
49
50 import org.eclipse.jface.dialogs.Dialog;
51 import org.eclipse.jface.dialogs.IDialogConstants;
52 import org.eclipse.jface.dialogs.MessageDialog;
53 import org.eclipse.jface.operation.IRunnableContext;
54 import org.eclipse.jface.preference.IPreferenceStore;
55 import org.eclipse.jface.viewers.ILabelProvider;
56 import org.eclipse.jface.viewers.ITreeContentProvider;
57 import org.eclipse.jface.viewers.ViewerFilter;
58 import org.eclipse.jface.window.Window;
59
60 import org.eclipse.ui.IWorkbench;
61 import org.eclipse.ui.dialogs.ISelectionStatusValidator;
62 import org.eclipse.ui.model.WorkbenchContentProvider;
63 import org.eclipse.ui.model.WorkbenchLabelProvider;
64 import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
65
66 import org.eclipse.ui.views.navigator.ResourceComparator;
67
68 import org.eclipse.ui.ide.IDE;
69
70 import org.eclipse.jdt.core.IClasspathEntry;
71 import org.eclipse.jdt.core.IJavaModelStatus;
72 import org.eclipse.jdt.core.IJavaProject;
73 import org.eclipse.jdt.core.JavaConventions;
74 import org.eclipse.jdt.core.JavaCore;
75
76 import org.eclipse.jdt.internal.corext.util.Messages;
77
78 import org.eclipse.jdt.ui.PreferenceConstants;
79
80 import org.eclipse.jdt.internal.ui.JavaPlugin;
81 import org.eclipse.jdt.internal.ui.JavaPluginImages;
82 import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
83 import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
84 import org.eclipse.jdt.internal.ui.util.CoreUtility;
85 import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer;
86 import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
87 import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
88 import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
89 import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
90 import org.eclipse.jdt.internal.ui.wizards.buildpaths.newsourcepage.NewSourceContainerWorkbookPage;
91 import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
92 import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
93 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
94 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
95 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
96 import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
97 import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
98
99 public class BuildPathsBlock {
100
101     public static interface IRemoveOldBinariesQuery {
102         
103         /**
104          * Do the callback. Returns <code>true</code> if .class files should be removed from the
105          * old output location.
106          * @param removeLocation true if the folder at oldOutputLocation should be removed, false if only its content
107          * @param oldOutputLocation The old output location
108          * @return Returns true if .class files should be removed.
109          * @throws OperationCanceledException
110          */

111         boolean doQuery(boolean removeLocation, IPath oldOutputLocation) throws OperationCanceledException;
112         
113     }
114
115
116     private IWorkspaceRoot fWorkspaceRoot;
117
118     private CheckedListDialogField fClassPathList;
119     private StringButtonDialogField fBuildPathDialogField;
120     
121     private StatusInfo fClassPathStatus;
122     private StatusInfo fOutputFolderStatus;
123     private StatusInfo fBuildPathStatus;
124
125     private IJavaProject fCurrJProject;
126         
127     private IPath fOutputLocationPath;
128     
129     private IStatusChangeListener fContext;
130     private Control fSWTWidget;
131     private TabFolder fTabFolder;
132     
133     private int fPageIndex;
134     
135     private BuildPathBasePage fSourceContainerPage;
136     private ProjectsWorkbookPage fProjectsPage;
137     private LibrariesWorkbookPage fLibrariesPage;
138     
139     private BuildPathBasePage fCurrPage;
140     
141     private String JavaDoc fUserSettingsTimeStamp;
142     private long fFileTimeStamp;
143     
144     private IRunnableContext fRunnableContext;
145     private boolean fUseNewPage;
146
147     private final IWorkbenchPreferenceContainer fPageContainer; // null when invoked from a non-property page context
148

149     private final static int IDX_UP= 0;
150     private final static int IDX_DOWN= 1;
151     private final static int IDX_TOP= 3;
152     private final static int IDX_BOTTOM= 4;
153     private final static int IDX_SELECT_ALL= 6;
154     private final static int IDX_UNSELECT_ALL= 7;
155     
156     public BuildPathsBlock(IRunnableContext runnableContext, IStatusChangeListener context, int pageToShow, boolean useNewPage, IWorkbenchPreferenceContainer pageContainer) {
157         fPageContainer= pageContainer;
158         fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot();
159         fContext= context;
160         fUseNewPage= useNewPage;
161         
162         fPageIndex= pageToShow;
163         
164         fSourceContainerPage= null;
165         fLibrariesPage= null;
166         fProjectsPage= null;
167         fCurrPage= null;
168         fRunnableContext= runnableContext;
169                 
170         BuildPathAdapter adapter= new BuildPathAdapter();
171     
172         String JavaDoc[] buttonLabels= new String JavaDoc[] {
173             /* IDX_UP */ NewWizardMessages.BuildPathsBlock_classpath_up_button,
174             /* IDX_DOWN */ NewWizardMessages.BuildPathsBlock_classpath_down_button,
175             /* 2 */ null,
176             /* IDX_TOP */ NewWizardMessages.BuildPathsBlock_classpath_top_button,
177             /* IDX_BOTTOM */ NewWizardMessages.BuildPathsBlock_classpath_bottom_button,
178             /* 5 */ null,
179             /* IDX_SELECT_ALL */ NewWizardMessages.BuildPathsBlock_classpath_checkall_button,
180             /* IDX_UNSELECT_ALL */ NewWizardMessages.BuildPathsBlock_classpath_uncheckall_button
181         
182         };
183         
184         fClassPathList= new CheckedListDialogField(adapter, buttonLabels, new CPListLabelProvider());
185         fClassPathList.setDialogFieldListener(adapter);
186         fClassPathList.setLabelText(NewWizardMessages.BuildPathsBlock_classpath_label);
187         fClassPathList.setUpButtonIndex(IDX_UP);
188         fClassPathList.setDownButtonIndex(IDX_DOWN);
189         fClassPathList.setCheckAllButtonIndex(IDX_SELECT_ALL);
190         fClassPathList.setUncheckAllButtonIndex(IDX_UNSELECT_ALL);
191         
192         fBuildPathDialogField= new StringButtonDialogField(adapter);
193         fBuildPathDialogField.setButtonLabel(NewWizardMessages.BuildPathsBlock_buildpath_button);
194         fBuildPathDialogField.setDialogFieldListener(adapter);
195         fBuildPathDialogField.setLabelText(NewWizardMessages.BuildPathsBlock_buildpath_label);
196
197         fBuildPathStatus= new StatusInfo();
198         fClassPathStatus= new StatusInfo();
199         fOutputFolderStatus= new StatusInfo();
200         
201         fCurrJProject= null;
202     }
203     
204     // -------- UI creation ---------
205

206     public Control createControl(Composite parent) {
207         fSWTWidget= parent;
208         
209         Composite composite= new Composite(parent, SWT.NONE);
210         composite.setFont(parent.getFont());
211         
212         GridLayout layout= new GridLayout();
213         layout.marginWidth= 0;
214         layout.marginHeight= 0;
215         layout.numColumns= 1;
216         composite.setLayout(layout);
217         
218         TabFolder folder= new TabFolder(composite, SWT.NONE);
219         folder.setLayoutData(new GridData(GridData.FILL_BOTH));
220         folder.setFont(composite.getFont());
221         
222         TabItem item;
223         item= new TabItem(folder, SWT.NONE);
224         item.setText(NewWizardMessages.BuildPathsBlock_tab_source);
225         item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT));
226         
227         if (fUseNewPage) {
228             fSourceContainerPage= new NewSourceContainerWorkbookPage(fClassPathList, fBuildPathDialogField, fRunnableContext, this);
229         } else {
230             fSourceContainerPage= new SourceContainerWorkbookPage(fClassPathList, fBuildPathDialogField);
231         }
232         item.setData(fSourceContainerPage);
233         item.setControl(fSourceContainerPage.getControl(folder));
234         
235         IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
236         Image projectImage= workbench.getSharedImages().getImage(IDE.SharedImages.IMG_OBJ_PROJECT);
237         
238         fProjectsPage= new ProjectsWorkbookPage(fClassPathList, fPageContainer);
239         item= new TabItem(folder, SWT.NONE);
240         item.setText(NewWizardMessages.BuildPathsBlock_tab_projects);
241         item.setImage(projectImage);
242         item.setData(fProjectsPage);
243         item.setControl(fProjectsPage.getControl(folder));
244         
245         fLibrariesPage= new LibrariesWorkbookPage(fClassPathList, fPageContainer);
246         item= new TabItem(folder, SWT.NONE);
247         item.setText(NewWizardMessages.BuildPathsBlock_tab_libraries);
248         item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_LIBRARY));
249         item.setData(fLibrariesPage);
250         item.setControl(fLibrariesPage.getControl(folder));
251         
252         // a non shared image
253
Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
254         composite.addDisposeListener(new ImageDisposer(cpoImage));
255         
256         ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList);
257         item= new TabItem(folder, SWT.NONE);
258         item.setText(NewWizardMessages.BuildPathsBlock_tab_order);
259         item.setImage(cpoImage);
260         item.setData(ordpage);
261         item.setControl(ordpage.getControl(folder));
262                 
263         if (fCurrJProject != null) {
264             fSourceContainerPage.init(fCurrJProject);
265             fLibrariesPage.init(fCurrJProject);
266             fProjectsPage.init(fCurrJProject);
267         }
268         
269         folder.setSelection(fPageIndex);
270         fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData();
271         folder.addSelectionListener(new SelectionAdapter() {
272             public void widgetSelected(SelectionEvent e) {
273                 tabChanged(e.item);
274             }
275         });
276         fTabFolder= folder;
277
278         Dialog.applyDialogFont(composite);
279         return composite;
280     }
281     
282     private Shell getShell() {
283         if (fSWTWidget != null) {
284             return fSWTWidget.getShell();
285         }
286         return JavaPlugin.getActiveWorkbenchShell();
287     }
288     
289     /**
290      * Initializes the classpath for the given project. Multiple calls to init are allowed,
291      * but all existing settings will be cleared and replace by the given or default paths.
292      * @param jproject The java project to configure. Does not have to exist.
293      * @param outputLocation The output location to be set in the page. If <code>null</code>
294      * is passed, jdt default settings are used, or - if the project is an existing Java project- the
295      * output location of the existing project
296      * @param classpathEntries The classpath entries to be set in the page. If <code>null</code>
297      * is passed, jdt default settings are used, or - if the project is an existing Java project - the
298      * classpath entries of the existing project
299      */

300     public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) {
301         fCurrJProject= jproject;
302         boolean projectExists= false;
303         List JavaDoc newClassPath= null;
304         IProject project= fCurrJProject.getProject();
305         projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$
306
if (projectExists) {
307             if (outputLocation == null) {
308                 outputLocation= fCurrJProject.readOutputLocation();
309             }
310             if (classpathEntries == null) {
311                 classpathEntries= fCurrJProject.readRawClasspath();
312             }
313         }
314         if (outputLocation == null) {
315             outputLocation= getDefaultOutputLocation(jproject);
316         }
317
318         if (classpathEntries != null) {
319             newClassPath= getExistingEntries(classpathEntries);
320         }
321         if (newClassPath == null) {
322             newClassPath= getDefaultClassPath(jproject);
323         }
324         
325         List JavaDoc exportedEntries = new ArrayList JavaDoc();
326         for (int i= 0; i < newClassPath.size(); i++) {
327             CPListElement curr= (CPListElement) newClassPath.get(i);
328             if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
329                 exportedEntries.add(curr);
330             }
331         }
332         
333         // inits the dialog field
334
fBuildPathDialogField.setText(outputLocation.makeRelative().toString());
335         fBuildPathDialogField.enableButton(project.exists());
336         fClassPathList.setElements(newClassPath);
337         fClassPathList.setCheckedElements(exportedEntries);
338         
339         fClassPathList.selectFirstElement();
340         
341         if (fSourceContainerPage != null) {
342             fSourceContainerPage.init(fCurrJProject);
343             fProjectsPage.init(fCurrJProject);
344             fLibrariesPage.init(fCurrJProject);
345         }
346         
347         initializeTimeStamps();
348         updateUI();
349     }
350     
351     protected void updateUI() {
352         if (fSWTWidget == null || fSWTWidget.isDisposed()) {
353             return;
354         }
355         
356         if (Display.getCurrent() != null) {
357             doUpdateUI();
358         } else {
359             Display.getDefault().asyncExec(new Runnable JavaDoc() {
360                 public void run() {
361                     if (fSWTWidget == null || fSWTWidget.isDisposed()) {
362                         return;
363                     }
364                     doUpdateUI();
365                 }
366             });
367         }
368     }
369
370     protected void doUpdateUI() {
371         fBuildPathDialogField.refresh();
372         fClassPathList.refresh();
373     
374         doStatusLineUpdate();
375     }
376     
377     private String JavaDoc getEncodedSettings() {
378         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
379         CPListElement.appendEncodePath(fOutputLocationPath, buf).append(';');
380
381         int nElements= fClassPathList.getSize();
382         buf.append('[').append(nElements).append(']');
383         for (int i= 0; i < nElements; i++) {
384             CPListElement elem= (CPListElement) fClassPathList.getElement(i);
385             elem.appendEncodedSettings(buf);
386         }
387         return buf.toString();
388     }
389     
390     public boolean hasChangesInDialog() {
391         String JavaDoc currSettings= getEncodedSettings();
392         return !currSettings.equals(fUserSettingsTimeStamp);
393     }
394     
395     public boolean hasChangesInClasspathFile() {
396         IFile file= fCurrJProject.getProject().getFile(".classpath"); //$NON-NLS-1$
397
return fFileTimeStamp != file.getModificationStamp();
398     }
399     
400     public boolean isClassfileMissing() {
401         return !fCurrJProject.getProject().getFile(".classpath").exists(); //$NON-NLS-1$
402
}
403     
404     public void initializeTimeStamps() {
405         IFile file= fCurrJProject.getProject().getFile(".classpath"); //$NON-NLS-1$
406
fFileTimeStamp= file.getModificationStamp();
407         fUserSettingsTimeStamp= getEncodedSettings();
408     }
409
410     private ArrayList JavaDoc getExistingEntries(IClasspathEntry[] classpathEntries) {
411         ArrayList JavaDoc newClassPath= new ArrayList JavaDoc();
412         for (int i= 0; i < classpathEntries.length; i++) {
413             IClasspathEntry curr= classpathEntries[i];
414             newClassPath.add(CPListElement.createFromExisting(curr, fCurrJProject));
415         }
416         return newClassPath;
417     }
418     
419     // -------- public api --------
420

421     /**
422      * @return Returns the Java project. Can return <code>null<code> if the page has not
423      * been initialized.
424      */

425     public IJavaProject getJavaProject() {
426         return fCurrJProject;
427     }
428     
429     /**
430      * @return Returns the current output location. Note that the path returned must not be valid.
431      */

432     public IPath getOutputLocation() {
433         return new Path(fBuildPathDialogField.getText()).makeAbsolute();
434     }
435     
436     /**
437      * @return Returns the current class path (raw). Note that the entries returned must not be valid.
438      */

439     public IClasspathEntry[] getRawClassPath() {
440         List JavaDoc elements= fClassPathList.getElements();
441         int nElements= elements.size();
442         IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
443
444         for (int i= 0; i < nElements; i++) {
445             CPListElement currElement= (CPListElement) elements.get(i);
446             entries[i]= currElement.getClasspathEntry();
447         }
448         return entries;
449     }
450     
451     public int getPageIndex() {
452         return fPageIndex;
453     }
454     
455     
456     // -------- evaluate default settings --------
457

458     private List JavaDoc getDefaultClassPath(IJavaProject jproj) {
459         List JavaDoc list= new ArrayList JavaDoc();
460         IResource srcFolder;
461         IPreferenceStore store= PreferenceConstants.getPreferenceStore();
462         String JavaDoc sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME);
463         if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
464             srcFolder= jproj.getProject().getFolder(sourceFolderName);
465         } else {
466             srcFolder= jproj.getProject();
467         }
468
469         list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
470
471         IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
472         list.addAll(getExistingEntries(jreEntries));
473         return list;
474     }
475     
476     public static IPath getDefaultOutputLocation(IJavaProject jproj) {
477         IPreferenceStore store= PreferenceConstants.getPreferenceStore();
478         if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) {
479             String JavaDoc outputLocationName= store.getString(PreferenceConstants.SRCBIN_BINNAME);
480             return jproj.getProject().getFullPath().append(outputLocationName);
481         } else {
482             return jproj.getProject().getFullPath();
483         }
484     }
485         
486     private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
487
488         // -------- IStringButtonAdapter --------
489
public void changeControlPressed(DialogField field) {
490             buildPathChangeControlPressed(field);
491         }
492         
493         // ---------- IDialogFieldListener --------
494
public void dialogFieldChanged(DialogField field) {
495             buildPathDialogFieldChanged(field);
496         }
497
498         // ---------- IListAdapter --------
499
public void customButtonPressed(ListDialogField field, int index) {
500             buildPathCustomButtonPressed(field, index);
501         }
502
503         public void doubleClicked(ListDialogField field) {
504         }
505
506         public void selectionChanged(ListDialogField field) {
507             updateTopButtonEnablement();
508         }
509     }
510     
511     private void buildPathChangeControlPressed(DialogField field) {
512         if (field == fBuildPathDialogField) {
513             IContainer container= chooseContainer();
514             if (container != null) {
515                 fBuildPathDialogField.setText(container.getFullPath().makeRelative().toString());
516             }
517         }
518     }
519     
520     public void updateTopButtonEnablement() {
521         fClassPathList.enableButton(IDX_BOTTOM, fClassPathList.canMoveDown());
522         fClassPathList.enableButton(IDX_TOP, fClassPathList.canMoveUp());
523     }
524
525     public void buildPathCustomButtonPressed(ListDialogField field, int index) {
526         List JavaDoc elems= field.getSelectedElements();
527         field.removeElements(elems);
528         if (index == IDX_BOTTOM) {
529             field.addElements(elems);
530         } else if (index == IDX_TOP) {
531             field.addElements(elems, 0);
532         }
533     }
534
535     private void buildPathDialogFieldChanged(DialogField field) {
536         if (field == fClassPathList) {
537             updateClassPathStatus();
538             updateTopButtonEnablement();
539         } else if (field == fBuildPathDialogField) {
540             updateOutputLocationStatus();
541         }
542         doStatusLineUpdate();
543     }
544     
545
546     
547     // -------- verification -------------------------------
548

549     private void doStatusLineUpdate() {
550         if (Display.getCurrent() != null) {
551             IStatus res= findMostSevereStatus();
552             fContext.statusChanged(res);
553         }
554     }
555     
556     private IStatus findMostSevereStatus() {
557         return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fOutputFolderStatus, fBuildPathStatus });
558     }
559     
560     
561     /**
562      * Validates the build path.
563      */

564     public void updateClassPathStatus() {
565         fClassPathStatus.setOK();
566         
567         List JavaDoc elements= fClassPathList.getElements();
568     
569         CPListElement entryMissing= null;
570         CPListElement entryDeprecated= null;
571         int nEntriesMissing= 0;
572         IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
573
574         for (int i= elements.size()-1 ; i >= 0 ; i--) {
575             CPListElement currElement= (CPListElement)elements.get(i);
576             boolean isChecked= fClassPathList.isChecked(currElement);
577             if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
578                 if (!isChecked) {
579                     fClassPathList.setCheckedWithoutUpdate(currElement, true);
580                 }
581                 if (!fClassPathList.isGrayed(currElement)) {
582                     fClassPathList.setGrayedWithoutUpdate(currElement, true);
583                 }
584             } else {
585                 currElement.setExported(isChecked);
586             }
587
588             entries[i]= currElement.getClasspathEntry();
589             if (currElement.isMissing()) {
590                 nEntriesMissing++;
591                 if (entryMissing == null) {
592                     entryMissing= currElement;
593                 }
594             }
595             if (entryDeprecated == null & currElement.isDeprecated()) {
596                 entryDeprecated= currElement;
597             }
598         }
599                 
600         if (nEntriesMissing > 0) {
601             if (nEntriesMissing == 1) {
602                 fClassPathStatus.setWarning(Messages.format(NewWizardMessages.BuildPathsBlock_warning_EntryMissing, entryMissing.getPath().toString()));
603             } else {
604                 fClassPathStatus.setWarning(Messages.format(NewWizardMessages.BuildPathsBlock_warning_EntriesMissing, String.valueOf(nEntriesMissing)));
605             }
606         } else if (entryDeprecated != null) {
607             fClassPathStatus.setInfo(entryDeprecated.getDeprecationMessage());
608         }
609                 
610 /* if (fCurrJProject.hasClasspathCycle(entries)) {
611             fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
612         }
613 */

614         updateBuildPathStatus();
615     }
616
617     /**
618      * Validates output location & build path.
619      */

620     private void updateOutputLocationStatus() {
621         fOutputLocationPath= null;
622         
623         String JavaDoc text= fBuildPathDialogField.getText();
624         if ("".equals(text)) { //$NON-NLS-1$
625
fOutputFolderStatus.setError(NewWizardMessages.BuildPathsBlock_error_EnterBuildPath);
626             return;
627         }
628         IPath path= getOutputLocation();
629         fOutputLocationPath= path;
630         
631         IResource res= fWorkspaceRoot.findMember(path);
632         if (res != null) {
633             // if exists, must be a folder or project
634
if (res.getType() == IResource.FILE) {
635                 fOutputFolderStatus.setError(NewWizardMessages.BuildPathsBlock_error_InvalidBuildPath);
636                 return;
637             }
638         }
639         
640         fOutputFolderStatus.setOK();
641         
642         String JavaDoc pathStr= fBuildPathDialogField.getText();
643         Path outputPath= (new Path(pathStr));
644         pathStr= outputPath.lastSegment();
645         if (pathStr.equals(".settings") && outputPath.segmentCount() == 2) { //$NON-NLS-1$
646
fOutputFolderStatus.setWarning(NewWizardMessages.OutputLocation_SettingsAsLocation);
647         }
648         
649         if (pathStr.charAt(0) == '.' && pathStr.length() > 1) {
650             fOutputFolderStatus.setWarning(Messages.format(NewWizardMessages.OutputLocation_DotAsLocation, pathStr));
651         }
652         
653         updateBuildPathStatus();
654     }
655         
656     private void updateBuildPathStatus() {
657         List JavaDoc elements= fClassPathList.getElements();
658         IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
659     
660         for (int i= elements.size()-1 ; i >= 0 ; i--) {
661             CPListElement currElement= (CPListElement)elements.get(i);
662             entries[i]= currElement.getClasspathEntry();
663         }
664         
665         IJavaModelStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, fOutputLocationPath);
666         if (!status.isOK()) {
667             fBuildPathStatus.setError(status.getMessage());
668             return;
669         }
670         fBuildPathStatus.setOK();
671     }
672     
673     // -------- creation -------------------------------
674

675     public static void createProject(IProject project, URI JavaDoc locationURI, IProgressMonitor monitor) throws CoreException {
676         if (monitor == null) {
677             monitor= new NullProgressMonitor();
678         }
679         monitor.beginTask(NewWizardMessages.BuildPathsBlock_operationdesc_project, 10);
680
681         // create the project
682
try {
683             if (!project.exists()) {
684                 IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName());
685                 if (locationURI != null && ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(locationURI)) {
686                     locationURI= null;
687                 }
688                 desc.setLocationURI(locationURI);
689                 project.create(desc, monitor);
690                 monitor= null;
691             }
692             if (!project.isOpen()) {
693                 project.open(monitor);
694                 monitor= null;
695             }
696         } finally {
697             if (monitor != null) {
698                 monitor.done();
699             }
700         }
701     }
702
703     public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException {
704         if (monitor != null && monitor.isCanceled()) {
705             throw new OperationCanceledException();
706         }
707         if (!project.hasNature(JavaCore.NATURE_ID)) {
708             IProjectDescription description = project.getDescription();
709             String JavaDoc[] prevNatures= description.getNatureIds();
710             String JavaDoc[] newNatures= new String JavaDoc[prevNatures.length + 1];
711             System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
712             newNatures[prevNatures.length]= JavaCore.NATURE_ID;
713             description.setNatureIds(newNatures);
714             project.setDescription(description, monitor);
715         } else {
716             if (monitor != null) {
717                 monitor.worked(1);
718             }
719         }
720     }
721     
722     public void configureJavaProject(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
723         
724         flush(fClassPathList.getElements(), getOutputLocation(), getJavaProject(), monitor);
725         initializeTimeStamps();
726         
727         updateUI();
728     }
729         
730     /*
731      * Creates the Java project and sets the configured build path and output location.
732      * If the project already exists only build paths are updated.
733      */

734     public static void flush(List JavaDoc classPathEntries, IPath outputLocation, IJavaProject javaProject, IProgressMonitor monitor) throws CoreException, OperationCanceledException {
735         if (monitor == null) {
736             monitor= new NullProgressMonitor();
737         }
738         monitor.setTaskName(NewWizardMessages.BuildPathsBlock_operationdesc_java);
739         monitor.beginTask("", classPathEntries.size() * 4 + 4); //$NON-NLS-1$
740
try {
741             
742             IProject project= javaProject.getProject();
743             IPath projPath= project.getFullPath();
744             
745             IPath oldOutputLocation;
746             try {
747                 oldOutputLocation= javaProject.getOutputLocation();
748             } catch (CoreException e) {
749                 oldOutputLocation= projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
750             }
751             
752             if (oldOutputLocation.equals(projPath) && !outputLocation.equals(projPath)) {
753                 if (BuildPathsBlock.hasClassfiles(project)) {
754                     if (BuildPathsBlock.getRemoveOldBinariesQuery(JavaPlugin.getActiveWorkbenchShell()).doQuery(false, projPath)) {
755                         BuildPathsBlock.removeOldClassfiles(project);
756                     }
757                 }
758             } else if (!outputLocation.equals(oldOutputLocation)) {
759                 IFolder folder= ResourcesPlugin.getWorkspace().getRoot().getFolder(oldOutputLocation);
760                 if (folder.exists()) {
761                     if (folder.members().length == 0) {
762                         BuildPathsBlock.removeOldClassfiles(folder);
763                     } else {
764                         if (BuildPathsBlock.getRemoveOldBinariesQuery(JavaPlugin.getActiveWorkbenchShell()).doQuery(true, oldOutputLocation)) {
765                             BuildPathsBlock.removeOldClassfiles(folder);
766                         }
767                     }
768                 }
769             }
770             
771             monitor.worked(1);
772             
773             IWorkspaceRoot fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot();
774             
775             //create and set the output path first
776
if (!fWorkspaceRoot.exists(outputLocation)) {
777                 IFolder folder= fWorkspaceRoot.getFolder(outputLocation);
778                 CoreUtility.createDerivedFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
779                 folder.setDerived(true);
780             } else {
781                 monitor.worked(1);
782             }
783             if (monitor.isCanceled()) {
784                 throw new OperationCanceledException();
785             }
786             
787             int nEntries= classPathEntries.size();
788             IClasspathEntry[] classpath= new IClasspathEntry[nEntries];
789             int i= 0;
790             
791             for (Iterator JavaDoc iter= classPathEntries.iterator(); iter.hasNext();) {
792                 CPListElement entry= (CPListElement)iter.next();
793                 classpath[i]= entry.getClasspathEntry();
794                 i++;
795                 
796                 IResource res= entry.getResource();
797                 //1 tick
798
if (res instanceof IFolder && entry.getLinkTarget() == null && !res.exists()) {
799                     CoreUtility.createFolder((IFolder)res, true, true, new SubProgressMonitor(monitor, 1));
800                 } else {
801                     monitor.worked(1);
802                 }
803                 
804                 //3 ticks
805
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
806                     IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT);
807                     if (folderOutput != null && folderOutput.segmentCount() > 1) {
808                         IFolder folder= fWorkspaceRoot.getFolder(folderOutput);
809                         CoreUtility.createDerivedFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
810                     } else {
811                         monitor.worked(1);
812                     }
813                     
814                     IPath path= entry.getPath();
815                     if (projPath.equals(path)) {
816                         monitor.worked(2);
817                         continue;
818                     }
819                     
820                     if (projPath.isPrefixOf(path)) {
821                         path= path.removeFirstSegments(projPath.segmentCount());
822                     }
823                     IFolder folder= project.getFolder(path);
824                     IPath orginalPath= entry.getOrginalPath();
825                     if (orginalPath == null) {
826                         if (!folder.exists()) {
827                             //New source folder needs to be created
828
if (entry.getLinkTarget() == null) {
829                                 CoreUtility.createFolder(folder, true, true, new SubProgressMonitor(monitor, 2));
830                             } else {
831                                 folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 2));
832                             }
833                         }
834                     } else {
835                         if (projPath.isPrefixOf(orginalPath)) {
836                             orginalPath= orginalPath.removeFirstSegments(projPath.segmentCount());
837                         }
838                         IFolder orginalFolder= project.getFolder(orginalPath);
839                         if (entry.getLinkTarget() == null) {
840                             if (!folder.exists()) {
841                                 //Source folder was edited, move to new location
842
IPath parentPath= entry.getPath().removeLastSegments(1);
843                                 if (projPath.isPrefixOf(parentPath)) {
844                                     parentPath= parentPath.removeFirstSegments(projPath.segmentCount());
845                                 }
846                                 if (parentPath.segmentCount() > 0) {
847                                     IFolder parentFolder= project.getFolder(parentPath);
848                                     if (!parentFolder.exists()) {
849                                         CoreUtility.createFolder(parentFolder, true, true, new SubProgressMonitor(monitor, 1));
850                                     } else {
851                                         monitor.worked(1);
852                                     }
853                                 } else {
854                                     monitor.worked(1);
855                                 }
856                                 orginalFolder.move(entry.getPath(), true, true, new SubProgressMonitor(monitor, 1));
857                             }
858                         } else {
859                             if (!folder.exists() || !entry.getLinkTarget().equals(entry.getOrginalLinkTarget())) {
860                                 orginalFolder.delete(true, new SubProgressMonitor(monitor, 1));
861                                 folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 1));
862                             }
863                         }
864                     }
865                 } else {
866                     monitor.worked(3);
867                 }
868                 if (monitor.isCanceled()) {
869                     throw new OperationCanceledException();
870                 }
871             }
872
873             javaProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 2));
874         } finally {
875             monitor.done();
876         }
877     }
878     
879     public static boolean hasClassfiles(IResource resource) throws CoreException {
880         if (resource.isDerived()) {
881             return true;
882         }
883         if (resource instanceof IContainer) {
884             IResource[] members= ((IContainer) resource).members();
885             for (int i= 0; i < members.length; i++) {
886                 if (hasClassfiles(members[i])) {
887                     return true;
888                 }
889             }
890         }
891         return false;
892     }
893     
894
895     public static void removeOldClassfiles(IResource resource) throws CoreException {
896         if (resource.isDerived()) {
897             resource.delete(false, null);
898         } else if (resource instanceof IContainer) {
899             IResource[] members= ((IContainer) resource).members();
900             for (int i= 0; i < members.length; i++) {
901                 removeOldClassfiles(members[i]);
902             }
903         }
904     }
905     
906     public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) {
907         return new IRemoveOldBinariesQuery() {
908             public boolean doQuery(final boolean removeFolder, final IPath oldOutputLocation) throws OperationCanceledException {
909                 final int[] res= new int[] { 1 };
910                 Display.getDefault().syncExec(new Runnable JavaDoc() {
911                     public void run() {
912                         Shell sh= shell != null ? shell : JavaPlugin.getActiveWorkbenchShell();
913                         String JavaDoc title= NewWizardMessages.BuildPathsBlock_RemoveBinariesDialog_title;
914                         String JavaDoc message;
915                         if (removeFolder) {
916                             message= Messages.format(NewWizardMessages.BuildPathsBlock_RemoveOldOutputFolder_description, oldOutputLocation.makeRelative().toOSString());
917                         } else {
918                             message= Messages.format(NewWizardMessages.BuildPathsBlock_RemoveBinariesDialog_description, oldOutputLocation.makeRelative().toOSString());
919                         }
920                         MessageDialog dialog= new MessageDialog(sh, title, null, message, MessageDialog.QUESTION, new String JavaDoc[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
921                         res[0]= dialog.open();
922                     }
923                 });
924                 if (res[0] == 0) {
925                     return true;
926                 } else if (res[0] == 1) {
927                     return false;
928                 }
929                 throw new OperationCanceledException();
930             }
931         };
932     }
933
934     
935     // ---------- util method ------------
936

937     private IContainer chooseContainer() {
938         Class JavaDoc[] acceptedClasses= new Class JavaDoc[] { IProject.class, IFolder.class };
939         ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
940         IProject[] allProjects= fWorkspaceRoot.getProjects();
941         ArrayList JavaDoc rejectedElements= new ArrayList JavaDoc(allProjects.length);
942         IProject currProject= fCurrJProject.getProject();
943         for (int i= 0; i < allProjects.length; i++) {
944             if (!allProjects[i].equals(currProject)) {
945                 rejectedElements.add(allProjects[i]);
946             }
947         }
948         ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
949
950         ILabelProvider lp= new WorkbenchLabelProvider();
951         ITreeContentProvider cp= new WorkbenchContentProvider();
952
953         IResource initSelection= null;
954         if (fOutputLocationPath != null) {
955             initSelection= fWorkspaceRoot.findMember(fOutputLocationPath);
956         }
957         
958         FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
959         dialog.setTitle(NewWizardMessages.BuildPathsBlock_ChooseOutputFolderDialog_title);
960         dialog.setValidator(validator);
961         dialog.setMessage(NewWizardMessages.BuildPathsBlock_ChooseOutputFolderDialog_description);
962         dialog.addFilter(filter);
963         dialog.setInput(fWorkspaceRoot);
964         dialog.setInitialSelection(initSelection);
965         dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
966         
967         if (dialog.open() == Window.OK) {
968             return (IContainer)dialog.getFirstResult();
969         }
970         return null;
971     }
972     
973     // -------- tab switching ----------
974

975     private void tabChanged(Widget widget) {
976         if (widget instanceof TabItem) {
977             TabItem tabItem= (TabItem) widget;
978             BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData();
979             if (fCurrPage != null) {
980                 List JavaDoc selection= fCurrPage.getSelection();
981                 if (!selection.isEmpty()) {
982                     newPage.setSelection(selection, false);
983                 }
984             }
985             fCurrPage= newPage;
986             fPageIndex= tabItem.getParent().getSelectionIndex();
987         }
988     }
989     
990     private int getPageIndex(int entryKind) {
991         switch (entryKind) {
992             case IClasspathEntry.CPE_CONTAINER:
993             case IClasspathEntry.CPE_LIBRARY:
994             case IClasspathEntry.CPE_VARIABLE:
995                 return 2;
996             case IClasspathEntry.CPE_PROJECT:
997                 return 1;
998             case IClasspathEntry.CPE_SOURCE:
999                 return 0;
1000        }
1001        return 0;
1002    }
1003    
1004    private CPListElement findElement(IClasspathEntry entry) {
1005        for (int i= 0, len= fClassPathList.getSize(); i < len; i++) {
1006            CPListElement curr= (CPListElement) fClassPathList.getElement(i);
1007            if (curr.getEntryKind() == entry.getEntryKind() && curr.getPath().equals(entry.getPath())) {
1008                return curr;
1009            }
1010        }
1011        return null;
1012    }
1013    
1014    public void setElementToReveal(IClasspathEntry entry, String JavaDoc attributeKey) {
1015        int pageIndex= getPageIndex(entry.getEntryKind());
1016        if (fTabFolder == null) {
1017            fPageIndex= pageIndex;
1018        } else {
1019            fTabFolder.setSelection(pageIndex);
1020            CPListElement element= findElement(entry);
1021            if (element != null) {
1022                Object JavaDoc elementToSelect= element;
1023                
1024                if (attributeKey != null) {
1025                    Object JavaDoc attrib= element.findAttributeElement(attributeKey);
1026                    if (attrib != null) {
1027                        elementToSelect= attrib;
1028                    }
1029                }
1030                BuildPathBasePage page= (BuildPathBasePage) fTabFolder.getItem(pageIndex).getData();
1031                List JavaDoc selection= new ArrayList JavaDoc(1);
1032                selection.add(elementToSelect);
1033                page.setSelection(selection, true);
1034            }
1035        }
1036    }
1037    
1038    public void addElement(IClasspathEntry entry) {
1039        int pageIndex= getPageIndex(entry.getEntryKind());
1040        if (fTabFolder == null) {
1041            fPageIndex= pageIndex;
1042        } else {
1043            fTabFolder.setSelection(pageIndex);
1044
1045            Object JavaDoc page= fTabFolder.getItem(pageIndex).getData();
1046            if (page instanceof LibrariesWorkbookPage) {
1047                CPListElement element= CPListElement.createFromExisting(entry, fCurrJProject);
1048                ((LibrariesWorkbookPage) page).addElement(element);
1049            }
1050        }
1051    }
1052
1053    public void dispose() {
1054        if (fSourceContainerPage instanceof NewSourceContainerWorkbookPage) {
1055            ((NewSourceContainerWorkbookPage)fSourceContainerPage).dispose();
1056            fSourceContainerPage= null;
1057        }
1058    }
1059
1060    public boolean isOKStatus() {
1061        return findMostSevereStatus().isOK();
1062    }
1063
1064    public void setFocus() {
1065        fSourceContainerPage.setFocus();
1066    }
1067}
1068
Popular Tags