KickJava   Java API By Example, From Geeks To Geeks.

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


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 package org.eclipse.ui.dialogs;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Hashtable JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.List JavaDoc;
17 import java.util.Map JavaDoc;
18 import java.util.Vector JavaDoc;
19
20 import org.eclipse.core.resources.IContainer;
21 import org.eclipse.core.resources.IProject;
22 import org.eclipse.core.resources.IResource;
23 import org.eclipse.core.resources.ResourcesPlugin;
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.jface.dialogs.IDialogConstants;
26 import org.eclipse.jface.viewers.CheckStateChangedEvent;
27 import org.eclipse.jface.viewers.ICheckStateListener;
28 import org.eclipse.jface.viewers.IStructuredSelection;
29 import org.eclipse.jface.viewers.ITreeContentProvider;
30 import org.eclipse.swt.SWT;
31 import org.eclipse.swt.custom.BusyIndicator;
32 import org.eclipse.swt.events.SelectionAdapter;
33 import org.eclipse.swt.events.SelectionEvent;
34 import org.eclipse.swt.events.SelectionListener;
35 import org.eclipse.swt.graphics.Font;
36 import org.eclipse.swt.layout.GridData;
37 import org.eclipse.swt.layout.GridLayout;
38 import org.eclipse.swt.widgets.Button;
39 import org.eclipse.swt.widgets.Composite;
40 import org.eclipse.swt.widgets.Shell;
41 import org.eclipse.ui.ide.IDE;
42 import org.eclipse.ui.internal.ide.DialogUtil;
43 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
44 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
45 import org.eclipse.ui.internal.ide.dialogs.ResourceTreeAndListGroup;
46 import org.eclipse.ui.model.WorkbenchContentProvider;
47 import org.eclipse.ui.model.WorkbenchLabelProvider;
48
49 /**
50  * Abstract superclass for a typical export 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>createDestinationGroup</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  * <li><code>internalSaveWidgetValues</code></li>
72  * <li><code>updateWidgetEnablements</code></li>
73  * </ul>
74  * </p>
75  */

