KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > wizards > newresource > BasicNewProjectResourceWizard


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
12 package org.eclipse.ui.wizards.newresource;
13
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.net.URI JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.Set JavaDoc;
20 import java.util.StringTokenizer JavaDoc;
21
22 import org.eclipse.core.commands.ExecutionException;
23 import org.eclipse.core.resources.IProject;
24 import org.eclipse.core.resources.IProjectDescription;
25 import org.eclipse.core.resources.IResourceStatus;
26 import org.eclipse.core.resources.IWorkspace;
27 import org.eclipse.core.resources.ResourcesPlugin;
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.IConfigurationElement;
30 import org.eclipse.core.runtime.IExecutableExtension;
31 import org.eclipse.core.runtime.IProgressMonitor;
32 import org.eclipse.core.runtime.IStatus;
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.IDialogSettings;
37 import org.eclipse.jface.dialogs.MessageDialogWithToggle;
38 import org.eclipse.jface.operation.IRunnableWithProgress;
39 import org.eclipse.jface.preference.IPreferenceStore;
40 import org.eclipse.jface.resource.ImageDescriptor;
41 import org.eclipse.jface.viewers.IStructuredSelection;
42 import org.eclipse.osgi.util.NLS;
43 import org.eclipse.ui.IPerspectiveDescriptor;
44 import org.eclipse.ui.IPerspectiveRegistry;
45 import org.eclipse.ui.IPluginContribution;
46 import org.eclipse.ui.IWorkbench;
47 import org.eclipse.ui.IWorkbenchPage;
48 import org.eclipse.ui.IWorkbenchPreferenceConstants;
49 import org.eclipse.ui.IWorkbenchWindow;
50 import org.eclipse.ui.PlatformUI;
51 import org.eclipse.ui.WorkbenchException;
52 import org.eclipse.ui.activities.IActivityManager;
53 import org.eclipse.ui.activities.IIdentifier;
54 import org.eclipse.ui.activities.IWorkbenchActivitySupport;
55 import org.eclipse.ui.activities.WorkbenchActivityHelper;
56 import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
57 import org.eclipse.ui.dialogs.WizardNewProjectReferencePage;
58 import org.eclipse.ui.ide.IDE;
59 import org.eclipse.ui.ide.undo.CreateProjectOperation;
60 import org.eclipse.ui.ide.undo.WorkspaceUndoUtil;
61 import org.eclipse.ui.internal.IPreferenceConstants;
62 import org.eclipse.ui.internal.WorkbenchPlugin;
63 import org.eclipse.ui.internal.ide.IDEInternalPreferences;
64 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
65 import org.eclipse.ui.internal.ide.StatusUtil;
66 import org.eclipse.ui.internal.registry.PerspectiveDescriptor;
67 import org.eclipse.ui.internal.util.PrefUtil;
68 import org.eclipse.ui.internal.wizards.newresource.ResourceMessages;
69 import org.eclipse.ui.statushandlers.StatusAdapter;
70 import org.eclipse.ui.statushandlers.StatusManager;
71
72 /**
73  * Standard workbench wizard that creates a new project resource in the
74  * workspace.
75  * <p>
76  * This class may be instantiated and used without further configuration; this
77  * class is not intended to be subclassed.
78  * </p>
79  * <p>
80  * Example:
81  *
82  * <pre>
83  * IWorkbenchWizard wizard = new BasicNewProjectResourceWizard();
84  * wizard.init(workbench, selection);
85  * WizardDialog dialog = new WizardDialog(shell, wizard);
86  * dialog.open();
87  * </pre>
88  *
89  * During the call to <code>open</code>, the wizard dialog is presented to
90  * the user. When the user hits Finish, a project resource with the
91  * user-specified name is created, the dialog closes, and the call to
92  * <code>open</code> returns.
93  * </p>
94  */

