KickJava   Java API By Example, From Geeks To Geeks.

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


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  * Leon J. Breedt - Added multiple folder creation support (in WizardNewFolderMainPage)
11  *
12  *******************************************************************************/

13 package org.eclipse.ui.dialogs;
14
15 import java.lang.reflect.InvocationTargetException JavaDoc;
16 import java.net.URI JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import org.eclipse.core.commands.ExecutionException;
19 import org.eclipse.core.resources.IFolder;
20 import org.eclipse.core.resources.IResource;
21 import org.eclipse.core.resources.IResourceStatus;
22 import org.eclipse.core.resources.IWorkspaceRoot;
23 import org.eclipse.core.resources.ResourcesPlugin;
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.core.runtime.IAdaptable;
26 import org.eclipse.core.runtime.IPath;
27 import org.eclipse.core.runtime.IProgressMonitor;
28 import org.eclipse.core.runtime.IStatus;
29 import org.eclipse.core.runtime.OperationCanceledException;
30 import org.eclipse.core.runtime.Preferences;
31 import org.eclipse.core.runtime.SubProgressMonitor;
32 import org.eclipse.jface.dialogs.ErrorDialog;
33 import org.eclipse.jface.dialogs.MessageDialog;
34 import org.eclipse.jface.operation.IRunnableWithProgress;
35 import org.eclipse.jface.viewers.IStructuredSelection;
36 import org.eclipse.jface.wizard.WizardPage;
37 import org.eclipse.osgi.util.NLS;
38 import org.eclipse.swt.SWT;
39 import org.eclipse.swt.events.SelectionAdapter;
40 import org.eclipse.swt.events.SelectionEvent;
41 import org.eclipse.swt.graphics.Point;
42 import org.eclipse.swt.layout.GridData;
43 import org.eclipse.swt.layout.GridLayout;
44 import org.eclipse.swt.widgets.Button;
45 import org.eclipse.swt.widgets.Composite;
46 import org.eclipse.swt.widgets.Event;
47 import org.eclipse.swt.widgets.Listener;
48 import org.eclipse.swt.widgets.Shell;
49 import org.eclipse.ui.PlatformUI;
50 import org.eclipse.ui.ide.undo.CreateFolderOperation;
51 import org.eclipse.ui.ide.undo.WorkspaceUndoUtil;
52 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
53 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
54 import org.eclipse.ui.internal.ide.IIDEHelpContextIds;
55 import org.eclipse.ui.internal.ide.dialogs.CreateLinkedResourceGroup;
56 import org.eclipse.ui.internal.ide.misc.ResourceAndContainerGroup;
57
58 /**
59  * Standard main page for a wizard that creates a folder resource.
60  * <p>
61  * This page may be used by clients as-is; it may be also be subclassed to suit.
62  * </p>
63  * <p>
64  * Subclasses may extend
65  * <ul>
66  * <li><code>handleEvent</code></li>
67  * </ul>
68  * </p>
69  */