76 public abstract class WizardExportResourcesPage extends WizardDataTransferPage {
77     private IStructuredSelection initialResourceSelection;
78
79     private List JavaDoc selectedTypes = new ArrayList JavaDoc();
80
81     // widgets
82
private ResourceTreeAndListGroup resourceGroup;
83
84     private final static String JavaDoc SELECT_TYPES_TITLE = IDEWorkbenchMessages.WizardTransferPage_selectTypes;
85
86     private final static String JavaDoc SELECT_ALL_TITLE = IDEWorkbenchMessages.WizardTransferPage_selectAll;
87
88     private final static String JavaDoc DESELECT_ALL_TITLE = IDEWorkbenchMessages.WizardTransferPage_deselectAll;
89
90     /**
91      * Creates an export wizard page. If the current resource selection
92      * is not empty then it will be used as the initial collection of resources
93      * selected for export.
94      *
95      * @param pageName the name of the page
96      * @param selection {@link IStructuredSelection} of {@link IResource}
97      * @see IDE#computeSelectedResources(IStructuredSelection)
98      */

99     protected WizardExportResourcesPage(String JavaDoc pageName,
100             IStructuredSelection selection) {
101         super(pageName);
102         this.initialResourceSelection = selection;
103     }
104
105     /**
106      * The <code>addToHierarchyToCheckedStore</code> implementation of this
107      * <code>WizardDataTransferPage</code> method returns <code>false</code>.
108      * Subclasses may override this method.
109      */

110     protected boolean allowNewContainerName() {
111         return false;
112     }
113
114     /**
115      * Creates a new button with the given id.
116      * <p>
117      * The <code>Dialog</code> implementation of this framework method
118      * creates a standard push button, registers for selection events
119      * including button presses and registers
120      * default buttons with its shell.
121      * The button id is stored as the buttons client data.
122      * Note that the parent's layout is assumed to be a GridLayout and
123      * the number of columns in this layout is incremented.
124      * Subclasses may override.
125      * </p>
126      *
127      * @param parent the parent composite
128      * @param id the id of the button (see
129      * <code>IDialogConstants.*_ID</code> constants
130      * for standard dialog button ids)
131      * @param label the label from the button
132      * @param defaultButton <code>true</code> if the button is to be the
133      * default button, and <code>false</code> otherwise
134      */

135     protected Button createButton(Composite parent, int id, String JavaDoc label,
136             boolean defaultButton) {
137         // increment the number of columns in the button bar
138
((GridLayout) parent.getLayout()).numColumns++;
139
140         Button button = new Button(parent, SWT.PUSH);
141
142         GridData buttonData = new GridData(GridData.FILL_HORIZONTAL);
143         button.setLayoutData(buttonData);
144
145         button.setData(new Integer JavaDoc(id));
146         button.setText(label);
147         button.setFont(parent.getFont());
148
149         if (defaultButton) {
150             Shell shell = parent.getShell();
151             if (shell != null) {
152                 shell.setDefaultButton(button);
153             }
154             button.setFocus();
155         }
156         button.setFont(parent.getFont());
157         setButtonLayoutData(button);
158         return button;
159     }
160
161     /**
162      * Creates the buttons for selecting specific types or selecting all or none of the
163      * elements.
164      *
165      * @param parent the parent control
166      */

167     protected final void createButtonsGroup(Composite parent) {
168
169         Font font = parent.getFont();
170
171         // top level group
172
Composite buttonComposite = new Composite(parent, SWT.NONE);
173         buttonComposite.setFont(parent.getFont());
174
175         GridLayout layout = new GridLayout();
176         layout.numColumns = 3;
177         layout.makeColumnsEqualWidth = true;
178         buttonComposite.setLayout(layout);
179         buttonComposite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
180                 | GridData.HORIZONTAL_ALIGN_FILL));
181
182         // types edit button
183
Button selectTypesButton = createButton(buttonComposite,
184                 IDialogConstants.SELECT_TYPES_ID, SELECT_TYPES_TITLE, false);
185
186         SelectionListener listener = new SelectionAdapter() {
187             public void widgetSelected(SelectionEvent e) {
188                 handleTypesEditButtonPressed();
189             }
190         };
191         selectTypesButton.addSelectionListener(listener);
192         selectTypesButton.setFont(font);
193         setButtonLayoutData(selectTypesButton);
194
195         Button selectButton = createButton(buttonComposite,
196                 IDialogConstants.SELECT_ALL_ID, SELECT_ALL_TITLE, false);
197
198         listener = new SelectionAdapter() {
199             public void widgetSelected(SelectionEvent e) {
200                 resourceGroup.setAllSelections(true);
201             }
202         };
203         selectButton.addSelectionListener(listener);
204         selectButton.setFont(font);
205         setButtonLayoutData(selectButton);
206
207         Button deselectButton = createButton(buttonComposite,
208                 IDialogConstants.DESELECT_ALL_ID, DESELECT_ALL_TITLE, false);
209
210         listener = new SelectionAdapter() {
211             public void widgetSelected(SelectionEvent e) {
212                 resourceGroup.setAllSelections(false);
213             }
214         };
215         deselectButton.addSelectionListener(listener);
216         deselectButton.setFont(font);
217         setButtonLayoutData(deselectButton);
218
219     }
220
221     /** (non-Javadoc)
222      * Method declared on IDialogPage.
223      */

224     public void createControl(Composite parent) {
225
226         initializeDialogUnits(parent);
227
228         Composite composite = new Composite(parent, SWT.NULL);
229         composite.setLayout(new GridLayout());
230         composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
231                 | GridData.HORIZONTAL_ALIGN_FILL));
232         composite.setFont(parent.getFont());
233
234         createResourcesGroup(composite);
235         createButtonsGroup(composite);
236
237         createDestinationGroup(composite);
238
239         createOptionsGroup(composite);
240
241         restoreResourceSpecificationWidgetValues(); // ie.- local
242
restoreWidgetValues(); // ie.- subclass hook
243
if (initialResourceSelection != null) {
244             setupBasedOnInitialSelections();
245         }
246
247         updateWidgetEnablements();
248         setPageComplete(determinePageCompletion());
249         setErrorMessage(null); // should not initially have error message
250

