KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > wizards > datatransfer > WizardExternalProjectImportPage


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.ui.wizards.datatransfer;
12
13 import java.io.File JavaDoc;
14 import java.io.FileFilter JavaDoc;
15 import java.lang.reflect.InvocationTargetException JavaDoc;
16
17 import org.eclipse.core.resources.IProject;
18 import org.eclipse.core.resources.IProjectDescription;
19 import org.eclipse.core.resources.IResource;
20 import org.eclipse.core.resources.IResourceStatus;
21 import org.eclipse.core.resources.IWorkspace;
22 import org.eclipse.core.resources.ResourcesPlugin;
23 import org.eclipse.core.runtime.CoreException;
24 import org.eclipse.core.runtime.IPath;
25 import org.eclipse.core.runtime.IProgressMonitor;
26 import org.eclipse.core.runtime.OperationCanceledException;
27 import org.eclipse.core.runtime.Path;
28 import org.eclipse.core.runtime.Platform;
29 import org.eclipse.core.runtime.SubProgressMonitor;
30 import org.eclipse.jface.dialogs.ErrorDialog;
31 import org.eclipse.jface.dialogs.MessageDialog;
32 import org.eclipse.jface.wizard.WizardPage;
33 import org.eclipse.osgi.util.NLS;
34 import org.eclipse.swt.SWT;
35 import org.eclipse.swt.events.SelectionAdapter;
36 import org.eclipse.swt.events.SelectionEvent;
37 import org.eclipse.swt.graphics.Font;
38 import org.eclipse.swt.layout.GridData;
39 import org.eclipse.swt.layout.GridLayout;
40 import org.eclipse.swt.widgets.Button;
41 import org.eclipse.swt.widgets.Composite;
42 import org.eclipse.swt.widgets.DirectoryDialog;
43 import org.eclipse.swt.widgets.Event;
44 import org.eclipse.swt.widgets.Label;
45 import org.eclipse.swt.widgets.Listener;
46 import org.eclipse.swt.widgets.Text;
47 import org.eclipse.ui.PlatformUI;
48 import org.eclipse.ui.actions.WorkspaceModifyOperation;
49 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
50 import org.eclipse.ui.internal.ide.IIDEHelpContextIds;
51 import org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages;
52
53 /**
54  * Standard main page for a wizard that creates a project resource from
55  * whose location already contains a project.
56  * <p>
57  * This page may be used by clients as-is; it may be also be subclassed to suit.
58  * </p>
59  * <p>
60  * Example usage:
61  * <pre>
62  * mainPage = new WizardExternalProjectImportPage("basicNewProjectPage");
63  * mainPage.setTitle("Project");
64  * mainPage.setDescription("Create a new project resource.");
65  * </pre>
66  * </p>
67  */