70 public class WizardNewFolderMainPage extends WizardPage implements Listener {
71     private static final int SIZING_CONTAINER_GROUP_HEIGHT = 250;
72
73     private IStructuredSelection currentSelection;
74
75     private IFolder newFolder;
76
77     // link target location
78
private URI JavaDoc linkTargetPath;
79
80     // widgets
81
private ResourceAndContainerGroup resourceGroup;
82
83     private Button advancedButton;
84
85     private CreateLinkedResourceGroup linkedResourceGroup;
86
87     private Composite linkedResourceParent;
88
89     private Composite linkedResourceComposite;
90
91     /**
92      * Height of the "advanced" linked resource group. Set when the advanced
93      * group is first made visible.
94      */

95     private int linkedResourceGroupHeight = -1;
96
97     /**
98      * First time the advanced group is validated.
99      */

100     private boolean firstLinkCheck = true;
101
102     /**
103      * Creates a new folder creation wizard page. If the initial resource
104      * selection contains exactly one container resource then it will be used as
105      * the default container resource.
106      *
107      * @param pageName
108      * the name of the page
109      * @param selection
110      * the current resource selection
111      */

112     public WizardNewFolderMainPage(String JavaDoc pageName,
113             IStructuredSelection selection) {
114         super("newFolderPage1");//$NON-NLS-1$
115
setTitle(pageName);
116         setDescription(IDEWorkbenchMessages.WizardNewFolderMainPage_description);
117         this.currentSelection = selection;
118     }
119
120     /**
121      * Creates the widget for advanced options.
122      *
123      * @param parent
124      * the parent composite
125      */

126     protected void createAdvancedControls(Composite parent) {
127         Preferences preferences = ResourcesPlugin.getPlugin()
128                 .getPluginPreferences();
129
130         if (preferences.getBoolean(ResourcesPlugin.PREF_DISABLE_LINKING) == false) {
131             linkedResourceParent = new Composite(parent, SWT.NONE);
132             linkedResourceParent.setFont(parent.getFont());
133             linkedResourceParent.setLayoutData(new GridData(
134                     GridData.FILL_HORIZONTAL));
135             GridLayout layout = new GridLayout();
136             layout.marginHeight = 0;
137             layout.marginWidth = 0;
138             linkedResourceParent.setLayout(layout);
139
140             advancedButton = new Button(linkedResourceParent, SWT.PUSH);
141             advancedButton.setFont(linkedResourceParent.getFont());
142             advancedButton.setText(IDEWorkbenchMessages.showAdvanced);
143             GridData data = setButtonLayoutData(advancedButton);
144             data.horizontalAlignment = GridData.BEGINNING;
145             advancedButton.setLayoutData(data);
146             advancedButton.addSelectionListener(new SelectionAdapter() {
147                 public void widgetSelected(SelectionEvent e) {
148                     handleAdvancedButtonSelect();
149                 }
150             });
151         }
152         linkedResourceGroup = new CreateLinkedResourceGroup(IResource.FOLDER,
153                 new Listener() {
154                     public void handleEvent(Event e) {
155                         setPageComplete(validatePage());
156                         firstLinkCheck = false;
157                     }
158                 }, new CreateLinkedResourceGroup.IStringValue() {
159                     public String JavaDoc getValue() {
160                         return resourceGroup.getResource();
161                     }
162
163                     public void setValue(String JavaDoc string) {
164                         resourceGroup.setResource(string);
165                     }
166                 });
167     }
168
169     /**
170      * (non-Javadoc) Method declared on IDialogPage.
171      */

172     public void createControl(Composite parent) {
173         initializeDialogUnits(parent);
174         // top level group
175
Composite composite = new Composite(parent, SWT.NONE);
176         composite.setFont(parent.getFont());
177         composite.setLayout(new GridLayout());
178         composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
179                 | GridData.HORIZONTAL_ALIGN_FILL));
180
181         PlatformUI.getWorkbench().getHelpSystem().setHelp(composite,
182                 IIDEHelpContextIds.NEW_FOLDER_WIZARD_PAGE);
183
184         resourceGroup = new ResourceAndContainerGroup(composite, this,
185                 IDEWorkbenchMessages.WizardNewFolderMainPage_folderName,
186                 IDEWorkbenchMessages.WizardNewFolderMainPage_folderLabel,
187                 false, SIZING_CONTAINER_GROUP_HEIGHT);
188         resourceGroup.setAllowExistingResources(false);
189         createAdvancedControls(composite);
190         initializePage();
191         validatePage();
192         // Show description on opening
193
setErrorMessage(null);
194         setMessage(null);
195         setControl(composite);
196     }
197
198     /**
199      * Creates a folder resource given the folder handle.
200      *
201      * @param folderHandle
202      * the folder handle to create a folder resource for
203      * @param monitor
204      * the progress monitor to show visual progress with
205      * @exception CoreException
206      * if the operation fails
207      * @exception OperationCanceledException
208      * if the operation is canceled
209      *
210      * @deprecated As of 3.3, use {@link #createNewFolder()} which uses the
211      * undoable operation support.
212      */

213     protected void createFolder(IFolder folderHandle, IProgressMonitor monitor)
214             throws CoreException {
215         try {
216             // Create the folder resource in the workspace
217
// Update: Recursive to create any folders which do not exist
218
// already
219
if (!folderHandle.exists()) {
220                 if (linkTargetPath != null) {
221                     folderHandle.createLink(linkTargetPath,
222                             IResource.ALLOW_MISSING_LOCAL, monitor);
223                 } else {
224                     IPath path = folderHandle.getFullPath();
225                     IWorkspaceRoot root = ResourcesPlugin.getWorkspace()
226                             .getRoot();
227                     int numSegments = path.segmentCount();
228                     if (numSegments > 2
229                             && !root.getFolder(path.removeLastSegments(1))
230                                     .exists()) {
231                         // If the direct parent of the path doesn't exist, try
232
// to create the
233
// necessary directories.
234
for (int i = numSegments - 2; i > 0; i--) {
235                             IFolder folder = root.getFolder(path
236                                     .removeLastSegments(i));
237                             if (!folder.exists()) {
238                                 folder.create(false, true, monitor);
239                             }
240                         }
241                     }
242                     folderHandle.create(false, true, monitor);
243                 }
244             }
245         } catch (CoreException e) {
246             // If the folder already existed locally, just refresh to get
247
// contents
248
if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) {
249                 folderHandle.refreshLocal(IResource.DEPTH_INFINITE,
250                         new SubProgressMonitor(monitor, 500));
251             } else {
252                 throw e;
253             }
254         }
255
256         if (monitor.isCanceled()) {
257             throw new OperationCanceledException();
258         }
259     }
260
261     /**
262      * Creates a folder resource handle for the folder with the given workspace
263      * path. This method does not create the folder resource; this is the
264      * responsibility of <code>createFolder</code>.
265      *
266      * @param folderPath
267      * the path of the folder resource to create a handle for
268      * @return the new folder resource handle
269      * @see #createFolder
270      */

