KickJava   Java API By Example, From Geeks To Geeks.

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


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  * Sebastian Davids <sdavids@gmx.de> - Fix for bug 19346 - Dialog
11  * font should be activated and used by other components.
12  *******************************************************************************/

13
14 package org.eclipse.ui.dialogs;
15
16 import java.lang.reflect.InvocationTargetException JavaDoc;
17 import java.net.URI JavaDoc;
18 import org.eclipse.core.resources.IContainer;
19 import org.eclipse.core.resources.IFolder;
20 import org.eclipse.core.resources.IProject;
21 import org.eclipse.core.resources.IProjectNatureDescriptor;
22 import org.eclipse.core.resources.IResource;
23 import org.eclipse.core.resources.IWorkspace;
24 import org.eclipse.core.resources.IWorkspaceRoot;
25 import org.eclipse.core.resources.ResourcesPlugin;
26 import org.eclipse.core.runtime.CoreException;
27 import org.eclipse.core.runtime.IPath;
28 import org.eclipse.core.runtime.IProgressMonitor;
29 import org.eclipse.core.runtime.IStatus;
30 import org.eclipse.core.runtime.OperationCanceledException;
31 import org.eclipse.core.runtime.Path;
32 import org.eclipse.core.runtime.Preferences;
33 import org.eclipse.core.runtime.Status;
34 import org.eclipse.jface.dialogs.ErrorDialog;
35 import org.eclipse.jface.dialogs.IDialogConstants;
36 import org.eclipse.jface.dialogs.MessageDialog;
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.Font;
42 import org.eclipse.swt.graphics.Point;
43 import org.eclipse.swt.layout.GridData;
44 import org.eclipse.swt.layout.GridLayout;
45 import org.eclipse.swt.widgets.Button;
46 import org.eclipse.swt.widgets.Composite;
47 import org.eclipse.swt.widgets.Control;
48 import org.eclipse.swt.widgets.Event;
49 import org.eclipse.swt.widgets.Label;
50 import org.eclipse.swt.widgets.Listener;
51 import org.eclipse.swt.widgets.Shell;
52 import org.eclipse.swt.widgets.Text;
53 import org.eclipse.ui.PlatformUI;
54 import org.eclipse.ui.actions.WorkspaceModifyOperation;
55 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
56 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
57 import org.eclipse.ui.internal.ide.IIDEHelpContextIds;
58 import org.eclipse.ui.internal.ide.dialogs.CreateLinkedResourceGroup;
59
60 /**
61  * The NewFolderDialog is used to create a new folder.
62  * The folder can optionally be linked to a file system folder.
63  * <p>
64  * This class may be instantiated; it is not intended to be subclassed.
65  * </p>
66  */