251         setControl(composite);
252     }
253
254     /**
255      * Creates the export destination specification visual components.
256      * <p>
257      * Subclasses must implement this method.
258      * </p>
259      *
260      * @param parent the parent control
261      */

262     protected abstract void createDestinationGroup(Composite parent);
263
264     /**
265      * Creates the checkbox tree and list for selecting resources.
266      *
267      * @param parent the parent control
268      */

269     protected final void createResourcesGroup(Composite parent) {
270
271         //create the input element, which has the root resource
272
//as its only child
273
List JavaDoc input = new ArrayList JavaDoc();
274         IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
275                 .getProjects();
276         for (int i = 0; i < projects.length; i++) {
277             if (projects[i].isOpen()) {
278                 input.add(projects[i]);
279             }
280         }
281
282         this.resourceGroup = new ResourceTreeAndListGroup(parent, input,
283                 getResourceProvider(IResource.FOLDER | IResource.PROJECT),
284                 WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(),
285                 getResourceProvider(IResource.FILE), WorkbenchLabelProvider
286                         .getDecoratingWorkbenchLabelProvider(), SWT.NONE,
287                 DialogUtil.inRegularFontMode(parent));
288         
289         ICheckStateListener listener = new ICheckStateListener() {
290             public void checkStateChanged(CheckStateChangedEvent event) {
291                 updateWidgetEnablements();
292             }
293         };
294         
295         this.resourceGroup.addCheckStateListener(listener);
296     }
297
298     /*
299      * @see WizardDataTransferPage.getErrorDialogTitle()
300      */

301     protected String JavaDoc getErrorDialogTitle() {
302         return IDEWorkbenchMessages.WizardExportPage_errorDialogTitle;
303     }
304
305     /**
306      * Obsolete method. This was implemented to handle the case where ensureLocal()
307      * needed to be called but it doesn't use it any longer.
308      *
309      * @deprecated Only retained for backwards compatibility.
310      */

311     protected boolean ensureResourcesLocal(List JavaDoc resources) {
312         return true;
313     }
314
315     /**
316      * Returns a new subcollection containing only those resources which are not
317      * local.
318      *
319      * @param originalList the original list of resources (element type:
320      * <code>IResource</code>)
321      * @return the new list of non-local resources (element type:
322      * <code>IResource</code>)
323      */

324     protected List JavaDoc extractNonLocalResources(List JavaDoc originalList) {
325         Vector JavaDoc result = new Vector JavaDoc(originalList.size());
326         Iterator JavaDoc resourcesEnum = originalList.iterator();
327
328         while (resourcesEnum.hasNext()) {
329             IResource currentResource = (IResource) resourcesEnum.next();
330             if (!currentResource.isLocal(IResource.DEPTH_ZERO)) {
331                 result.addElement(currentResource);
332             }
333         }
334
335         return result;
336     }
337
338     /**
339      * Returns a content provider for <code>IResource</code>s that returns
340      * only children of the given resource type.
341      */

342     private ITreeContentProvider getResourceProvider(final int resourceType) {
343         return new WorkbenchContentProvider() {
344             public Object JavaDoc[] getChildren(Object JavaDoc o) {
345                 if (o instanceof IContainer) {
346                     IResource[] members = null;
347                     try {
348                         members = ((IContainer) o).members();
349                     } catch (CoreException e) {
350                         //just return an empty set of children
351
return new Object JavaDoc[0];
352                     }
353
354                     //filter out the desired resource types
355
ArrayList JavaDoc results = new ArrayList JavaDoc();
356                     for (int i = 0; i < members.length; i++) {
357                         //And the test bits with the resource types to see if they are what we want
358
if ((members[i].getType() & resourceType) > 0) {
359                             results.add(members[i]);
360                         }
361                     }
362                     return results.toArray();
363                 }
364                 //input element case
365
if (o instanceof ArrayList JavaDoc) {
366                     return ((ArrayList JavaDoc) o).toArray();
367                 }
368                 return new Object JavaDoc[0];
369             }
370         };
371     }
372
373     /**
374      * Returns this page's collection of currently-specified resources to be
375      * exported. This is the primary resource selection facility accessor for
376      * subclasses.
377      *
378      * @return a collection of resources currently selected
379      * for export (element type: <code>IResource</code>)
380      */