95 public class BasicNewProjectResourceWizard extends BasicNewResourceWizard
96         implements IExecutableExtension {
97     private WizardNewProjectCreationPage mainPage;
98
99     private WizardNewProjectReferencePage referencePage;
100
101     // cache of newly-created project
102
private IProject newProject;
103
104     /**
105      * The config element which declares this wizard.
106      */

107     private IConfigurationElement configElement;
108
109     private static String JavaDoc WINDOW_PROBLEMS_TITLE = ResourceMessages.NewProject_errorOpeningWindow;
110
111     /**
112      * Extension attribute name for final perspective.
113      */

114     private static final String JavaDoc FINAL_PERSPECTIVE = "finalPerspective"; //$NON-NLS-1$
115

116     /**
117      * Extension attribute name for preferred perspectives.
118      */

119     private static final String JavaDoc PREFERRED_PERSPECTIVES = "preferredPerspectives"; //$NON-NLS-1$
120

121     /**
122      * Creates a wizard for creating a new project resource in the workspace.
123      */

124     public BasicNewProjectResourceWizard() {
125         IDialogSettings workbenchSettings = IDEWorkbenchPlugin.getDefault()
126                 .getDialogSettings();
127         IDialogSettings section = workbenchSettings
128                 .getSection("BasicNewProjectResourceWizard");//$NON-NLS-1$
129
if (section == null) {
130             section = workbenchSettings
131                     .addNewSection("BasicNewProjectResourceWizard");//$NON-NLS-1$
132
}
133         setDialogSettings(section);
134     }
135
136     /*
137      * (non-Javadoc) Method declared on IWizard.
138      */

139     public void addPages() {
140         super.addPages();
141
142         mainPage = new WizardNewProjectCreationPage("basicNewProjectPage");//$NON-NLS-1$
143
mainPage.setTitle(ResourceMessages.NewProject_title);
144         mainPage.setDescription(ResourceMessages.NewProject_description);
145         this.addPage(mainPage);
146
147         // only add page if there are already projects in the workspace
148
if (ResourcesPlugin.getWorkspace().getRoot().getProjects().length > 0) {
149             referencePage = new WizardNewProjectReferencePage(
150                     "basicReferenceProjectPage");//$NON-NLS-1$
151
referencePage.setTitle(ResourceMessages.NewProject_referenceTitle);
152             referencePage
153                     .setDescription(ResourceMessages.NewProject_referenceDescription);
154             this.addPage(referencePage);
155         }
156     }
157
158     /**
159      * Creates a new project resource with the selected name.
160      * <p>
161      * In normal usage, this method is invoked after the user has pressed Finish
162      * on the wizard; the enablement of the Finish button implies that all
163      * controls on the pages currently contain valid values.
164      * </p>
165      * <p>
166      * Note that this wizard caches the new project once it has been
167      * successfully created; subsequent invocations of this method will answer
168      * the same project resource without attempting to create it again.
169      * </p>
170      *
171      * @return the created project resource, or <code>null</code> if the
172      * project was not created
173      */

174     private IProject createNewProject() {
175         if (newProject != null) {
176             return newProject;
177         }
178
179         // get a project handle
180
final IProject newProjectHandle = mainPage.getProjectHandle();
181
182         // get a project descriptor
183
URI JavaDoc location = null;
184         if (!mainPage.useDefaults()) {
185             location = mainPage.getLocationURI();
186         }
187
188         IWorkspace workspace = ResourcesPlugin.getWorkspace();
189         final IProjectDescription description = workspace
190                 .newProjectDescription(newProjectHandle.getName());
191         description.setLocationURI(location);
192
193         // update the referenced project if provided
194
if (referencePage != null) {
195             IProject[] refProjects = referencePage.getReferencedProjects();
196             if (refProjects.length > 0) {
197                 description.setReferencedProjects(refProjects);
198             }
199         }
200
201         // create the new project operation
202
IRunnableWithProgress op = new IRunnableWithProgress() {
203             public void run(IProgressMonitor monitor)
204                     throws InvocationTargetException JavaDoc {
205                 CreateProjectOperation op = new CreateProjectOperation(
206                         description, ResourceMessages.NewProject_windowTitle);
207                 try {
208                     PlatformUI.getWorkbench().getOperationSupport()
209                             .getOperationHistory().execute(
210                                     op,
211                                     monitor,
212                                     WorkspaceUndoUtil
213                                             .getUIInfoAdapter(getShell()));
214                 } catch (ExecutionException e) {
215                     throw new InvocationTargetException JavaDoc(e);
216                 }
217             }
218         };
219
220         // run the new project creation operation
221
try {
222             getContainer().run(true, true, op);
223         } catch (InterruptedException JavaDoc e) {
224             return null;
225         } catch (InvocationTargetException JavaDoc e) {
226             Throwable JavaDoc t = e.getTargetException();
227             if (t instanceof ExecutionException
228                     && t.getCause() instanceof CoreException) {
229                 CoreException cause = (CoreException) t.getCause();
230                 StatusAdapter status;
231                 if (cause.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
232                     status = new StatusAdapter(
233                             StatusUtil
234                                     .newStatus(
235                                             IStatus.WARNING,
236                                             NLS
237                                                     .bind(
238                                                             ResourceMessages.NewProject_caseVariantExistsError,
239                                                             newProjectHandle
240                                                                     .getName()),
241                                             cause));
242                 } else {
243                     status = new StatusAdapter(StatusUtil.newStatus(cause
244                             .getStatus().getSeverity(),
245                             ResourceMessages.NewProject_errorMessage, cause));
246                 }
247                 status.setProperty(StatusAdapter.TITLE_PROPERTY,
248                         ResourceMessages.NewProject_errorMessage);
249                 StatusManager.getManager().handle(status, StatusManager.BLOCK);
250             } else {
251                 StatusAdapter status = new StatusAdapter(new Status(
252                         IStatus.WARNING, IDEWorkbenchPlugin.IDE_WORKBENCH, 0,
253                         NLS.bind(ResourceMessages.NewProject_internalError, t
254                                 .getMessage()), t));
255                 status.setProperty(StatusAdapter.TITLE_PROPERTY,
256                         ResourceMessages.NewProject_errorMessage);
257                 StatusManager.getManager().handle(status,
258                         StatusManager.LOG | StatusManager.BLOCK);
259             }
260             return null;
261         }
262
263         newProject = newProjectHandle;
264
265         return newProject;
266     }
267
268     /**
269      * Returns the newly created project.
270      *
271      * @return the created project, or <code>null</code> if project not
272      * created
273      */

274     public IProject getNewProject() {
275         return newProject;
276     }
277
278     /*
279      * (non-Javadoc) Method declared on IWorkbenchWizard.
280      */

281     public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
282         super.init(workbench, currentSelection);
283         setNeedsProgressMonitor(true);
284         setWindowTitle(ResourceMessages.NewProject_windowTitle);
285     }
286
287     /*
288      * (non-Javadoc) Method declared on BasicNewResourceWizard.
289      */