67 public class NewFolderDialog extends SelectionStatusDialog {
68     // widgets
69
private Text folderNameField;
70
71     private Button advancedButton;
72
73     private CreateLinkedResourceGroup linkedResourceGroup;
74
75     private IContainer container;
76
77     private boolean firstLinkCheck = true;
78
79     /**
80      * Parent composite of the advanced widget group for creating
81      * linked resources.
82      */

83     private Composite linkedResourceParent;
84
85     /**
86      * Linked resources widget group. Null if advanced section is not visible.
87      */

88     private Composite linkedResourceComposite;
89
90     /**
91      * Height of the dialog without the "advanced" linked resource group.
92      * Set when the advanced group is first made visible.
93      */

94     private int basicShellHeight = -1;
95
96     /**
97      * Creates a NewFolderDialog
98      *
99      * @param parentShell parent of the new dialog
100      * @param container parent of the new folder
101      */

102     public NewFolderDialog(Shell parentShell, IContainer container) {
103         super(parentShell);
104         this.container = container;
105         setTitle(IDEWorkbenchMessages.NewFolderDialog_title);
106         setShellStyle(getShellStyle() | SWT.RESIZE);
107         setStatusLineAboveButtons(true);
108     }
109
110     /**
111      * Creates the folder using the name and link target entered
112      * by the user.
113      * Sets the dialog result to the created folder.
114      */

115     protected void computeResult() {
116         //Do nothing here as we
117
//need to know the result
118
}
119
120     /* (non-Javadoc)
121      * Method declared in Window.
122      */

123     protected void configureShell(Shell shell) {
124         super.configureShell(shell);
125         PlatformUI.getWorkbench().getHelpSystem().setHelp(shell,
126                 IIDEHelpContextIds.NEW_FOLDER_DIALOG);
127     }
128
129     /**
130      * @see org.eclipse.jface.window.Window#create()
131      */

132     public void create() {
133         super.create();
134         // initially disable the ok button since we don't preset the
135
// folder name field
136
getButton(IDialogConstants.OK_ID).setEnabled(false);
137     }
138
139     /**
140      * Creates the widget for advanced options.
141      *
142      * @param parent the parent composite
143      */

144     protected void createAdvancedControls(Composite parent) {
145         Preferences preferences = ResourcesPlugin.getPlugin()
146                 .getPluginPreferences();
147
148         if (preferences.getBoolean(ResourcesPlugin.PREF_DISABLE_LINKING) == false
149                 && isValidContainer()) {
150             linkedResourceParent = new Composite(parent, SWT.NONE);
151             linkedResourceParent.setFont(parent.getFont());
152             linkedResourceParent.setLayoutData(new GridData(
153                     GridData.FILL_HORIZONTAL));
154             GridLayout layout = new GridLayout();
155             layout.marginHeight = 0;
156             layout.marginWidth = 0;
157             linkedResourceParent.setLayout(layout);
158
159             advancedButton = new Button(linkedResourceParent, SWT.PUSH);
160             advancedButton.setFont(linkedResourceParent.getFont());
161             advancedButton.setText(IDEWorkbenchMessages.showAdvanced);
162             setButtonLayoutData(advancedButton);
163             GridData data = (GridData) advancedButton.getLayoutData();
164             data.horizontalAlignment = GridData.BEGINNING;
165             advancedButton.setLayoutData(data);
166             advancedButton.addSelectionListener(new SelectionAdapter() {
167                 public void widgetSelected(SelectionEvent e) {
168                     handleAdvancedButtonSelect();
169                 }
170             });
171         }
172         linkedResourceGroup = new CreateLinkedResourceGroup(IResource.FOLDER,
173                 new Listener() {
174                     public void handleEvent(Event e) {
175                         validateLinkedResource();
176                         firstLinkCheck = false;
177                     }
178                 }, new CreateLinkedResourceGroup.IStringValue() {
179                     public void setValue(String JavaDoc string) {
180                         folderNameField.setText(string);
181                     }
182
183                     public String JavaDoc getValue() {
184                         return folderNameField.getText();
185                     }
186                 });
187     }
188
189     /* (non-Javadoc)
190      * Method declared on Dialog.
191      */

192     protected Control createDialogArea(Composite parent) {
193         Composite composite = (Composite) super.createDialogArea(parent);
194         composite.setLayout(new GridLayout());
195         composite.setLayoutData(new GridData(GridData.FILL_BOTH));
196
197         createFolderNameGroup(composite);
198         createAdvancedControls(composite);
199         return composite;
200     }
201
202     /**
203      * Creates the folder name specification controls.
204      *
205      * @param parent the parent composite
206      */

207     private void createFolderNameGroup(Composite parent) {
208         Font font = parent.getFont();
209         // project specification group
210
Composite folderGroup = new Composite(parent, SWT.NONE);
211         GridLayout layout = new GridLayout();
212         layout.numColumns = 2;
213         folderGroup.setLayout(layout);
214         folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
215
216         // new folder label
217
Label folderLabel = new Label(folderGroup, SWT.NONE);
218         folderLabel.setFont(font);
219         folderLabel.setText(IDEWorkbenchMessages.NewFolderDialog_nameLabel);
220
221         // new folder name entry field
222
folderNameField = new Text(folderGroup, SWT.BORDER);
223         GridData data = new GridData(GridData.FILL_HORIZONTAL);
224         data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH;
225         folderNameField.setLayoutData(data);
226         folderNameField.setFont(font);
227         folderNameField.addListener(SWT.Modify, new Listener() {
228             public void handleEvent(Event event) {
229                 validateLinkedResource();
230             }
231         });
232     }
233
234     /**
235      * Creates a folder resource handle for the folder with the given name.
236      * The folder handle is created relative to the container specified during
237      * object creation.
238      *
239      * @param folderName the name of the folder resource to create a handle for
240      * @return the new folder resource handle
241      */

242     private IFolder createFolderHandle(String JavaDoc folderName) {
243         IWorkspaceRoot workspaceRoot = container.getWorkspace().getRoot();
244         IPath folderPath = container.getFullPath().append(folderName);
245         IFolder folderHandle = workspaceRoot.getFolder(folderPath);
246
247         return folderHandle;
248     }
249
250     /**
251      * Creates a new folder with the given name and optionally linking to
252      * the specified link target.
253      *
254      * @param folderName name of the new folder
255      * @param linkTarget name of the link target folder. may be null.
256      * @return IFolder the new folder
257      */

258     private IFolder createNewFolder(String JavaDoc folderName, final URI JavaDoc linkTarget) {
259         final IFolder folderHandle = createFolderHandle(folderName);
260
261         WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
262             public void execute(IProgressMonitor monitor) throws CoreException {
263                 try {
264                     monitor
265                             .beginTask(
266                                     IDEWorkbenchMessages.NewFolderDialog_progress,
267                                     2000);
268                     if (monitor.isCanceled()) {
269                         throw new OperationCanceledException();
270                     }
271                     if (linkTarget == null) {
272                         folderHandle.create(false, true, monitor);
273                     } else {
274                         folderHandle.createLink(linkTarget,
275                                 IResource.ALLOW_MISSING_LOCAL, monitor);
276                     }
277                     if (monitor.isCanceled()) {
278                         throw new OperationCanceledException();
279                     }
280                 } finally {
281                     monitor.done();
282                 }
283             }
284         };
285         try {
286             PlatformUI.getWorkbench().getProgressService().busyCursorWhile(
287                     operation);
288         } catch (InterruptedException JavaDoc exception) {
289             return null;
290         } catch (InvocationTargetException JavaDoc exception) {
291             if (exception.getTargetException() instanceof CoreException) {
292                 ErrorDialog.openError(getShell(),
293                         IDEWorkbenchMessages.NewFolderDialog_errorTitle, null, // no special message
294
((CoreException) exception.getTargetException())
295                                 .getStatus());
296             } else {
297                 // CoreExceptions are handled above, but unexpected runtime exceptions and errors may still occur.
298
IDEWorkbenchPlugin.log(getClass(),
299                         "createNewFolder", exception.getTargetException()); //$NON-NLS-1$
300
MessageDialog
301                         .openError(
302                                 getShell(),
303                                 IDEWorkbenchMessages.NewFolderDialog_errorTitle,
304                                 NLS
305                                         .bind(
306                                                 IDEWorkbenchMessages.NewFolderDialog_internalError,
307                                                 exception.getTargetException()
308                                                         .getMessage()));
309             }
310             return null;
311         }
312         return folderHandle;
313     }
314
315     /**
316      * Shows/hides the advanced option widgets.
317      */

