KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > jarpackager > JarPackageWizardPage


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.jdt.internal.ui.jarpackager;
12
13 import java.io.File JavaDoc;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.HashSet JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.Set JavaDoc;
18
19 import org.eclipse.core.runtime.IAdaptable;
20 import org.eclipse.core.runtime.IPath;
21 import org.eclipse.core.runtime.IProgressMonitor;
22 import org.eclipse.core.runtime.IStatus;
23 import org.eclipse.core.runtime.Path;
24
25 import org.eclipse.core.resources.IFile;
26 import org.eclipse.core.resources.IFolder;
27 import org.eclipse.core.resources.IProject;
28 import org.eclipse.core.resources.IResource;
29 import org.eclipse.core.resources.IWorkspace;
30 import org.eclipse.core.resources.ResourcesPlugin;
31
32 import org.eclipse.swt.SWT;
33 import org.eclipse.swt.custom.BusyIndicator;
34 import org.eclipse.swt.events.SelectionAdapter;
35 import org.eclipse.swt.events.SelectionEvent;
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.Combo;
40 import org.eclipse.swt.widgets.Composite;
41 import org.eclipse.swt.widgets.Event;
42 import org.eclipse.swt.widgets.FileDialog;
43 import org.eclipse.swt.widgets.Label;
44 import org.eclipse.swt.widgets.Link;
45 import org.eclipse.swt.widgets.TreeItem;
46
47 import org.eclipse.jface.dialogs.Dialog;
48 import org.eclipse.jface.dialogs.IDialogSettings;
49 import org.eclipse.jface.dialogs.IMessageProvider;
50 import org.eclipse.jface.operation.IRunnableWithProgress;
51 import org.eclipse.jface.viewers.CheckStateChangedEvent;
52 import org.eclipse.jface.viewers.DecoratingLabelProvider;
53 import org.eclipse.jface.viewers.ICheckStateListener;
54 import org.eclipse.jface.viewers.IStructuredSelection;
55 import org.eclipse.jface.viewers.ITreeContentProvider;
56 import org.eclipse.jface.wizard.IWizardPage;
57
58 import org.eclipse.ui.PlatformUI;
59 import org.eclipse.ui.dialogs.WizardExportResourcesPage;
60
61 import org.eclipse.ltk.core.refactoring.RefactoringCore;
62 import org.eclipse.ltk.core.refactoring.history.IRefactoringHistoryService;
63 import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
64
65 import org.eclipse.jdt.core.IClassFile;
66 import org.eclipse.jdt.core.IClasspathEntry;
67 import org.eclipse.jdt.core.ICompilationUnit;
68 import org.eclipse.jdt.core.IJavaElement;
69 import org.eclipse.jdt.core.IJavaModel;
70 import org.eclipse.jdt.core.IPackageFragment;
71 import org.eclipse.jdt.core.IPackageFragmentRoot;
72 import org.eclipse.jdt.core.JavaCore;
73 import org.eclipse.jdt.core.JavaModelException;
74 import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor;
75
76 import org.eclipse.jdt.ui.JavaElementComparator;
77 import org.eclipse.jdt.ui.JavaElementLabelProvider;
78 import org.eclipse.jdt.ui.ProblemsLabelDecorator;
79 import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
80 import org.eclipse.jdt.ui.jarpackager.JarPackageData;
81
82 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
83 import org.eclipse.jdt.internal.ui.filters.EmptyInnerPackageFilter;
84 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
85 import org.eclipse.jdt.internal.ui.util.SWTUtil;
86 import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
87
88 /**
89  * Page 1 of the JAR Package wizard
90  */