271     protected IFolder createFolderHandle(IPath folderPath) {
272         return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(
273                 folderPath);
274     }
275
276     /**
277      * Creates the link target path if a link target has been specified.
278      */

279     protected void createLinkTarget() {
280         linkTargetPath = linkedResourceGroup.getLinkTargetURI();
281     }
282
283     /**
284      * Creates a new folder resource in the selected container and with the
285      * selected name. Creates any missing resource containers along the path;
286      * does nothing if the container resources already exist.
287      * <p>
288      * In normal usage, this method is invoked after the user has pressed Finish
289      * on the wizard; the enablement of the Finish button implies that all
290      * controls on this page currently contain valid values.
291      * </p>
292      * <p>
293      * Note that this page caches the new folder once it has been successfully
294      * created; subsequent invocations of this method will answer the same
295      * folder resource without attempting to create it again.
296      * </p>
297      * <p>
298      * This method should be called within a workspace modify operation since it
299      * creates resources.
300      * </p>
301      *
302      * @return the created folder resource, or <code>null</code> if the folder
303      * was not created
304      */

305     public IFolder createNewFolder() {
306         if (newFolder != null) {
307             return newFolder;
308         }
309
310         // create the new folder and cache it if successful
311
final IPath containerPath = resourceGroup.getContainerFullPath();
312         IPath newFolderPath = containerPath.append(resourceGroup.getResource());
313         final IFolder newFolderHandle = createFolderHandle(newFolderPath);
314
315         createLinkTarget();
316         IRunnableWithProgress op = new IRunnableWithProgress() {
317             public void run(IProgressMonitor monitor) {
318                 CreateFolderOperation op = new CreateFolderOperation(
319                         newFolderHandle, linkTargetPath,
320                         IDEWorkbenchMessages.WizardNewFolderCreationPage_title);
321                 try {
322                     PlatformUI.getWorkbench().getOperationSupport()
323                             .getOperationHistory().execute(
324                                     op,
325                                     monitor,
326                                     WorkspaceUndoUtil
327                                             .getUIInfoAdapter(getShell()));
328                 } catch (final ExecutionException e) {
329                     getContainer().getShell().getDisplay().syncExec(
330                             new Runnable JavaDoc() {
331                                 public void run() {
332                                     if (e.getCause() instanceof CoreException) {
333                                         ErrorDialog
334                                                 .openError(
335                                                         getContainer()
336                                                                 .getShell(), // Was Utilities.getFocusShell()
337
IDEWorkbenchMessages.WizardNewFolderCreationPage_errorTitle,
338                                                         null, // no special message
339
((CoreException) e
340                                                                 .getCause())
341                                                                 .getStatus());
342                                     } else {
343                                         IDEWorkbenchPlugin
344                                                 .log(
345                                                         getClass(),
346                                                         "createNewFolder()", e.getCause()); //$NON-NLS-1$
347
MessageDialog
348                                                 .openError(
349                                                         getContainer()
350                                                                 .getShell(),
351                                                         IDEWorkbenchMessages.WizardNewFolderCreationPage_internalErrorTitle,
352                                                         NLS
353                                                                 .bind(
354                                                                         IDEWorkbenchMessages.WizardNewFolder_internalError,
355                                                                         e
356                                                                                 .getCause()
357                                                                                 .getMessage()));
358                                     }
359                                 }
360                             });
361                 }
362             }
363         };
364
365         try {
366             getContainer().run(true, true, op);
367         } catch (InterruptedException JavaDoc e) {
368             return null;
369         } catch (InvocationTargetException JavaDoc e) {
370             // ExecutionExceptions are handled above, but unexpected runtime
371
// exceptions and errors may still occur.
372
IDEWorkbenchPlugin.log(getClass(),
373                     "createNewFolder()", e.getTargetException()); //$NON-NLS-1$
374
MessageDialog
375                     .openError(
376                             getContainer().getShell(),
377                             IDEWorkbenchMessages.WizardNewFolderCreationPage_internalErrorTitle,
378                             NLS
379                                     .bind(
380                                             IDEWorkbenchMessages.WizardNewFolder_internalError,
381                                             e.getTargetException().getMessage()));
382             return null;
383         }
384
385         newFolder = newFolderHandle;
386
387         return newFolder;
388     }
389
390     /**
391      * Shows/hides the advanced option widgets.
392      */