318     protected void handleAdvancedButtonSelect() {
319         Shell shell = getShell();
320         Point shellSize = shell.getSize();
321         Composite composite = (Composite) getDialogArea();
322
323         if (linkedResourceComposite != null) {
324             linkedResourceComposite.dispose();
325             linkedResourceComposite = null;
326             composite.layout();
327             shell.setSize(shellSize.x, basicShellHeight);
328             advancedButton.setText(IDEWorkbenchMessages.showAdvanced);
329         } else {
330             if (basicShellHeight == -1) {
331                 basicShellHeight = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT,
332                         true).y;
333             }
334             linkedResourceComposite = linkedResourceGroup
335                     .createContents(linkedResourceParent);
336             shellSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
337             shell.setSize(shellSize);
338             composite.layout();
339             advancedButton.setText(IDEWorkbenchMessages.hideAdvanced);
340         }
341     }
342
343     /**
344      * Returns whether the container specified in the constructor is
345      * a valid parent for creating linked resources.
346      *
347      * @return boolean <code>true</code> if the container specified in
348      * the constructor is a valid parent for creating linked resources.
349      * <code>false</code> if no linked resources may be created with the
350      * specified container as a parent.
351      */

352     private boolean isValidContainer() {
353         if (container.getType() != IResource.PROJECT
354                 && container.getType() != IResource.FOLDER) {
355             return false;
356         }
357
358         try {
359             IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
360             IProject project = container.getProject();
361             String JavaDoc[] natureIds = project.getDescription().getNatureIds();
362
363             for (int i = 0; i < natureIds.length; i++) {
364                 IProjectNatureDescriptor descriptor = workspace
365                         .getNatureDescriptor(natureIds[i]);
366                 if (descriptor != null
367                         && descriptor.isLinkingAllowed() == false) {
368                     return false;
369                 }
370             }
371         } catch (CoreException exception) {
372             // project does not exist or is closed
373
return false;
374         }
375         return true;
376     }
377
378     /**
379      * Update the dialog's status line to reflect the given status. It is safe to call
380      * this method before the dialog has been opened.
381      */

