KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > dialogs > WizardResourceImportPage


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  * Martin Boyle <martingboyle@gmail.com> - Fix for
11  * Bug 183013 [Wizards] Error importing into linked EFS folder - "undefined path variable"
12  *******************************************************************************/

13 package org.eclipse.ui.dialogs;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Map JavaDoc;
17
18 import org.eclipse.core.resources.IContainer;
19 import org.eclipse.core.resources.IProject;
20 import org.eclipse.core.resources.IResource;
21 import org.eclipse.core.resources.IWorkspace;
22 import org.eclipse.core.resources.IWorkspaceRoot;
23 import org.eclipse.core.runtime.IAdaptable;
24 import org.eclipse.core.runtime.IPath;
25 import org.eclipse.core.runtime.IProgressMonitor;
26 import org.eclipse.core.runtime.IStatus;
27 import org.eclipse.jface.viewers.CheckStateChangedEvent;
28 import org.eclipse.jface.viewers.ICheckStateListener;
29 import org.eclipse.jface.viewers.IStructuredSelection;
30 import org.eclipse.jface.viewers.ITreeContentProvider;
31 import org.eclipse.swt.SWT;
32 import org.eclipse.swt.custom.BusyIndicator;
33 import org.eclipse.swt.layout.GridData;
34 import org.eclipse.swt.layout.GridLayout;
35 import org.eclipse.swt.widgets.Button;
36 import org.eclipse.swt.widgets.Composite;
37 import org.eclipse.swt.widgets.Event;
38 import org.eclipse.swt.widgets.Label;
39 import org.eclipse.swt.widgets.Text;
40 import org.eclipse.swt.widgets.Widget;
41 import org.eclipse.ui.internal.ide.DialogUtil;
42 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
43 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
44 import org.eclipse.ui.internal.ide.dialogs.IElementFilter;
45 import org.eclipse.ui.internal.ide.dialogs.ResourceTreeAndListGroup;
46 import org.eclipse.ui.model.WorkbenchLabelProvider;
47 import org.eclipse.ui.model.WorkbenchViewerComparator;
48
49 /**
50  * The abstract superclass for a typical import wizard's main page.
51  * <p>
52  * Clients may subclass this page to inherit its common destination resource
53  * selection facilities.
54  * </p>
55  * <p>
56  * Subclasses must implement
57  * <ul>
58  * <li><code>createSourceGroup</code></li>
59  * </ul>
60  * </p>
61  * <p>
62  * Subclasses may override
63  * <ul>
64  * <li><code>allowNewContainerName</code></li>
65  * </ul>
66  * </p>
67  * <p>
68  * Subclasses may extend
69  * <ul>
70  * <li><code>handleEvent</code></li>
71  * </ul>
72  * </p>
73  */