290     protected void initializeDefaultPageImageDescriptor() {
291         ImageDescriptor desc = IDEWorkbenchPlugin
292                 .getIDEImageDescriptor("wizban/newprj_wiz.png");//$NON-NLS-1$
293
setDefaultPageImageDescriptor(desc);
294     }
295
296     /*
297      * (non-Javadoc) Opens a new window with a particular perspective and input.
298      */

299     private static void openInNewWindow(IPerspectiveDescriptor desc) {
300
301         // Open the page.
302
try {
303             PlatformUI.getWorkbench().openWorkbenchWindow(desc.getId(),
304                     ResourcesPlugin.getWorkspace().getRoot());
305         } catch (WorkbenchException e) {
306             IWorkbenchWindow window = PlatformUI.getWorkbench()
307                     .getActiveWorkbenchWindow();
308             if (window != null) {
309                 ErrorDialog.openError(window.getShell(), WINDOW_PROBLEMS_TITLE,
310                         e.getMessage(), e.getStatus());
311             }
312         }
313     }
314
315     /*
316      * (non-Javadoc) Method declared on IWizard.
317      */

318     public boolean performFinish() {
319         createNewProject();
320
321         if (newProject == null) {
322             return false;
323         }
324
325         updatePerspective();
326         selectAndReveal(newProject);
327
328         return true;
329     }
330
331     /*
332      * (non-Javadoc) Replaces the current perspective with the new one.
333      */

334     private static void replaceCurrentPerspective(IPerspectiveDescriptor persp) {
335
336         // Get the active page.
337
IWorkbenchWindow window = PlatformUI.getWorkbench()
338                 .getActiveWorkbenchWindow();
339         if (window == null) {
340             return;
341         }
342         IWorkbenchPage page = window.getActivePage();
343         if (page == null) {
344             return;
345         }
346
347         // Set the perspective.
348
page.setPerspective(persp);
349     }
350
351     /**
352      * Stores the configuration element for the wizard. The config element will
353      * be used in <code>performFinish</code> to set the result perspective.
354      */

355     public void setInitializationData(IConfigurationElement cfig,
356             String JavaDoc propertyName, Object JavaDoc data) {
357         configElement = cfig;
358     }
359
360     /**
361      * Updates the perspective for the active page within the window.
362      */