381     protected List JavaDoc getSelectedResources() {
382         Iterator JavaDoc resourcesToExportIterator = this
383                 .getSelectedResourcesIterator();
384         List JavaDoc resourcesToExport = new ArrayList JavaDoc();
385         while (resourcesToExportIterator.hasNext()) {
386             resourcesToExport.add(resourcesToExportIterator.next());
387         }
388         return resourcesToExport;
389     }
390
391     /**
392      * Returns this page's collection of currently-specified resources to be
393      * exported. This is the primary resource selection facility accessor for
394      * subclasses.
395      *
396      * @return an iterator over the collection of resources currently selected
397      * for export (element type: <code>IResource</code>). This will include
398      * white checked folders and individually checked files.
399      */

400     protected Iterator JavaDoc getSelectedResourcesIterator() {
401         return this.resourceGroup.getAllCheckedListItems().iterator();
402     }
403
404     /**
405      * Returns the resource extensions currently specified to be exported.
406      *
407      * @return the resource extensions currently specified to be exported (element
408      * type: <code>String</code>)
409      */

410     protected List JavaDoc getTypesToExport() {
411
412         return selectedTypes;
413     }
414
415     /**
416      * Returns this page's collection of currently-specified resources to be
417      * exported. This returns both folders and files - for just the files use
418      * getSelectedResources.
419      *
420      * @return a collection of resources currently selected
421      * for export (element type: <code>IResource</code>)
422      */

423     protected List JavaDoc getWhiteCheckedResources() {
424
425         return this.resourceGroup.getAllWhiteCheckedItems();
426     }
427
428     /**
429      * Queries the user for the types of resources to be exported and selects
430      * them in the checkbox group.
431      */

432     protected void handleTypesEditButtonPressed() {
433         Object JavaDoc[] newSelectedTypes = queryResourceTypesToExport();
434
435         if (newSelectedTypes != null) { // ie.- did not press Cancel
436
this.selectedTypes = new ArrayList JavaDoc(newSelectedTypes.length);
437             for (int i = 0; i < newSelectedTypes.length; i++) {
438                 this.selectedTypes.add(newSelectedTypes[i]);
439             }
440             setupSelectionsBasedOnSelectedTypes();
441         }
442
443     }
444
445     /**
446      * Returns whether the extension of the given resource name is an extension that
447      * has been specified for export by the user.
448      *
449      * @param resourceName the resource name
450      * @return <code>true</code> if the resource name is suitable for export based
451      * upon its extension
452      */

453     protected boolean hasExportableExtension(String JavaDoc resourceName) {
454         if (selectedTypes == null) {
455             return true;
456         }
457
458         int separatorIndex = resourceName.lastIndexOf("."); //$NON-NLS-1$
459
if (separatorIndex == -1) {
460             return false;
461         }
462
463         String JavaDoc extension = resourceName.substring(separatorIndex + 1);
464
465         Iterator JavaDoc it = selectedTypes.iterator();
466         while (it.hasNext()) {
467             if (extension.equalsIgnoreCase((String JavaDoc) it.next())) {
468                 return true;
469             }
470         }
471
472         return false;
473     }
474
475     /**
476      * Persists additional setting that are to be restored in the next instance of
477      * this page.
478      * <p>
479      * The <code>WizardImportPage</code> implementation of this method does
480      * nothing. Subclasses may extend to persist additional settings.
481      * </p>
482      */

483     protected void internalSaveWidgetValues() {
484     }
485
486     /**
487      * Queries the user for the resource types that are to be exported and returns
488      * these types as an array.
489      *
490      * @return the resource types selected for export (element type:
491      * <code>String</code>), or <code>null</code> if the user canceled the
492      * selection
493      */

494     protected Object JavaDoc[] queryResourceTypesToExport() {
495
496         TypeFilteringDialog dialog = new TypeFilteringDialog(getContainer()
497                 .getShell(), getTypesToExport());
498
499         dialog.open();
500
501         return dialog.getResult();
502     }
503
504     /**
505      * Restores resource specification control settings that were persisted
506      * in the previous instance of this page. Subclasses wishing to restore
507      * persisted values for their controls may extend.
508      */