74 public abstract class WizardResourceImportPage extends WizardDataTransferPage {
75     private IResource currentResourceSelection;
76
77     // initial value stores
78
private String JavaDoc initialContainerFieldValue;
79
80     protected java.util.List JavaDoc selectedTypes = new ArrayList JavaDoc();
81
82     // widgets
83
private Text containerNameField;
84
85     private Button containerBrowseButton;
86
87     /**
88      * The <code>selectionGroup</code> field should have been created with a
89      * private modifier. Subclasses should not access this field directly.
90      */

91     protected ResourceTreeAndListGroup selectionGroup;
92
93     //messages
94
private static final String JavaDoc EMPTY_FOLDER_MESSAGE = IDEWorkbenchMessages.WizardImportPage_specifyFolder;
95
96     private static final String JavaDoc EMPTY_PROJECT_MESSAGE = IDEWorkbenchMessages.WizardImportPage_specifyProject;
97     
98     private static final String JavaDoc INACCESSABLE_FOLDER_MESSAGE = IDEWorkbenchMessages.WizardImportPage_folderMustExist;
99
100     /**
101      * Creates an import wizard page. If the initial resource selection
102      * contains exactly one container resource then it will be used as the default
103      * import destination.
104      *
105      * @param name the name of the page
106      * @param selection the current resource selection
107      */

108     protected WizardResourceImportPage(String JavaDoc name,
109             IStructuredSelection selection) {
110         super(name);
111
112         //Initialize to null
113
currentResourceSelection = null;
114         if (selection.size() == 1) {
115             Object JavaDoc firstElement = selection.getFirstElement();
116             if (firstElement instanceof IAdaptable) {
117                 Object JavaDoc resource = ((IAdaptable) firstElement)
118                         .getAdapter(IResource.class);
119                 if (resource != null) {
120                     currentResourceSelection = (IResource) resource;
121                 }
122             }
123         }
124
125         if (currentResourceSelection != null) {
126             if (currentResourceSelection.getType() == IResource.FILE) {
127                 currentResourceSelection = currentResourceSelection.getParent();
128             }
129
130             if (!currentResourceSelection.isAccessible()) {
131                 currentResourceSelection = null;
132             }
133         }
134
135     }
136
137     /**
138      * The <code>WizardResourceImportPage</code> implementation of this
139      * <code>WizardDataTransferPage</code> method returns <code>true</code>.
140      * Subclasses may override this method.
141      */

142     protected boolean allowNewContainerName() {
143         return true;
144     }
145
146     /** (non-Javadoc)
147      * Method declared on IDialogPage.
148      */

149     public void createControl(Composite parent) {
150
151         initializeDialogUnits(parent);
152
153         Composite composite = new Composite(parent, SWT.NULL);
154         composite.setLayout(new GridLayout());
155         composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
156                 | GridData.HORIZONTAL_ALIGN_FILL));
157         composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
158         composite.setFont(parent.getFont());
159
160         createSourceGroup(composite);
161
162         createDestinationGroup(composite);
163
164         createOptionsGroup(composite);
165
166         restoreWidgetValues();
167         updateWidgetEnablements();
168         setPageComplete(determinePageCompletion());
169         setErrorMessage(null); // should not initially have error message
170

171         setControl(composite);
172     }
173
174     /**
175      * Creates the import destination specification controls.
176      *
177      * @param parent the parent control
178      */