382     protected void updateStatus(IStatus status) {
383         if (firstLinkCheck && status != null) {
384             // don't show the first validation result as an error.
385
// fixes bug 29659
386
Status newStatus = new Status(IStatus.OK, status.getPlugin(),
387                     status.getCode(), status.getMessage(), status
388                             .getException());
389             super.updateStatus(newStatus);
390         } else {
391             super.updateStatus(status);
392         }
393     }
394
395     /**
396      * Update the dialog's status line to reflect the given status. It is safe to call
397      * this method before the dialog has been opened.
398      * @param severity
399      * @param message
400      */

401     private void updateStatus(int severity, String JavaDoc message) {
402         updateStatus(new Status(severity, IDEWorkbenchPlugin.IDE_WORKBENCH,
403                 severity, message, null));
404     }
405
406     /**
407      * Checks whether the folder name and link location are valid.
408      * Disable the OK button if the folder name and link location are valid.
409      * a message that indicates the problem otherwise.
410      */

411     private void validateLinkedResource() {
412         boolean valid = validateFolderName();
413
414         if (valid) {
415             IFolder linkHandle = createFolderHandle(folderNameField.getText());
416             IStatus status = linkedResourceGroup
417                     .validateLinkLocation(linkHandle);
418
419             if (status.getSeverity() != IStatus.ERROR) {
420                 getOkButton().setEnabled(true);
421             } else {
422                 getOkButton().setEnabled(false);
423             }
424
425             if (status.isOK() == false) {
426                 updateStatus(status);
427             }
428         } else {
429             getOkButton().setEnabled(false);
430         }
431     }
432
433     /**
434      * Checks if the folder name is valid.
435      *
436      * @return null if the new folder name is valid.
437      * a message that indicates the problem otherwise.
438      */

439     private boolean validateFolderName() {
440         String JavaDoc name = folderNameField.getText();
441         IWorkspace workspace = container.getWorkspace();
442         IStatus nameStatus = workspace.validateName(name, IResource.FOLDER);
443
444         if ("".equals(name)) { //$NON-NLS-1$
445
updateStatus(IStatus.ERROR,
446                     IDEWorkbenchMessages.NewFolderDialog_folderNameEmpty);
447             return false;
448         }
449         if (nameStatus.isOK() == false) {
450             updateStatus(nameStatus);
451             return false;
452         }
453         IPath path = new Path(name);
454         if (container.getFolder(path).exists()
455                 || container.getFile(path).exists()) {
456             updateStatus(IStatus.ERROR, NLS.bind(
457                     IDEWorkbenchMessages.NewFolderDialog_alreadyExists, name));
458             return false;
459         }
460         updateStatus(IStatus.OK, ""); //$NON-NLS-1$
461
return true;
462     }
463
464     /* (non-Javadoc)
465      * @see org.eclipse.ui.dialogs.SelectionStatusDialog#okPressed()
466      */

467     protected void okPressed() {
468         URI JavaDoc linkTarget = linkedResourceGroup.getLinkTargetURI();
469         IFolder folder = createNewFolder(folderNameField.getText(), linkTarget);
470         if (folder == null) {
471             return;
472         }
473
474         setSelectionResult(new IFolder[] { folder });
475
476         super.okPressed();
477     }
478 }
479
Popular Tags