91 class JarPackageWizardPage extends WizardExportResourcesPage implements IJarPackageWizardPage {
92
93     private JarPackageData fJarPackage;
94     private IStructuredSelection fInitialSelection;
95     private CheckboxTreeAndListGroup fInputGroup;
96
97     // widgets
98
private Button fExportClassFilesCheckbox;
99     private Button fExportOutputFoldersCheckbox;
100     private Button fExportJavaFilesCheckbox;
101     private Button fExportRefactoringsCheckbox;
102     private Link fRefactoringLink;
103     
104     private Combo fDestinationNamesCombo;
105     private Button fDestinationBrowseButton;
106     
107     private Button fCompressCheckbox;
108     private Button fOverwriteCheckbox;
109     private Button fIncludeDirectoryEntriesCheckbox;
110     private boolean fInitiallySelecting= true;
111
112     // dialog store id constants
113
private static final String JavaDoc PAGE_NAME= "JarPackageWizardPage"; //$NON-NLS-1$
114

115     private static final String JavaDoc STORE_EXPORT_CLASS_FILES= PAGE_NAME + ".EXPORT_CLASS_FILES"; //$NON-NLS-1$
116
private static final String JavaDoc STORE_EXPORT_OUTPUT_FOLDERS= PAGE_NAME + ".EXPORT_OUTPUT_FOLDER"; //$NON-NLS-1$
117
private static final String JavaDoc STORE_EXPORT_JAVA_FILES= PAGE_NAME + ".EXPORT_JAVA_FILES"; //$NON-NLS-1$
118

119     private static final String JavaDoc STORE_DESTINATION_NAMES= PAGE_NAME + ".DESTINATION_NAMES_ID"; //$NON-NLS-1$
120

121     private static final String JavaDoc STORE_REFACTORINGS= PAGE_NAME + ".REFACTORINGS"; //$NON-NLS-1$
122
private static final String JavaDoc STORE_COMPRESS= PAGE_NAME + ".COMPRESS"; //$NON-NLS-1$
123
private final static String JavaDoc STORE_OVERWRITE= PAGE_NAME + ".OVERWRITE"; //$NON-NLS-1$
124
private final static String JavaDoc STORE_INCLUDE_DIRECTORY_ENTRIES= PAGE_NAME + ".INCLUDE_DIRECTORY_ENTRIES"; //$NON-NLS-1$
125

126     // other constants
127
private static final int SIZING_SELECTION_WIDGET_WIDTH= 480;
128     private static final int SIZING_SELECTION_WIDGET_HEIGHT= 150;
129     
130     /**
131      * Create an instance of this class
132      */

133     public JarPackageWizardPage(JarPackageData jarPackage, IStructuredSelection selection) {
134         super(PAGE_NAME, selection);
135         setTitle(JarPackagerMessages.JarPackageWizardPage_title);
136         setDescription(JarPackagerMessages.JarPackageWizardPage_description);
137         fJarPackage= jarPackage;
138         fInitialSelection= selection;
139     }
140
141     /*
142      * Method declared on IDialogPage.
143      */

144     public void createControl(final Composite parent) {
145         
146         initializeDialogUnits(parent);
147         
148         Composite composite= new Composite(parent, SWT.NULL);
149         composite.setLayout(new GridLayout());
150         composite.setLayoutData(
151             new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
152
153         createPlainLabel(composite, JarPackagerMessages.JarPackageWizardPage_whatToExport_label);
154         createInputGroup(composite);
155
156         createExportTypeGroup(composite);
157
158         new Label(composite, SWT.NONE); // vertical spacer
159

160
161         createPlainLabel(composite, JarPackagerMessages.JarPackageWizardPage_whereToExport_label);
162         createDestinationGroup(composite);
163
164         createPlainLabel(composite, JarPackagerMessages.JarPackageWizardPage_options_label);
165         createOptionsGroup(composite);
166
167         restoreResourceSpecificationWidgetValues(); // superclass API defines this hook
168
restoreWidgetValues();
169         if (fInitialSelection != null)
170             BusyIndicator.showWhile(parent.getDisplay(), new Runnable JavaDoc() {
171                 public void run() {
172                     setupBasedOnInitialSelections();
173                 }
174             });
175
176         setControl(composite);
177         update();
178         fRefactoringLink.setEnabled(fExportRefactoringsCheckbox.getSelection());
179         giveFocusToDestination();
180         
181         Dialog.applyDialogFont(composite);
182         PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.JARPACKAGER_WIZARD_PAGE);
183     }
184
185     /**
186      * Create the export options specification widgets.
187      *
188      * @param parent org.eclipse.swt.widgets.Composite
189      */

190     protected void createOptionsGroup(Composite parent) {
191         Composite optionsGroup= new Composite(parent, SWT.NONE);
192         GridLayout layout= new GridLayout();
193         layout.marginHeight= 0;
194         optionsGroup.setLayout(layout);
195
196         fCompressCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
197         fCompressCheckbox.setText(JarPackagerMessages.JarPackageWizardPage_compress_text);
198         fCompressCheckbox.addListener(SWT.Selection, this);
199
200         fIncludeDirectoryEntriesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
201         fIncludeDirectoryEntriesCheckbox.setText(JarPackagerMessages.JarPackageWizardPage_includeDirectoryEntries_text);
202         fIncludeDirectoryEntriesCheckbox.addListener(SWT.Selection, this);
203
204         fOverwriteCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
205         fOverwriteCheckbox.setText(JarPackagerMessages.JarPackageWizardPage_overwrite_text);
206         fOverwriteCheckbox.addListener(SWT.Selection, this);
207     }
208
209     /**
210      * Answer the contents of the destination specification widget. If this
211      * value does not have the required suffix then add it first.
212      *
213      * @return java.lang.String
214      */

215     protected String JavaDoc getDestinationValue() {
216         String JavaDoc destinationText= fDestinationNamesCombo.getText().trim();
217         if (destinationText.indexOf('.') < 0)
218             destinationText += getOutputSuffix();
219         return destinationText;
220     }
221
222     /**
223      * Answer the string to display in self as the destination type
224      *
225      * @return java.lang.String
226      */

227     protected String JavaDoc getDestinationLabel() {
228         return JarPackagerMessages.JarPackageWizardPage_destination_label;
229     }
230
231     /**
232      * Answer the suffix that files exported from this wizard must have.
233      * If this suffix is a file extension (which is typically the case)
234      * then it must include the leading period character.
235      *
236      * @return java.lang.String
237      */

238     protected String JavaDoc getOutputSuffix() {
239         return "." + JarPackagerUtil.JAR_EXTENSION; //$NON-NLS-1$
240
}
241
242     /**
243      * Returns an iterator over this page's collection of currently-specified
244      * elements to be exported. This is the primary element selection facility
245      * accessor for subclasses.
246      *
247      * @return an iterator over the collection of elements currently selected for export
248      */

249     protected Iterator JavaDoc getSelectedResourcesIterator() {
250         return fInputGroup.getAllCheckedListItems();
251     }
252
253     /**
254      * Persists resource specification control setting that are to be restored
255      * in the next instance of this page. Subclasses wishing to persist
256      * settings for their controls should extend the hook method
257      * <code>internalSaveWidgetValues</code>.
258      */

259     public final void saveWidgetValues() {
260         // update directory names history
261
IDialogSettings settings= getDialogSettings();
262         if (settings != null) {
263             String JavaDoc[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
264             if (directoryNames == null)
265                 directoryNames= new String JavaDoc[0];
266             directoryNames= addToHistory(directoryNames, getDestinationValue());
267             settings.put(STORE_DESTINATION_NAMES, directoryNames);
268
269             settings.put(STORE_EXPORT_CLASS_FILES, fJarPackage.areClassFilesExported());
270             settings.put(STORE_EXPORT_OUTPUT_FOLDERS, fJarPackage.areOutputFoldersExported());
271             settings.put(STORE_EXPORT_JAVA_FILES, fJarPackage.areJavaFilesExported());
272
273             // options
274
settings.put(STORE_REFACTORINGS, fJarPackage.isRefactoringAware());
275             settings.put(STORE_COMPRESS, fJarPackage.isCompressed());
276             settings.put(STORE_INCLUDE_DIRECTORY_ENTRIES, fJarPackage.areDirectoryEntriesIncluded());
277             settings.put(STORE_OVERWRITE, fJarPackage.allowOverwrite());
278         }
279         // Allow subclasses to save values
280
internalSaveWidgetValues();
281     }
282
283     /**
284      * Hook method for subclasses to persist their settings.
285      */

286     protected void internalSaveWidgetValues() {
287     }
288
289     /**
290      * Hook method for restoring widget values to the values that they held
291      * last time this wizard was used to completion.
292      */

293     protected void restoreWidgetValues() {
294         if (!((JarPackageWizard)getWizard()).isInitializingFromJarPackage())
295             initializeJarPackage();
296
297         fExportClassFilesCheckbox.setSelection(fJarPackage.areClassFilesExported());
298         fExportOutputFoldersCheckbox.setSelection(fJarPackage.areOutputFoldersExported());
299         fExportJavaFilesCheckbox.setSelection(fJarPackage.areJavaFilesExported());
300
301         // destination
302
if (fJarPackage.getJarLocation().isEmpty())
303             fDestinationNamesCombo.setText(""); //$NON-NLS-1$
304
else
305             fDestinationNamesCombo.setText(fJarPackage.getJarLocation().toOSString());
306         IDialogSettings settings= getDialogSettings();
307         if (settings != null) {
308             String JavaDoc[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
309             if (directoryNames == null)
310                 return; // ie.- no settings stored
311
if (! fDestinationNamesCombo.getText().equals(directoryNames[0]))
312                 fDestinationNamesCombo.add(fDestinationNamesCombo.getText());
313             for (int i= 0; i < directoryNames.length; i++)
314                 fDestinationNamesCombo.add(directoryNames[i]);
315         }
316         
317         // options
318
if (fExportRefactoringsCheckbox != null)
319             fExportRefactoringsCheckbox.setSelection(fJarPackage.isRefactoringAware());
320         fCompressCheckbox.setSelection(fJarPackage.isCompressed());
321         fIncludeDirectoryEntriesCheckbox.setSelection(fJarPackage.areDirectoryEntriesIncluded());
322         fOverwriteCheckbox.setSelection(fJarPackage.allowOverwrite());
323     }
324
325     /**
326      * Initializes the JAR package from last used wizard page values.
327      */

328     protected void initializeJarPackage() {
329         IDialogSettings settings= getDialogSettings();
330         if (settings != null) {
331             // source
332
fJarPackage.setElements(getSelectedElements());
333             fJarPackage.setExportClassFiles(settings.getBoolean(STORE_EXPORT_CLASS_FILES));
334             fJarPackage.setExportOutputFolders(settings.getBoolean(STORE_EXPORT_OUTPUT_FOLDERS));
335             fJarPackage.setExportJavaFiles(settings.getBoolean(STORE_EXPORT_JAVA_FILES));
336
337             // options
338
fJarPackage.setRefactoringAware(settings.getBoolean(STORE_REFACTORINGS));
339             fJarPackage.setCompress(settings.getBoolean(STORE_COMPRESS));
340             fJarPackage.setIncludeDirectoryEntries(settings.getBoolean(STORE_INCLUDE_DIRECTORY_ENTRIES));
341             fJarPackage.setOverwrite(settings.getBoolean(STORE_OVERWRITE));
342                         
343             // destination
344
String JavaDoc[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
345             if (directoryNames == null)
346                 return; // ie.- no settings stored
347
fJarPackage.setJarLocation(Path.fromOSString(directoryNames[0]));
348         }
349     }
350
351     /**
352      * Stores the widget values in the JAR package.
353      */

354     protected void updateModel() {
355         if (getControl() == null)
356             return;
357         
358         // source
359
if (fExportClassFilesCheckbox.getSelection() && !fJarPackage.areClassFilesExported())
360             fExportOutputFoldersCheckbox.setSelection(false);
361         if (fExportOutputFoldersCheckbox.getSelection() && !fJarPackage.areOutputFoldersExported())
362             fExportClassFilesCheckbox.setSelection(false);
363         fJarPackage.setExportClassFiles(fExportClassFilesCheckbox.getSelection());
364         fJarPackage.setExportOutputFolders(fExportOutputFoldersCheckbox.getSelection());
365         fJarPackage.setExportJavaFiles(fExportJavaFilesCheckbox.getSelection());
366         fJarPackage.setElements(getSelectedElements());
367
368         // destination
369
String JavaDoc comboText= fDestinationNamesCombo.getText();
370         IPath path= Path.fromOSString(comboText);
371
372         if (path.segmentCount() > 0 && ensureTargetFileIsValid(path.toFile()) && path.getFileExtension() == null)
373             // append .jar
374
path= path.addFileExtension(JarPackagerUtil.JAR_EXTENSION);
375
376         fJarPackage.setJarLocation(path);
377
378         // options
379
if (fExportRefactoringsCheckbox != null)
380             fJarPackage.setRefactoringAware(fExportRefactoringsCheckbox.getSelection());
381         else
382             fJarPackage.setRefactoringAware(false);
383         fJarPackage.setCompress(fCompressCheckbox.getSelection());
384         fJarPackage.setIncludeDirectoryEntries(fIncludeDirectoryEntriesCheckbox.getSelection());
385         fJarPackage.setOverwrite(fOverwriteCheckbox.getSelection());
386     }
387
388     /**
389      * Returns a boolean indicating whether the passed File handle is
390      * is valid and available for use.
391      *
392      * @return boolean
393      */

394     protected boolean ensureTargetFileIsValid(File JavaDoc targetFile) {
395         if (targetFile.exists() && targetFile.isDirectory() && fDestinationNamesCombo.getText().length() > 0) {
396             setErrorMessage(JarPackagerMessages.JarPackageWizardPage_error_exportDestinationMustNotBeDirectory);
397             fDestinationNamesCombo.setFocus();
398             return false;
399         }
400         if (targetFile.exists()) {
401             if (!targetFile.canWrite()) {
402                 setErrorMessage(JarPackagerMessages.JarPackageWizardPage_error_jarFileExistsAndNotWritable);
403                 fDestinationNamesCombo.setFocus();
404                 return false;
405             }
406         }
407         return true;
408     }
409
410     /*
411      * Overrides method from WizardExportPage
412      */

413     protected void createDestinationGroup(Composite parent) {
414         
415         initializeDialogUnits(parent);
416         
417         // destination specification group
418
Composite destinationSelectionGroup= new Composite(parent, SWT.NONE);
419         GridLayout layout= new GridLayout();
420         layout.numColumns= 3;
421         destinationSelectionGroup.setLayout(layout);
422         destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
423
424         new Label(destinationSelectionGroup, SWT.NONE).setText(getDestinationLabel());
425
426         // destination name entry field
427
fDestinationNamesCombo= new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
428         fDestinationNamesCombo.addListener(SWT.Modify, this);
429         fDestinationNamesCombo.addListener(SWT.Selection, this);
430         GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
431         data.widthHint= SIZING_TEXT_FIELD_WIDTH;
432         fDestinationNamesCombo.setLayoutData(data);
433
434         // destination browse button
435
fDestinationBrowseButton= new Button(destinationSelectionGroup, SWT.PUSH);
436         fDestinationBrowseButton.setText(JarPackagerMessages.JarPackageWizardPage_browseButton_text);
437         fDestinationBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
438         SWTUtil.setButtonDimensionHint(fDestinationBrowseButton);
439         fDestinationBrowseButton.addSelectionListener(new SelectionAdapter() {
440             public void widgetSelected(SelectionEvent e) {
441                 handleDestinationBrowseButtonPressed();
442             }
443         });
444     }
445
446     /**
447      * Open an appropriate destination browser so that the user can specify a source
448      * to import from
449      */

450     protected void handleDestinationBrowseButtonPressed() {
451         FileDialog dialog= new FileDialog(getContainer().getShell(), SWT.SAVE);
452         dialog.setFilterExtensions(new String JavaDoc[] {"*.jar", "*.zip"}); //$NON-NLS-1$ //$NON-NLS-2$
453

454         String JavaDoc currentSourceString= getDestinationValue();
455         int lastSeparatorIndex= currentSourceString.lastIndexOf(File.separator);
456         if (lastSeparatorIndex != -1) {
457             dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
458             dialog.setFileName(currentSourceString.substring(lastSeparatorIndex + 1, currentSourceString.length()));
459         }
460         else
461             dialog.setFileName(currentSourceString);
462         String JavaDoc selectedFileName= dialog.open();
463         if (selectedFileName != null)
464             fDestinationNamesCombo.setText(selectedFileName);
465     }
466
467     /**
468      * Returns the resource for the specified path.
469      *
470      * @param path the path for which the resource should be returned
471      * @return the resource specified by the path or <code>null</code>
472      */

473     protected IResource findResource(IPath path) {
474         IWorkspace workspace= ResourcesPlugin.getWorkspace();
475         IStatus result= workspace.validatePath(
476                             path.toString(),
477                             IResource.ROOT | IResource.PROJECT | IResource.FOLDER | IResource.FILE);
478         if (result.isOK() && workspace.getRoot().exists(path))
479             return workspace.getRoot().findMember(path);
480         return null;
481     }
482
483     /**
484      * Creates the checkbox tree and list for selecting resources.
485      *
486      * @param parent the parent control
487      */

488     protected void createInputGroup(Composite parent) {
489         int labelFlags= JavaElementLabelProvider.SHOW_BASICS
490                         | JavaElementLabelProvider.SHOW_OVERLAY_ICONS
491                         | JavaElementLabelProvider.SHOW_SMALL_ICONS;
492         ITreeContentProvider treeContentProvider=
493             new StandardJavaElementContentProvider() {
494                 public boolean hasChildren(Object JavaDoc element) {
495                     // prevent the + from being shown in front of packages
496
return !(element instanceof IPackageFragment) && super.hasChildren(element);
497                 }
498             };
499         final DecoratingLabelProvider provider= new DecoratingLabelProvider(new JavaElementLabelProvider(labelFlags), new ProblemsLabelDecorator(null));
500         fInputGroup= new CheckboxTreeAndListGroup(
501                     parent,
502                     JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()),
503                     treeContentProvider,
504                     provider,
505                     new StandardJavaElementContentProvider(),
506                     provider,
507                     SWT.NONE,
508                     SIZING_SELECTION_WIDGET_WIDTH,
509                     SIZING_SELECTION_WIDGET_HEIGHT) {
510
511                         protected void setTreeChecked(final Object JavaDoc element, final boolean state) {
512                             if (fInitiallySelecting && element instanceof IResource) {
513                                 final IResource resource= (IResource) element;
514                                 if (resource.getName().charAt(0) == '.')
515                                     return;
516                             }
517                             super.setTreeChecked(element, state);
518                         }
519         };
520         fInputGroup.addTreeFilter(new EmptyInnerPackageFilter());
521         fInputGroup.setTreeComparator(new JavaElementComparator());
522         fInputGroup.setListComparator(new JavaElementComparator());
523         fInputGroup.addTreeFilter(new ContainerFilter(ContainerFilter.FILTER_NON_CONTAINERS));
524         fInputGroup.addTreeFilter(new LibraryFilter());
525         fInputGroup.addListFilter(new ContainerFilter(ContainerFilter.FILTER_CONTAINERS));
526         fInputGroup.getTree().addListener(SWT.MouseUp, this);
527         fInputGroup.getTable().addListener(SWT.MouseUp, this);
528         
529         ICheckStateListener listener = new ICheckStateListener() {
530             public void checkStateChanged(CheckStateChangedEvent event) {
531                 update();
532             }
533         };
534         
535         fInputGroup.addCheckStateListener(listener);
536     }
537
538     /**
539      * Creates the export type controls.
540      *
541      * @param parent
542      * the parent control
543      */

544     protected void createExportTypeGroup(Composite parent) {
545         Composite optionsGroup= new Composite(parent, SWT.NONE);
546         GridLayout layout= new GridLayout();
547         layout.marginHeight= 0;
548         optionsGroup.setLayout(layout);
549
550         fExportClassFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
551         fExportClassFilesCheckbox.setText(JarPackagerMessages.JarPackageWizardPage_exportClassFiles_text);
552         fExportClassFilesCheckbox.addListener(SWT.Selection, this);
553
554         fExportOutputFoldersCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
555         fExportOutputFoldersCheckbox.setText(JarPackagerMessages.JarPackageWizardPage_exportOutputFolders_text);
556         fExportOutputFoldersCheckbox.addListener(SWT.Selection, this);
557
558         fExportJavaFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
559         fExportJavaFilesCheckbox.setText(JarPackagerMessages.JarPackageWizardPage_exportJavaFiles_text);
560         fExportJavaFilesCheckbox.addListener(SWT.Selection, this);
561
562         Composite refactoringsGroup= new Composite(optionsGroup, SWT.NONE);
563         layout= new GridLayout();
564         layout.horizontalSpacing= 0;
565         layout.marginWidth= 0;
566         layout.marginHeight= 0;
567         layout.numColumns= 2;
568         refactoringsGroup.setLayout(layout);
569
570         fExportRefactoringsCheckbox= new Button(refactoringsGroup, SWT.CHECK | SWT.LEFT);
571         fExportRefactoringsCheckbox.setText(JarPackagerMessages.JarPackageWizardPage_refactorings_text);
572         fExportRefactoringsCheckbox.addListener(SWT.Selection, this);
573
574         fRefactoringLink= new Link(refactoringsGroup, SWT.WRAP);
575         fRefactoringLink.setText(JarPackagerMessages.JarPackageWizardPage_configure_label);
576         fRefactoringLink.addSelectionListener(new SelectionAdapter() {
577
578             public void widgetSelected(SelectionEvent event) {
579                 openRefactoringDialog();
580             }
581
582         });
583         fRefactoringLink.setToolTipText(JarPackagerMessages.JarPackageWizardPage_configure_tooltip);
584         GridData data= new GridData(GridData.BEGINNING | GridData.GRAB_HORIZONTAL);
585         fRefactoringLink.setLayoutData(data);
586
587         fExportRefactoringsCheckbox.addSelectionListener(new SelectionAdapter() {
588
589             public void widgetSelected(SelectionEvent event) {
590                 fRefactoringLink.setEnabled(fExportRefactoringsCheckbox.getSelection());
591             }
592         });
593     }
594
595     /**
596      * Opens the dialog to configure refactorings.
597      */

598     protected void openRefactoringDialog() {
599         final RefactoringHistory[] history= { null};
600         final IRefactoringHistoryService service= RefactoringCore.getHistoryService();
601         try {
602             service.connect();
603             final Set JavaDoc set= new HashSet JavaDoc();
604             final Object JavaDoc[] elements= fJarPackage.getElements();
605             for (int index= 0; index < elements.length; index++) {
606                 if (elements[index] instanceof IAdaptable) {
607                     final IAdaptable adaptable= (IAdaptable) elements[index];
608                     final IResource resource= (IResource) adaptable.getAdapter(IResource.class);
609                     if (resource != null)
610                         set.add(resource.getProject());
611                 }
612             }
613             try {
614                 getContainer().run(false, true, new IRunnableWithProgress() {
615
616                     public void run(final IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
617                         history[0]= service.getRefactoringHistory((IProject[]) set.toArray(new IProject[set.size()]), 0, Long.MAX_VALUE, JavaRefactoringDescriptor.JAR_MIGRATION, monitor);
618                     }
619                 });
620             } catch (InvocationTargetException JavaDoc exception) {
621                 ExceptionHandler.handle(exception, getShell(), JarPackagerMessages.JarPackageWizardPage_error_caption, JarPackagerMessages.JarPackageWizardPage_error_label);
622                 return;
623             } catch (InterruptedException JavaDoc exception) {
624                 return;
625             }
626             new JarRefactoringDialog(getShell(), getDialogSettings(), fJarPackage, history[0]).open();
627             updatePageCompletion();
628         } finally {
629             service.disconnect();
630         }
631     }
632
633     /**
634      * Updates the enablement of this page's controls. Subclasses may extend.
635      */

636     protected void updateWidgetEnablements() {
637         if (fExportRefactoringsCheckbox != null) {
638             final boolean selection= fExportRefactoringsCheckbox.getSelection();
639             fIncludeDirectoryEntriesCheckbox.setEnabled(!selection);
640             if (selection) {
641                 fIncludeDirectoryEntriesCheckbox.setSelection(true);
642                 fJarPackage.setIncludeDirectoryEntries(true);
643             }
644         }
645     }
646
647     /*
648      * Overrides method from IJarPackageWizardPage
649      */

650     public boolean isPageComplete() {
651         boolean complete= validateSourceGroup();
652         complete= validateDestinationGroup() && complete;
653         complete= validateOptionsGroup() && complete;
654         if (complete)
655             setErrorMessage(null);
656         return complete;
657     }
658
659     /*
660      * Implements method from Listener
661      */

662     public void handleEvent(Event e) {
663         if (getControl() == null)
664             return;
665         update();
666     }
667     
668     protected void update() {
669         updateModel();
670         updateWidgetEnablements();
671         updatePageCompletion();
672     }
673     
674     protected void updatePageCompletion() {
675         boolean pageComplete= isPageComplete();
676         setPageComplete(pageComplete);
677         if (pageComplete)
678             setErrorMessage(null);
679         updateRefactoringMessage();
680     }
681
682     protected void updateRefactoringMessage() {
683         String JavaDoc currentMessage= getMessage();
684         if (fJarPackage.isRefactoringAware() && fJarPackage.getRefactoringDescriptors().length == 0) {
685             if (currentMessage == null)
686                 setMessage(JarPackagerMessages.JarPackageWizardPage_no_refactorings_selected, IMessageProvider.INFORMATION);
687         } else if (JarPackagerMessages.JarPackageWizardPage_no_refactorings_selected.equals(currentMessage))
688             setMessage(null);
689     }
690     
691     /*
692      * Overrides method from WizardDataTransferPage
693      */

694     protected boolean validateDestinationGroup() {
695         if (fDestinationNamesCombo.getText().length() == 0) {
696             // Clear error
697
if (getErrorMessage() != null)
698                 setErrorMessage(null);
699             if (getMessage() != null)
700                 setMessage(null);
701             return false;
702         }
703         if (fJarPackage.getAbsoluteJarLocation().toString().endsWith("/")) { //$NON-NLS-1$
704
setErrorMessage(JarPackagerMessages.JarPackageWizardPage_error_exportDestinationMustNotBeDirectory);
705             fDestinationNamesCombo.setFocus();
706             return false;
707         }
708         // Check if the Jar is put into the workspace and conflicts with the containers
709
// exported. If the workspace isn't on the local files system we are fine since
710
// the Jar is always created in the local file system
711
IPath workspaceLocation= ResourcesPlugin.getWorkspace().getRoot().getLocation();
712         if (workspaceLocation != null && workspaceLocation.isPrefixOf(fJarPackage.getAbsoluteJarLocation())) {
713             int segments= workspaceLocation.matchingFirstSegments(fJarPackage.getAbsoluteJarLocation());
714             IPath path= fJarPackage.getAbsoluteJarLocation().removeFirstSegments(segments);
715             IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(path);
716             if (resource != null && resource.getType() == IResource.FILE) {
717                 // test if included
718
if (JarPackagerUtil.contains(JarPackagerUtil.asResources(fJarPackage.getElements()), (IFile)resource)) {
719                     setErrorMessage(JarPackagerMessages.JarPackageWizardPage_error_cantExportJARIntoItself);
720                     return false;
721                 }
722             }
723         }
724         // Inform user about relative directory
725
String JavaDoc currentMessage= getMessage();
726         if (!(new File JavaDoc(fDestinationNamesCombo.getText()).isAbsolute())) {
727             if (currentMessage == null)
728                 setMessage(JarPackagerMessages.JarPackageWizardPage_info_relativeExportDestination, IMessageProvider.INFORMATION);
729         } else {
730             if (currentMessage != null)
731                 setMessage(null);
732         }
733         return ensureTargetFileIsValid(fJarPackage.getAbsoluteJarLocation().toFile());
734     }
735
736     /*
737      * Overrides method from WizardDataTransferPage
738      */

739     protected boolean validateOptionsGroup() {
740         return true;
741     }
742
743     /*
744      * Overrides method from WizardDataTransferPage
745      */

746     protected boolean validateSourceGroup() {
747         if (!(fExportClassFilesCheckbox.getSelection() || fExportOutputFoldersCheckbox.getSelection() || fExportJavaFilesCheckbox.getSelection())) {
748             setErrorMessage(JarPackagerMessages.JarPackageWizardPage_error_noExportTypeChecked);
749             return false;
750         }
751         
752         if (getSelectedResources().size() == 0) {
753             if (getErrorMessage() != null)
754                 setErrorMessage(null);
755             return false;
756         }
757         if (fExportClassFilesCheckbox.getSelection() || fExportOutputFoldersCheckbox.getSelection())
758             return true;
759             
760         // Source file only export - check if there are source files
761
Iterator JavaDoc iter= getSelectedResourcesIterator();
762         while (iter.hasNext()) {
763             Object JavaDoc element= iter.next();
764             if (element instanceof IClassFile) {
765                 IPackageFragmentRoot root= (IPackageFragmentRoot)((IClassFile)element).getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
766                 if (root == null)
767                     continue;
768                 IClasspathEntry cpEntry;
769                 try {
770                     cpEntry= root.getRawClasspathEntry();
771                 } catch (JavaModelException e) {
772                     continue;
773                 }
774                 if (cpEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
775                     return true;
776                 }
777             } else {
778                 return true;
779             }
780         }
781
782         if (getErrorMessage() != null)
783             setErrorMessage(null);
784         return false;
785     }
786
787     /**
788      * Creates a file resource handle for the file with the given workspace path.
789      * This method does not create the file resource; this is the responsibility
790      * of <code>createFile</code>.
791      *
792      * @param filePath the path of the file resource to create a handle for
793      * @return the new file resource handle
794      */

795     protected IFile createFileHandle(IPath filePath) {
796         if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
797             return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
798         else
799             return null;
800     }
801
802     /**
803      * Set the current input focus to self's destination entry field
804      */

805     protected void giveFocusToDestination() {
806         fDestinationNamesCombo.setFocus();
807     }
808
809     /*
810      * Overrides method from WizardExportResourcePage
811      */

812     protected void setupBasedOnInitialSelections() {
813         Iterator JavaDoc iterator= fInitialSelection.iterator();
814         while (iterator.hasNext()) {
815             Object JavaDoc selectedElement= iterator.next();
816
817             if (selectedElement instanceof IResource && !((IResource)selectedElement).isAccessible())
818                 continue;
819
820             if (selectedElement instanceof IJavaElement && !((IJavaElement)selectedElement).exists())
821                 continue;
822             
823             if (selectedElement instanceof ICompilationUnit || selectedElement instanceof IClassFile || selectedElement instanceof IFile)
824                 fInputGroup.initialCheckListItem(selectedElement);
825             else {
826                 if (selectedElement instanceof IFolder) {
827                     // Convert resource to Java element if possible
828
IJavaElement je= JavaCore.create((IResource)selectedElement);
829                     if (je != null && je.exists() && je.getJavaProject().isOnClasspath((IResource)selectedElement))
830                         selectedElement= je;
831                 }
832                 try {
833                     fInputGroup.initialCheckTreeItem(selectedElement);
834                 } finally {
835                     fInitiallySelecting= false;
836                 }
837             }
838         }
839         
840         TreeItem[] items= fInputGroup.getTree().getItems();
841         int i= 0;
842         while (i < items.length && !items[i].getChecked())
843             i++;
844         if (i < items.length) {
845             fInputGroup.getTree().setSelection(new TreeItem[] {items[i]});
846             fInputGroup.getTree().showSelection();
847             fInputGroup.populateListViewer(items[i].getData());
848         }
849     }
850
851     /*
852      * Implements method from IJarPackageWizardPage.
853      */

854     public void finish() {
855         saveWidgetValues();
856     }
857
858     /*
859      * Method declared on IWizardPage.
860      */

861     public void setPreviousPage(IWizardPage page) {
862         super.setPreviousPage(page);
863         if (getControl() != null)
864             updatePageCompletion();
865     }
866
867     Object JavaDoc[] getSelectedElementsWithoutContainedChildren() {
868         Set JavaDoc closure= removeContainedChildren(fInputGroup.getWhiteCheckedTreeItems());
869         closure.addAll(getExportedNonContainers());
870         return closure.toArray();
871     }
872
873     private Set JavaDoc removeContainedChildren(Set JavaDoc elements) {
874         Set JavaDoc newList= new HashSet JavaDoc(elements.size());
875         Set JavaDoc javaElementResources= getCorrespondingContainers(elements);
876         Iterator JavaDoc iter= elements.iterator();
877         boolean removedOne= false;
878         while (iter.hasNext()) {
879             Object JavaDoc element= iter.next();
880             Object JavaDoc parent;
881             if (element instanceof IResource)
882                 parent= ((IResource)element).getParent();
883             else if (element instanceof IJavaElement) {
884                 parent= ((IJavaElement)element).getParent();
885                 if (parent instanceof IPackageFragmentRoot) {
886                     IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)parent;
887                     try {
888                         if (pkgRoot.getCorrespondingResource() instanceof IProject)
889                             parent= pkgRoot.getJavaProject();
890                     } catch (JavaModelException ex) {
891                         // leave parent as is
892
}
893                 }
894             }
895             else {
896                 // unknown type
897
newList.add(element);
898                 continue;
899             }
900             if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel)) && (elements.contains(parent) || javaElementResources.contains(parent))))
901                 removedOne= true;
902             else
903                 newList.add(element);
904         }
905         if (removedOne)
906             return removeContainedChildren(newList);
907         else
908             return newList;
909     }
910
911     private Set JavaDoc getExportedNonContainers() {
912         Set JavaDoc whiteCheckedTreeItems= fInputGroup.getWhiteCheckedTreeItems();
913         Set JavaDoc exportedNonContainers= new HashSet JavaDoc(whiteCheckedTreeItems.size());
914         Set JavaDoc javaElementResources= getCorrespondingContainers(whiteCheckedTreeItems);
915         Iterator JavaDoc iter= fInputGroup.getAllCheckedListItems();
916         while (iter.hasNext()) {
917             Object JavaDoc element= iter.next();
918             Object JavaDoc parent= null;
919             if (element instanceof IResource)
920                 parent= ((IResource)element).getParent();
921             else if (element instanceof IJavaElement)
922                 parent= ((IJavaElement)element).getParent();
923             if (!whiteCheckedTreeItems.contains(parent) && !javaElementResources.contains(parent))
924                 exportedNonContainers.add(element);
925         }
926         return exportedNonContainers;
927     }
928
929     /*
930      * Create a list with the folders / projects that correspond
931      * to the Java elements (Java project, package, package root)
932      */

933     private Set JavaDoc getCorrespondingContainers(Set JavaDoc elements) {
934         Set JavaDoc javaElementResources= new HashSet JavaDoc(elements.size());
935         Iterator JavaDoc iter= elements.iterator();
936         while (iter.hasNext()) {
937             Object JavaDoc element= iter.next();
938             if (element instanceof IJavaElement) {
939                 IJavaElement je= (IJavaElement)element;
940                 int type= je.getElementType();
941                 if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
942                     // exclude default package since it is covered by the root
943
if (!(type == IJavaElement.PACKAGE_FRAGMENT && ((IPackageFragment)element).isDefaultPackage())) {
944                         Object JavaDoc resource;
945                         try {
946                             resource= je.getCorrespondingResource();
947                         } catch (JavaModelException ex) {
948                             resource= null;
949                         }
950                         if (resource != null)
951                             javaElementResources.add(resource);
952                     }
953                 }
954             }
955         }
956         return javaElementResources;
957     }
958
959     private Object JavaDoc[] getSelectedElements() {
960         return getSelectedResources().toArray();
961     }
962 }
963
Popular Tags