363     protected void updatePerspective() {
364         updatePerspective(configElement);
365     }
366
367     /**
368      * Updates the perspective based on the current settings in the
369      * Workbench/Perspectives preference page.
370      *
371      * Use the setting for the new perspective opening if we are set to open in
372      * a new perspective.
373      * <p>
374      * A new project wizard class will need to implement the
375      * <code>IExecutableExtension</code> interface so as to gain access to the
376      * wizard's <code>IConfigurationElement</code>. That is the configuration
377      * element to pass into this method.
378      * </p>
379      *
380      * @param configElement -
381      * the element we are updating with
382      *
383      * @see IPreferenceConstants#OPM_NEW_WINDOW
384      * @see IPreferenceConstants#OPM_ACTIVE_PAGE
385      * @see IWorkbenchPreferenceConstants#NO_NEW_PERSPECTIVE
386      */

387     public static void updatePerspective(IConfigurationElement configElement) {
388         // Do not change perspective if the configuration element is
389
// not specified.
390
if (configElement == null) {
391             return;
392         }
393
394         // Retrieve the new project open perspective preference setting
395
String JavaDoc perspSetting = PrefUtil.getAPIPreferenceStore().getString(
396                 IDE.Preferences.PROJECT_OPEN_NEW_PERSPECTIVE);
397
398         String JavaDoc promptSetting = IDEWorkbenchPlugin.getDefault()
399                 .getPreferenceStore().getString(
400                         IDEInternalPreferences.PROJECT_SWITCH_PERSP_MODE);
401
402         // Return if do not switch perspective setting and are not prompting
403
if (!(promptSetting.equals(MessageDialogWithToggle.PROMPT))
404                 && perspSetting
405                         .equals(IWorkbenchPreferenceConstants.NO_NEW_PERSPECTIVE)) {
406             return;
407         }
408
409         // Read the requested perspective id to be opened.
410
String JavaDoc finalPerspId = configElement.getAttribute(FINAL_PERSPECTIVE);
411         if (finalPerspId == null) {
412             return;
413         }
414
415         // Map perspective id to descriptor.
416
IPerspectiveRegistry reg = PlatformUI.getWorkbench()
417                 .getPerspectiveRegistry();
418
419         // leave this code in - the perspective of a given project may map to
420
// activities other than those that the wizard itself maps to.
421
IPerspectiveDescriptor finalPersp = reg
422                 .findPerspectiveWithId(finalPerspId);
423         if (finalPersp != null && finalPersp instanceof IPluginContribution) {
424             IPluginContribution contribution = (IPluginContribution) finalPersp;
425             if (contribution.getPluginId() != null) {
426                 IWorkbenchActivitySupport workbenchActivitySupport = PlatformUI
427                         .getWorkbench().getActivitySupport();
428                 IActivityManager activityManager = workbenchActivitySupport
429                         .getActivityManager();
430                 IIdentifier identifier = activityManager
431                         .getIdentifier(WorkbenchActivityHelper
432                                 .createUnifiedId(contribution));
433                 Set JavaDoc idActivities = identifier.getActivityIds();
434
435                 if (!idActivities.isEmpty()) {
436                     Set JavaDoc enabledIds = new HashSet JavaDoc(activityManager
437                             .getEnabledActivityIds());
438
439                     if (enabledIds.addAll(idActivities)) {
440                         workbenchActivitySupport
441                                 .setEnabledActivityIds(enabledIds);
442                     }
443                 }
444             }
445         } else {
446             IDEWorkbenchPlugin.log("Unable to find persective " //$NON-NLS-1$
447
+ finalPerspId
448                     + " in BasicNewProjectResourceWizard.updatePerspective"); //$NON-NLS-1$
449
return;
450         }
451
452         // gather the preferred perspectives
453
// always consider the final perspective (and those derived from it)
454
// to be preferred
455
ArrayList JavaDoc preferredPerspIds = new ArrayList JavaDoc();
456         addPerspectiveAndDescendants(preferredPerspIds, finalPerspId);
457         String JavaDoc preferred = configElement.getAttribute(PREFERRED_PERSPECTIVES);
458         if (preferred != null) {
459             StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(preferred, " \t\n\r\f,"); //$NON-NLS-1$
460
while (tok.hasMoreTokens()) {
461                 addPerspectiveAndDescendants(preferredPerspIds, tok.nextToken());
462             }
463         }
464
465         IWorkbenchWindow window = PlatformUI.getWorkbench()
466                 .getActiveWorkbenchWindow();
467         if (window != null) {
468             IWorkbenchPage page = window.getActivePage();
469             if (page != null) {
470                 IPerspectiveDescriptor currentPersp = page.getPerspective();
471
472                 // don't switch if the current perspective is a preferred
473
// perspective
474
if (currentPersp != null
475                         && preferredPerspIds.contains(currentPersp.getId())) {
476                     return;
477                 }
478             }
479
480             // prompt the user to switch
481
if (!confirmPerspectiveSwitch(window, finalPersp)) {
482                 return;
483             }
484         }
485
486         int workbenchPerspectiveSetting = WorkbenchPlugin.getDefault()
487                 .getPreferenceStore().getInt(
488                         IPreferenceConstants.OPEN_PERSP_MODE);
489
490         // open perspective in new window setting
491
if (workbenchPerspectiveSetting == IPreferenceConstants.OPM_NEW_WINDOW) {
492             openInNewWindow(finalPersp);
493             return;
494         }
495
496         // replace active perspective setting otherwise
497
replaceCurrentPerspective(finalPersp);
498     }
499
500     /**
501      * Adds to the list all perspective IDs in the Workbench who's original ID
502      * matches the given ID.
503      *
504      * @param perspectiveIds
505      * the list of perspective IDs to supplement.
506      * @param id
507      * the id to query.
508      * @since 3.0
509      */