393     protected void handleAdvancedButtonSelect() {
394         Shell shell = getShell();
395         Point shellSize = shell.getSize();
396         Composite composite = (Composite) getControl();
397
398         if (linkedResourceComposite != null) {
399             linkedResourceComposite.dispose();
400             linkedResourceComposite = null;
401             composite.layout();
402             shell.setSize(shellSize.x, shellSize.y - linkedResourceGroupHeight);
403             advancedButton.setText(IDEWorkbenchMessages.showAdvanced);
404         } else {
405             linkedResourceComposite = linkedResourceGroup
406                     .createContents(linkedResourceParent);
407             if (linkedResourceGroupHeight == -1) {
408                 Point groupSize = linkedResourceComposite.computeSize(
409                         SWT.DEFAULT, SWT.DEFAULT, true);
410                 linkedResourceGroupHeight = groupSize.y;
411             }
412             shell.setSize(shellSize.x, shellSize.y + linkedResourceGroupHeight);
413             composite.layout();
414             advancedButton.setText(IDEWorkbenchMessages.hideAdvanced);
415         }
416     }
417
418     /**
419      * The <code>WizardNewFolderCreationPage</code> implementation of this
420      * <code>Listener</code> method handles all events and enablements for
421      * controls on this page. Subclasses may extend.
422      */

423     public void handleEvent(Event ev) {
424         setPageComplete(validatePage());
425     }
426
427     /**
428      * Initializes this page's controls.
429      */

430     protected void initializePage() {
431         Iterator JavaDoc it = currentSelection.iterator();
432         if (it.hasNext()) {
433             Object JavaDoc next = it.next();
434             IResource selectedResource = null;
435             if (next instanceof IResource) {
436                 selectedResource = (IResource) next;
437             } else if (next instanceof IAdaptable) {
438                 selectedResource = (IResource) ((IAdaptable) next)
439                         .getAdapter(IResource.class);
440             }
441             if (selectedResource != null) {
442                 if (selectedResource.getType() == IResource.FILE) {
443                     selectedResource = selectedResource.getParent();
444                 }
445                 if (selectedResource.isAccessible()) {
446                     resourceGroup.setContainerFullPath(selectedResource
447                             .getFullPath());
448                 }
449             }
450         }
451
452         setPageComplete(false);
453     }
454
455     /*
456      * @see DialogPage.setVisible(boolean)
457      */

458     public void setVisible(boolean visible) {
459         super.setVisible(visible);
460         if (visible) {
461             resourceGroup.setFocus();
462         }
463     }
464
465     /**
466      * Checks whether the linked resource target is valid. Sets the error
467      * message accordingly and returns the status.
468      *
469      * @return IStatus validation result from the CreateLinkedResourceGroup
470      */

471     protected IStatus validateLinkedResource() {
472         IPath containerPath = resourceGroup.getContainerFullPath();
473         IPath newFolderPath = containerPath.append(resourceGroup.getResource());
474         IFolder newFolderHandle = createFolderHandle(newFolderPath);
475         IStatus status = linkedResourceGroup
476                 .validateLinkLocation(newFolderHandle);
477
478         if (status.getSeverity() == IStatus.ERROR) {
479             if (firstLinkCheck) {
480                 setMessage(status.getMessage());
481             } else {
482                 setErrorMessage(status.getMessage());
483             }
484         } else if (status.getSeverity() == IStatus.WARNING) {
485             setMessage(status.getMessage(), WARNING);
486             setErrorMessage(null);
487         }
488         return status;
489     }
490
491     /**
492      * Returns whether this page's controls currently all contain valid values.
493      *
494      * @return <code>true</code> if all controls are valid, and
495      * <code>false</code> if at least one is invalid
496      */

497     protected boolean validatePage() {
498         boolean valid = true;
499
500         if (!resourceGroup.areAllValuesValid()) {
501             // if blank name then fail silently
502
if (resourceGroup.getProblemType() == ResourceAndContainerGroup.PROBLEM_RESOURCE_EMPTY
503                     || resourceGroup.getProblemType() == ResourceAndContainerGroup.PROBLEM_CONTAINER_EMPTY) {
504                 setMessage(resourceGroup.getProblemMessage());
505                 setErrorMessage(null);
506             } else {
507                 setErrorMessage(resourceGroup.getProblemMessage());
508             }
509             valid = false;
510         }
511
512         IStatus linkedResourceStatus = null;
513         if (valid) {
514             linkedResourceStatus = validateLinkedResource();
515             if (linkedResourceStatus.getSeverity() == IStatus.ERROR) {
516                 valid = false;
517             }
518         }
519         // validateLinkedResource sets messages itself
520
if (valid
521                 && (linkedResourceStatus == null || linkedResourceStatus.isOK())) {
522             setMessage(null);
523             setErrorMessage(null);
524         }
525         return valid;
526     }
527
528 }
529
Popular Tags