179     protected final void createDestinationGroup(Composite parent) {
180         // container specification group
181
Composite containerGroup = new Composite(parent, SWT.NONE);
182         GridLayout layout = new GridLayout();
183         layout.numColumns = 3;
184         containerGroup.setLayout(layout);
185         containerGroup.setLayoutData(new GridData(
186                 GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
187         containerGroup.setFont(parent.getFont());
188
189         // container label
190
Label resourcesLabel = new Label(containerGroup, SWT.NONE);
191         resourcesLabel.setText(IDEWorkbenchMessages.WizardImportPage_folder);
192         resourcesLabel.setFont(parent.getFont());
193
194         // container name entry field
195
containerNameField = new Text(containerGroup, SWT.SINGLE | SWT.BORDER);
196         containerNameField.addListener(SWT.Modify, this);
197         GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
198                 | GridData.GRAB_HORIZONTAL);
199         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
200         containerNameField.setLayoutData(data);
201         containerNameField.setFont(parent.getFont());
202
203         // container browse button
204
containerBrowseButton = new Button(containerGroup, SWT.PUSH);
205         containerBrowseButton.setText(IDEWorkbenchMessages.WizardImportPage_browse2);
206         containerBrowseButton.setLayoutData(new GridData(
207                 GridData.HORIZONTAL_ALIGN_FILL));
208         containerBrowseButton.addListener(SWT.Selection, this);
209         containerBrowseButton.setFont(parent.getFont());
210         setButtonLayoutData(containerBrowseButton);
211
212         initialPopulateContainerField();
213     }
214
215     /**
216      * Create the import source selection widget
217      */

218     protected void createFileSelectionGroup(Composite parent) {
219
220         //Just create with a dummy root.
221
this.selectionGroup = new ResourceTreeAndListGroup(parent,
222                 new FileSystemElement("Dummy", null, true),//$NON-NLS-1$
223
getFolderProvider(), new WorkbenchLabelProvider(),
224                 getFileProvider(), new WorkbenchLabelProvider(), SWT.NONE,
225                 DialogUtil.inRegularFontMode(parent));
226
227         ICheckStateListener listener = new ICheckStateListener() {
228             public void checkStateChanged(CheckStateChangedEvent event) {
229                 updateWidgetEnablements();
230             }
231         };
232
233         WorkbenchViewerComparator comparator = new WorkbenchViewerComparator();
234         this.selectionGroup.setTreeComparator(comparator);
235         this.selectionGroup.setListComparator(comparator);
236         this.selectionGroup.addCheckStateListener(listener);
237
238     }
239
240     /**
241      * Creates the import source specification controls.
242      * <p>
243      * Subclasses must implement this method.
244      * </p>
245      *
246      * @param parent the parent control
247      */

248     protected abstract void createSourceGroup(Composite parent);
249
250     /*
251      * @see WizardDataTransferPage.getErrorDialogTitle()
252      */

253     protected String JavaDoc getErrorDialogTitle() {
254         return IDEWorkbenchMessages.WizardImportPage_errorDialogTitle;
255     }
256
257     /**
258      * Returns the path of the container resource specified in the container
259      * name entry field, or <code>null</code> if no name has been typed in.
260      * <p>
261      * The container specified by the full path might not exist and would need to
262      * be created.
263      * </p>
264      *
265      * @return the full path of the container resource specified in
266      * the container name entry field, or <code>null</code>
267      */

268     protected IPath getContainerFullPath() {
269         IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
270
271         //make the path absolute to allow for optional leading slash
272
IPath testPath = getResourcePath();
273
274         if (testPath.equals(workspace.getRoot().getFullPath())) {
275             return testPath;
276         }
277
278         IStatus result = workspace.validatePath(testPath.toString(),
279                 IResource.PROJECT | IResource.FOLDER | IResource.ROOT);
280         if (result.isOK()) {
281             return testPath;
282         }
283
284         return null;
285     }
286
287     /**
288      * Returns a content provider for <code>FileSystemElement</code>s that returns
289      * only files as children.
290      */

291     protected abstract ITreeContentProvider getFileProvider();
292
293     /**
294      * Returns a content provider for <code>FileSystemElement</code>s that returns
295      * only folders as children.
296      */

297     protected abstract ITreeContentProvider getFolderProvider();
298
299     /**
300      * Return the path for the resource field.
301      * @return IPath
302      */

303     protected IPath getResourcePath() {
304         return getPathFromText(this.containerNameField);
305     }
306
307     /**
308      * Returns this page's list of currently-specified resources to be
309      * imported. This is the primary resource selection facility accessor for
310      * subclasses.
311      *
312      * @return a list of resources currently selected
313      * for export (element type: <code>IResource</code>)
314      */

315     protected java.util.List JavaDoc getSelectedResources() {
316         return this.selectionGroup.getAllCheckedListItems();
317     }
318
319     /**
320      * Returns this page's list of currently-specified resources to be
321      * imported filtered by the IElementFilter.
322      *
323      */

324     protected void getSelectedResources(IElementFilter filter,
325             IProgressMonitor monitor) throws InterruptedException JavaDoc {
326         this.selectionGroup.getAllCheckedListItems(filter, monitor);
327     }
328
329     /**
330      * Returns the container resource specified in the container name entry field,
331      * or <code>null</code> if such a container does not exist in the workbench.
332      *
333      * @return the container resource specified in the container name entry field,
334      * or <code>null</code>
335      */

336     protected IContainer getSpecifiedContainer() {
337         IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
338         IPath path = getContainerFullPath();
339         if (workspace.getRoot().exists(path)){
340             IResource resource = workspace.getRoot().findMember(path);
341             if(resource.getType() == IResource.FILE) {
342                 return null;
343             }
344             return (IContainer) resource;
345             
346         }
347             
348
349         return null;
350     }
351
352     /**
353      * Returns a collection of the currently-specified resource types for
354      * use by the type selection dialog.
355      */

356     protected java.util.List JavaDoc getTypesToImport() {
357
358         return selectedTypes;
359     }
360
361     /**
362      * Opens a container selection dialog and displays the user's subsequent
363      * container resource selection in this page's container name field.
364      */

365     protected void handleContainerBrowseButtonPressed() {
366         // see if the user wishes to modify this container selection
367
IPath containerPath = queryForContainer(getSpecifiedContainer(),
368                 IDEWorkbenchMessages.WizardImportPage_selectFolderLabel,
369                 IDEWorkbenchMessages.WizardImportPage_selectFolderTitle);
370
371         // if a container was selected then put its name in the container name field
372
if (containerPath != null) { // null means user cancelled
373
setErrorMessage(null);
374             containerNameField.setText(containerPath.makeRelative().toString());
375         }
376     }
377
378     /**
379      * The <code>WizardResourceImportPage</code> implementation of this
380      * <code>Listener</code> method handles all events and enablements for controls
381      * on this page. Subclasses may extend.
382      * @param event Event
383      */

384     public void handleEvent(Event event) {
385         Widget source = event.widget;
386
387         if (source == containerBrowseButton) {
388             handleContainerBrowseButtonPressed();
389         }
390
391         updateWidgetEnablements();
392     }
393
394     /**
395      * Open a registered type selection dialog and note the selections
396      * in the receivers types-to-export field
397      */

398     protected void handleTypesEditButtonPressed() {
399
400         TypeFilteringDialog dialog = new TypeFilteringDialog(getContainer()
401                 .getShell(), getTypesToImport());
402
403         dialog.open();
404
405         Object JavaDoc[] newSelectedTypes = dialog.getResult();
406         if (newSelectedTypes != null) { // ie.- did not press Cancel
407
this.selectedTypes = new ArrayList JavaDoc(newSelectedTypes.length);
408             for (int i = 0; i < newSelectedTypes.length; i++) {
409                 this.selectedTypes.add(newSelectedTypes[i]);
410             }
411
412             setupSelectionsBasedOnSelectedTypes();
413         }
414
415     }
416
417     /**
418      * Sets the initial contents of the container name field.
419      */

420     protected final void initialPopulateContainerField() {
421         if (initialContainerFieldValue != null) {
422             containerNameField.setText(initialContainerFieldValue);
423         } else if (currentResourceSelection != null) {
424             containerNameField.setText(currentResourceSelection.getFullPath()
425                     .makeRelative().toString());
426         }
427     }
428
429     /**
430      * Set all of the selections in the selection group to value
431      * @param value boolean
432      */

433     protected void setAllSelections(boolean value) {
434         selectionGroup.setAllSelections(value);
435     }
436
437     /**
438      * Sets the value of this page's container resource field, or stores
439      * it for future use if this page's controls do not exist yet.
440      *
441      * @param value String
442      */

443     public void setContainerFieldValue(String JavaDoc value) {
444         if (containerNameField == null) {
445             initialContainerFieldValue = value;
446         } else {
447             containerNameField.setText(value);
448         }
449     }
450
451     /**
452      * Update the tree to only select those elements that match the selected types.
453      * Do nothing by default.
454      */

455     protected void setupSelectionsBasedOnSelectedTypes() {
456     }
457
458     /**
459      * Update the selections with those in map .
460      * @param map Map - key tree elements, values Lists of list elements
461      */

462     protected void updateSelections(final Map JavaDoc map) {
463
464         Runnable JavaDoc runnable = new Runnable JavaDoc() {
465             public void run() {
466                 selectionGroup.updateSelections(map);
467             }
468         };
469
470         BusyIndicator.showWhile(getShell().getDisplay(), runnable);
471     }
472
473     /**
474      * Check if widgets are enabled or disabled by a change in the dialog.
475      */

476     protected void updateWidgetEnablements() {
477
478         boolean pageComplete = determinePageCompletion();
479         setPageComplete(pageComplete);
480         if (pageComplete) {
481             setMessage(null);
482         }
483         super.updateWidgetEnablements();
484     }
485
486     /* (non-Javadoc)
487      * Method declared on WizardDataTransferPage.
488      */

489     protected final boolean validateDestinationGroup() {
490
491         IPath containerPath = getContainerFullPath();
492         if (containerPath == null) {
493             setMessage(EMPTY_FOLDER_MESSAGE);
494             return false;
495         }
496
497         // If the container exist, validate it
498
IContainer container = getSpecifiedContainer();
499         if (container == null) {
500             //If it exists but is not valid then abort
501
if(IDEWorkbenchPlugin.getPluginWorkspace().getRoot().exists(getContainerFullPath())) {
502                 return false;
503             }
504             
505             //if it is does not exist be sure the project does
506
IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
507             IPath projectPath = containerPath.removeLastSegments(containerPath
508                     .segmentCount() - 1);
509
510             if (workspace.getRoot().exists(projectPath)) {
511                 return true;
512             }
513             setErrorMessage(IDEWorkbenchMessages.WizardImportPage_projectNotExist);
514             return false;
515         }
516         if (!container.isAccessible()) {
517              setErrorMessage(INACCESSABLE_FOLDER_MESSAGE);
518              return false;
519         }
520         if (container.getLocationURI() == null) {
521           if (container.isLinked()) {
522                setErrorMessage(IDEWorkbenchMessages.WizardImportPage_undefinedPathVariable);
523           } else {
524                setErrorMessage(IDEWorkbenchMessages.WizardImportPage_containerNotExist);
525           }
526          return false;
527         }
528         
529
530         if (sourceConflictsWithDestination(containerPath)) {
531             setErrorMessage(getSourceConflictMessage());
532             return false;
533         }
534
535         if (container instanceof IWorkspaceRoot){
536             setErrorMessage(EMPTY_PROJECT_MESSAGE);
537             return false;
538         }
539         return true;
540
541     }
542
543     /**
544      * Returns the error message for when the source conflicts
545      * with the destination.
546      */

547     protected final String JavaDoc getSourceConflictMessage() {
548         return (IDEWorkbenchMessages.WizardImportPage_importOnReceiver);
549     }
550
551     /**
552      * Returns whether or not the source location conflicts
553      * with the destination resource. By default this is not
554      * checked, so <code>false</code> is returned.
555      *
556      * @param sourcePath the path being checked
557      * @return <code>true</code> if the source location conflicts with the
558      * destination resource, <code>false</code> if not
559      */

560     protected boolean sourceConflictsWithDestination(IPath sourcePath) {
561         return false;
562     }
563
564     /*
565      * @see WizardDataTransferPage.determinePageCompletion.
566      */

567     protected boolean determinePageCompletion() {
568         //Check for valid projects before making the user do anything
569
if (noOpenProjects()) {
570             setErrorMessage(IDEWorkbenchMessages.WizardImportPage_noOpenProjects);
571             return false;
572         }
573         return super.determinePageCompletion();
574     }
575
576     /**
577      * Returns whether or not the passed workspace has any
578      * open projects
579      * @return boolean
580      */

581     private boolean noOpenProjects() {
582         IProject[] projects = IDEWorkbenchPlugin.getPluginWorkspace().getRoot()
583                 .getProjects();
584         for (int i = 0; i < projects.length; i++) {
585             if (projects[i].isOpen()) {
586                 return false;
587             }
588         }
589         return true;
590     }
591 }
592
Popular Tags