510     private static void addPerspectiveAndDescendants(List JavaDoc perspectiveIds,
511             String JavaDoc id) {
512         IPerspectiveRegistry registry = PlatformUI.getWorkbench()
513                 .getPerspectiveRegistry();
514         IPerspectiveDescriptor[] perspectives = registry.getPerspectives();
515         for (int i = 0; i < perspectives.length; i++) {
516             // @issue illegal ref to workbench internal class;
517
// consider adding getOriginalId() as API on IPerspectiveDescriptor
518
PerspectiveDescriptor descriptor = ((PerspectiveDescriptor) perspectives[i]);
519             if (descriptor.getOriginalId().equals(id)) {
520                 perspectiveIds.add(descriptor.getId());
521             }
522         }
523     }
524
525     /**
526      * Prompts the user for whether to switch perspectives.
527      *
528      * @param window
529      * The workbench window in which to switch perspectives; must not
530      * be <code>null</code>
531      * @param finalPersp
532      * The perspective to switch to; must not be <code>null</code>.
533      *
534      * @return <code>true</code> if it's OK to switch, <code>false</code>
535      * otherwise
536      */

537     private static boolean confirmPerspectiveSwitch(IWorkbenchWindow window,
538             IPerspectiveDescriptor finalPersp) {
539         IPreferenceStore store = IDEWorkbenchPlugin.getDefault()
540                 .getPreferenceStore();
541         String JavaDoc pspm = store
542                 .getString(IDEInternalPreferences.PROJECT_SWITCH_PERSP_MODE);
543         if (!IDEInternalPreferences.PSPM_PROMPT.equals(pspm)) {
544             // Return whether or not we should always switch
545
return IDEInternalPreferences.PSPM_ALWAYS.equals(pspm);
546         }
547         String JavaDoc desc = finalPersp.getDescription();
548         String JavaDoc message;
549         if (desc == null || desc.length() == 0)
550             message = NLS.bind(ResourceMessages.NewProject_perspSwitchMessage,
551                     finalPersp.getLabel());
552         else
553             message = NLS.bind(
554                     ResourceMessages.NewProject_perspSwitchMessageWithDesc,
555                     new String JavaDoc[] { finalPersp.getLabel(), desc });
556
557         MessageDialogWithToggle dialog = MessageDialogWithToggle
558                 .openYesNoQuestion(window.getShell(),
559                         ResourceMessages.NewProject_perspSwitchTitle, message,
560                         null /* use the default message for the toggle */,
561                         false /* toggle is initially unchecked */, store,
562                         IDEInternalPreferences.PROJECT_SWITCH_PERSP_MODE);
563         int result = dialog.getReturnCode();
564
565         // If we are not going to prompt anymore propogate the choice.
566
if (dialog.getToggleState()) {
567             String JavaDoc preferenceValue;
568             if (result == IDialogConstants.YES_ID) {
569                 // Doesn't matter if it is replace or new window
570
// as we are going to use the open perspective setting
571
preferenceValue = IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE;
572             } else {
573                 preferenceValue = IWorkbenchPreferenceConstants.NO_NEW_PERSPECTIVE;
574             }
575
576             // update PROJECT_OPEN_NEW_PERSPECTIVE to correspond
577
PrefUtil.getAPIPreferenceStore().setValue(
578                     IDE.Preferences.PROJECT_OPEN_NEW_PERSPECTIVE,
579                     preferenceValue);
580         }
581         return result == IDialogConstants.YES_ID;
582     }
583 }
584
Popular Tags