509     protected void restoreResourceSpecificationWidgetValues() {
510     }
511
512     /**
513      * Persists resource specification control setting that are to be restored
514      * in the next instance of this page. Subclasses wishing to persist additional
515      * setting for their controls should extend hook method
516      * <code>internalSaveWidgetValues</code>.
517      */

518     protected void saveWidgetValues() {
519
520         // allow subclasses to save values
521
internalSaveWidgetValues();
522
523     }
524
525     /**
526      * Set the initial selections in the resource group.
527      */

528     protected void setupBasedOnInitialSelections() {
529
530         Iterator JavaDoc it = this.initialResourceSelection.iterator();
531         while (it.hasNext()) {
532             IResource currentResource = (IResource) it.next();
533             if (currentResource.getType() == IResource.FILE) {
534                 this.resourceGroup.initialCheckListItem(currentResource);
535             } else {
536                 this.resourceGroup.initialCheckTreeItem(currentResource);
537             }
538         }
539     }
540
541     /**
542      * Update the tree to only select those elements that match the selected types
543      */

544     private void setupSelectionsBasedOnSelectedTypes() {
545
546         Runnable JavaDoc runnable = new Runnable JavaDoc() {
547             public void run() {
548                 Map JavaDoc selectionMap = new Hashtable JavaDoc();
549                 //Only get the white selected ones
550
Iterator JavaDoc resourceIterator = resourceGroup
551                         .getAllWhiteCheckedItems().iterator();
552                 while (resourceIterator.hasNext()) {
553                     //handle the files here - white checked containers require recursion
554
IResource resource = (IResource) resourceIterator.next();
555                     if (resource.getType() == IResource.FILE) {
556                         if (hasExportableExtension(resource.getName())) {
557                             List JavaDoc resourceList = new ArrayList JavaDoc();
558                             IContainer parent = resource.getParent();
559                             if (selectionMap.containsKey(parent)) {
560                                 resourceList = (List JavaDoc) selectionMap.get(parent);
561                             }
562                             resourceList.add(resource);
563                             selectionMap.put(parent, resourceList);
564                         }
565                     } else {
566                         setupSelectionsBasedOnSelectedTypes(selectionMap,
567                                 (IContainer) resource);
568                     }
569                 }
570                 resourceGroup.updateSelections(selectionMap);
571             }
572         };
573
574         BusyIndicator.showWhile(getShell().getDisplay(), runnable);
575
576     }
577
578     /**
579      * Set up the selection values for the resources and put them in the selectionMap.
580      * If a resource is a file see if it matches one of the selected extensions. If not
581      * then check the children.
582      */

583     private void setupSelectionsBasedOnSelectedTypes(Map JavaDoc selectionMap,
584             IContainer parent) {
585
586         List JavaDoc selections = new ArrayList JavaDoc();
587         IResource[] resources;
588         boolean hasFiles = false;
589
590         try {
591             resources = parent.members();
592         } catch (CoreException exception) {
593             //Just return if we can't get any info
594
return;
595         }
596
597         for (int i = 0; i < resources.length; i++) {
598             IResource resource = resources[i];
599             if (resource.getType() == IResource.FILE) {
600                 if (hasExportableExtension(resource.getName())) {
601                     hasFiles = true;
602                     selections.add(resource);
603                 }
604             } else {
605                 setupSelectionsBasedOnSelectedTypes(selectionMap,
606                         (IContainer) resource);
607             }
608         }
609
610         //Only add it to the list if there are files in this folder
611
if (hasFiles) {
612             selectionMap.put(parent, selections);
613         }
614     }
615
616     /**
617      * Save any editors that the user wants to save before export.
618      * @return boolean if the save was successful.
619      */

620     protected boolean saveDirtyEditors() {
621         return IDEWorkbenchPlugin.getDefault().getWorkbench().saveAllEditors(
622                 true);
623     }
624     
625     /**
626      * Check if widgets are enabled or disabled by a change in the dialog.
627      */

628     protected void updateWidgetEnablements() {
629
630         boolean pageComplete = determinePageCompletion();
631         setPageComplete(pageComplete);
632         if (pageComplete) {
633             setMessage(null);
634         }
635         super.updateWidgetEnablements();
636     }
637 }
638
Popular Tags