68 public class WizardExternalProjectImportPage extends WizardPage {
69
70     private FileFilter JavaDoc projectFilter = new FileFilter JavaDoc() {
71         //Only accept those files that are .project
72
public boolean accept(File JavaDoc pathName) {
73             return pathName.getName().equals(
74                     IProjectDescription.DESCRIPTION_FILE_NAME);
75         }
76     };
77
78     //Keep track of the directory that we browsed to last time
79
//the wizard was invoked.
80
private static String JavaDoc previouslyBrowsedDirectory = ""; //$NON-NLS-1$
81

82     // widgets
83
private Text projectNameField;
84
85     private Text locationPathField;
86
87     private Button browseButton;
88
89     private IProjectDescription description;
90
91     private Listener locationModifyListener = new Listener() {
92         public void handleEvent(Event e) {
93             setPageComplete(validatePage());
94         }
95     };
96
97     // constants
98
private static final int SIZING_TEXT_FIELD_WIDTH = 250;
99
100     /**
101      * Creates a new project creation wizard page.
102      *
103      */

104     public WizardExternalProjectImportPage() {
105         super("wizardExternalProjectPage"); //$NON-NLS-1$
106
setPageComplete(false);
107         setTitle(DataTransferMessages.WizardExternalProjectImportPage_title);
108         setDescription(DataTransferMessages.WizardExternalProjectImportPage_description);
109
110     }
111
112     /** (non-Javadoc)
113      * Method declared on IDialogPage.
114      */

115     public void createControl(Composite parent) {
116
117         initializeDialogUnits(parent);
118
119         Composite composite = new Composite(parent, SWT.NULL);
120
121         PlatformUI.getWorkbench().getHelpSystem().setHelp(composite,
122                 IIDEHelpContextIds.NEW_PROJECT_WIZARD_PAGE);
123
124         composite.setLayout(new GridLayout());
125         composite.setLayoutData(new GridData(GridData.FILL_BOTH));
126         composite.setFont(parent.getFont());
127
128         createProjectNameGroup(composite);
129         createProjectLocationGroup(composite);
130         validatePage();
131         // Show description on opening
132
setErrorMessage(null);
133         setMessage(null);
134         setControl(composite);
135     }
136
137     /**
138      * Creates the project location specification controls.
139      *
140      * @param parent the parent composite
141      */

142     private final void createProjectLocationGroup(Composite parent) {
143
144         // project specification group
145
Composite projectGroup = new Composite(parent, SWT.NONE);
146         GridLayout layout = new GridLayout();
147         layout.numColumns = 3;
148         projectGroup.setLayout(layout);
149         projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
150         projectGroup.setFont(parent.getFont());
151
152         // new project label
153
Label projectContentsLabel = new Label(projectGroup, SWT.NONE);
154         projectContentsLabel.setText(DataTransferMessages.WizardExternalProjectImportPage_projectContentsLabel);
155         projectContentsLabel.setFont(parent.getFont());
156
157         createUserSpecifiedProjectLocationGroup(projectGroup);
158     }
159
160     /**
161      * Creates the project name specification controls.
162      *
163      * @param parent the parent composite
164      */

165     private final void createProjectNameGroup(Composite parent) {
166
167         Font dialogFont = parent.getFont();
168
169         // project specification group
170
Composite projectGroup = new Composite(parent, SWT.NONE);
171         GridLayout layout = new GridLayout();
172         layout.numColumns = 2;
173         projectGroup.setFont(dialogFont);
174         projectGroup.setLayout(layout);
175         projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
176
177         // new project label
178
Label projectLabel = new Label(projectGroup, SWT.NONE);
179         projectLabel.setText(DataTransferMessages.WizardExternalProjectImportPage_nameLabel);
180         projectLabel.setFont(dialogFont);
181
182         // new project name entry field
183
projectNameField = new Text(projectGroup, SWT.BORDER | SWT.READ_ONLY);
184         GridData data = new GridData(GridData.FILL_HORIZONTAL);
185         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
186         projectNameField.setLayoutData(data);
187         projectNameField.setFont(dialogFont);
188         projectNameField.setBackground(parent.getDisplay().getSystemColor(
189                 SWT.COLOR_WIDGET_BACKGROUND));
190     }
191
192     /**
193      * Creates the project location specification controls.
194      *
195      * @param projectGroup the parent composite
196      */

197     private void createUserSpecifiedProjectLocationGroup(Composite projectGroup) {
198
199         Font dialogFont = projectGroup.getFont();
200
201         // project location entry field
202
this.locationPathField = new Text(projectGroup, SWT.BORDER);
203         GridData data = new GridData(GridData.FILL_HORIZONTAL);
204         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
205         this.locationPathField.setLayoutData(data);
206         this.locationPathField.setFont(dialogFont);
207
208         // browse button
209
this.browseButton = new Button(projectGroup, SWT.PUSH);
210         this.browseButton.setText(DataTransferMessages.DataTransfer_browse);
211         this.browseButton.setFont(dialogFont);
212         setButtonLayoutData(this.browseButton);
213
214         this.browseButton.addSelectionListener(new SelectionAdapter() {
215             public void widgetSelected(SelectionEvent event) {
216                 handleLocationBrowseButtonPressed();
217             }
218         });
219
220         locationPathField.addListener(SWT.Modify, locationModifyListener);
221     }
222
223     /**
224      * Returns the current project location path as entered by
225      * the user, or its anticipated initial value.
226      *
227      * @return the project location path, its anticipated initial value, or <code>null</code>
228      * if no project location path is known
229      */

230     public IPath getLocationPath() {
231
232         return new Path(getProjectLocationFieldValue());
233     }
234
235     /**
236      * Creates a project resource handle for the current project name field value.
237      * <p>
238      * This method does not create the project resource; this is the responsibility
239      * of <code>IProject::create</code> invoked by the new project resource wizard.
240      * </p>
241      *
242      * @return the new project resource handle
243      */

244     public IProject getProjectHandle() {
245         return ResourcesPlugin.getWorkspace().getRoot().getProject(
246                 getProjectName());
247     }
248
249     /**
250      * Returns the current project name as entered by the user, or its anticipated
251      * initial value.
252      *
253      * @return the project name, its anticipated initial value, or <code>null</code>
254      * if no project name is known
255      */

256     public String JavaDoc getProjectName() {
257         return getProjectNameFieldValue();
258     }
259
260     /**
261      * Returns the value of the project name field
262      * with leading and trailing spaces removed.
263      *
264      * @return the project name in the field
265      */

266     private String JavaDoc getProjectNameFieldValue() {
267         if (projectNameField == null) {
268             return ""; //$NON-NLS-1$
269
}
270
271         return projectNameField.getText().trim();
272     }
273
274     /**
275      * Returns the value of the project location field
276      * with leading and trailing spaces removed.
277      *
278      * @return the project location directory in the field
279      */

280     private String JavaDoc getProjectLocationFieldValue() {
281         return locationPathField.getText().trim();
282     }
283
284     /**
285      * Open an appropriate directory browser
286      */

287     private void handleLocationBrowseButtonPressed() {
288         DirectoryDialog dialog = new DirectoryDialog(locationPathField
289                 .getShell());
290         dialog.setMessage(DataTransferMessages.WizardExternalProjectImportPage_directoryLabel);
291
292         String JavaDoc dirName = getProjectLocationFieldValue();
293         if (dirName.length() == 0) {
294             dirName = previouslyBrowsedDirectory;
295         }
296
297         if (dirName.length() == 0) {
298             dialog.setFilterPath(getWorkspace().getRoot().getLocation()
299                     .toOSString());
300         } else {
301             File JavaDoc path = new File JavaDoc(dirName);
302             if (path.exists()) {
303                 dialog.setFilterPath(new Path(dirName).toOSString());
304             }
305         }
306
307         String JavaDoc selectedDirectory = dialog.open();
308         if (selectedDirectory != null) {
309             previouslyBrowsedDirectory = selectedDirectory;
310             locationPathField.setText(previouslyBrowsedDirectory);
311             setProjectName(projectFile(previouslyBrowsedDirectory));
312         }
313     }
314
315     /**
316      * Returns whether this page's controls currently all contain valid
317      * values.
318      *
319      * @return <code>true</code> if all controls are valid, and
320      * <code>false</code> if at least one is invalid
321      */

322     private boolean validatePage() {
323
324         String JavaDoc locationFieldContents = getProjectLocationFieldValue();
325
326         if (locationFieldContents.equals("")) { //$NON-NLS-1$
327
setErrorMessage(null);
328             setMessage(DataTransferMessages.WizardExternalProjectImportPage_projectLocationEmpty);
329             return false;
330         }
331
332         IPath path = new Path(""); //$NON-NLS-1$
333
if (!path.isValidPath(locationFieldContents)) {
334             setErrorMessage(DataTransferMessages.WizardExternalProjectImportPage_locationError);
335             return false;
336         }
337
338         File JavaDoc projectFile = projectFile(locationFieldContents);
339         if (projectFile == null) {
340             setErrorMessage(NLS.bind(DataTransferMessages.WizardExternalProjectImportPage_notAProject, locationFieldContents));
341             return false;
342         }
343         setProjectName(projectFile);
344
345         if (getProjectHandle().exists()) {
346             setErrorMessage(DataTransferMessages.WizardExternalProjectImportPage_projectExistsMessage);
347             return false;
348         }
349
350         setErrorMessage(null);
351         setMessage(null);
352         return true;
353     }
354
355     private IWorkspace getWorkspace() {
356         IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
357         return workspace;
358     }
359
360     /**
361      * Return whether or not the specifed location is a prefix
362      * of the root.
363      */

364     private boolean isPrefixOfRoot(IPath locationPath) {
365         return Platform.getLocation().isPrefixOf(locationPath);
366     }
367
368     /**
369      * Set the project name using either the name of the
370      * parent of the file or the name entry in the xml for
371      * the file
372      */

373     private void setProjectName(File JavaDoc projectFile) {
374
375         //If there is no file or the user has already specified forget it
376
if (projectFile == null) {
377             return;
378         }
379
380         IPath path = new Path(projectFile.getPath());
381
382         IProjectDescription newDescription = null;
383
384         try {
385             newDescription = getWorkspace().loadProjectDescription(path);
386         } catch (CoreException exception) {
387             //no good couldn't get the name
388
}
389
390         if (newDescription == null) {
391             this.description = null;
392             this.projectNameField.setText(""); //$NON-NLS-1$
393
} else {
394             this.description = newDescription;
395             this.projectNameField.setText(this.description.getName());
396         }
397     }
398
399     /**
400      * Return a.project file from the specified location.
401      * If there isn't one return null.
402      */

403     private File JavaDoc projectFile(String JavaDoc locationFieldContents) {
404         File JavaDoc directory = new File JavaDoc(locationFieldContents);
405         if (directory.isFile()) {
406             return null;
407         }
408
409         File JavaDoc[] files = directory.listFiles(this.projectFilter);
410         if (files != null && files.length == 1) {
411             return files[0];
412         }
413
414         return null;
415     }
416
417     /**
418      * Creates a new project resource with the selected name.
419      * <p>
420      * In normal usage, this method is invoked after the user has pressed Finish on
421      * the wizard; the enablement of the Finish button implies that all controls
422      * on the pages currently contain valid values.
423      * </p>
424      *
425      * @return the created project resource, or <code>null</code> if the project
426      * was not created
427      */

428     IProject createExistingProject() {
429
430         String JavaDoc projectName = projectNameField.getText();
431         final IWorkspace workspace = ResourcesPlugin.getWorkspace();
432         final IProject project = workspace.getRoot().getProject(projectName);
433         if (this.description == null) {
434             this.description = workspace.newProjectDescription(projectName);
435             IPath locationPath = getLocationPath();
436             //If it is under the root use the default location
437
if (isPrefixOfRoot(locationPath)) {
438                 this.description.setLocation(null);
439             } else {
440                 this.description.setLocation(locationPath);
441             }
442         } else {
443             this.description.setName(projectName);
444         }
445
446         // create the new project operation
447
WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
448             protected void execute(IProgressMonitor monitor)
449                     throws CoreException {
450                 monitor.beginTask("", 2000); //$NON-NLS-1$
451
project.create(description, new SubProgressMonitor(monitor,
452                         1000));
453                 if (monitor.isCanceled()) {
454                     throw new OperationCanceledException();
455                 }
456                 project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(monitor, 1000));
457
458             }
459         };
460
461         // run the new project creation operation
462
try {
463             getContainer().run(true, true, op);
464         } catch (InterruptedException JavaDoc e) {
465             return null;
466         } catch (InvocationTargetException JavaDoc e) {
467             // ie.- one of the steps resulted in a core exception
468
Throwable JavaDoc t = e.getTargetException();
469             if (t instanceof CoreException) {
470                 if (((CoreException) t).getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
471                     MessageDialog
472                             .openError(
473                                     getShell(),
474                                     DataTransferMessages.WizardExternalProjectImportPage_errorMessage,
475                                     NLS.bind(
476                                             DataTransferMessages.WizardExternalProjectImportPage_caseVariantExistsError,
477                                             projectName)
478                             );
479                 } else {
480                     ErrorDialog
481                             .openError(
482                                     getShell(),
483                                     DataTransferMessages.WizardExternalProjectImportPage_errorMessage,
484                                     null, ((CoreException) t).getStatus());
485                 }
486             }
487             return null;
488         }
489
490         return project;
491     }
492
493     /*
494      * see @DialogPage.setVisible(boolean)
495      */

496     public void setVisible(boolean visible) {
497         super.setVisible(visible);
498         if (visible) {
499             this.locationPathField.setFocus();
500         }
501     }
502
503 }
504
Popular Tags