KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > wizards > datatransfer > WizardFileSystemResourceImportPage1


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ui.internal.wizards.datatransfer;
12
13 import java.io.File JavaDoc;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Collection JavaDoc;
17 import java.util.Hashtable JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Map JavaDoc;
21
22 import org.eclipse.core.resources.IContainer;
23 import org.eclipse.core.runtime.IPath;
24 import org.eclipse.core.runtime.IProgressMonitor;
25 import org.eclipse.core.runtime.IStatus;
26 import org.eclipse.core.runtime.Path;
27 import org.eclipse.jface.dialogs.ErrorDialog;
28 import org.eclipse.jface.dialogs.IDialogConstants;
29 import org.eclipse.jface.dialogs.IDialogSettings;
30 import org.eclipse.jface.dialogs.MessageDialog;
31 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
32 import org.eclipse.jface.operation.IRunnableWithProgress;
33 import org.eclipse.jface.viewers.IStructuredSelection;
34 import org.eclipse.jface.viewers.ITreeContentProvider;
35 import org.eclipse.swt.SWT;
36 import org.eclipse.swt.custom.BusyIndicator;
37 import org.eclipse.swt.events.FocusEvent;
38 import org.eclipse.swt.events.FocusListener;
39 import org.eclipse.swt.events.KeyEvent;
40 import org.eclipse.swt.events.KeyListener;
41 import org.eclipse.swt.events.SelectionAdapter;
42 import org.eclipse.swt.events.SelectionEvent;
43 import org.eclipse.swt.events.SelectionListener;
44 import org.eclipse.swt.layout.GridData;
45 import org.eclipse.swt.layout.GridLayout;
46 import org.eclipse.swt.widgets.Button;
47 import org.eclipse.swt.widgets.Combo;
48 import org.eclipse.swt.widgets.Composite;
49 import org.eclipse.swt.widgets.DirectoryDialog;
50 import org.eclipse.swt.widgets.Event;
51 import org.eclipse.swt.widgets.Group;
52 import org.eclipse.swt.widgets.Label;
53 import org.eclipse.swt.widgets.Listener;
54 import org.eclipse.swt.widgets.Shell;
55 import org.eclipse.ui.IWorkbench;
56 import org.eclipse.ui.PlatformUI;
57 import org.eclipse.ui.dialogs.FileSystemElement;
58 import org.eclipse.ui.dialogs.WizardResourceImportPage;
59 import org.eclipse.ui.internal.ide.dialogs.IElementFilter;
60 import org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog;
61 import org.eclipse.ui.model.WorkbenchContentProvider;
62 import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
63 import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider;
64 import org.eclipse.ui.wizards.datatransfer.ImportOperation;
65
66 /**
67  * Page 1 of the base resource import-from-file-system Wizard
68  */

69 public class WizardFileSystemResourceImportPage1 extends WizardResourceImportPage
70         implements Listener {
71     // widgets
72
protected Combo sourceNameField;
73
74     protected Button overwriteExistingResourcesCheckbox;
75
76     protected Button createContainerStructureButton;
77
78     protected Button createOnlySelectedButton;
79
80     protected Button sourceBrowseButton;
81
82     protected Button selectTypesButton;
83
84     protected Button selectAllButton;
85
86     protected Button deselectAllButton;
87
88     //A boolean to indicate if the user has typed anything
89
private boolean entryChanged = false;
90
91     // dialog store id constants
92
private final static String JavaDoc STORE_SOURCE_NAMES_ID = "WizardFileSystemResourceImportPage1.STORE_SOURCE_NAMES_ID";//$NON-NLS-1$
93

94     private final static String JavaDoc STORE_OVERWRITE_EXISTING_RESOURCES_ID = "WizardFileSystemResourceImportPage1.STORE_OVERWRITE_EXISTING_RESOURCES_ID";//$NON-NLS-1$
95

96     private final static String JavaDoc STORE_CREATE_CONTAINER_STRUCTURE_ID = "WizardFileSystemResourceImportPage1.STORE_CREATE_CONTAINER_STRUCTURE_ID";//$NON-NLS-1$
97

98     private static final String JavaDoc SELECT_TYPES_TITLE = DataTransferMessages.DataTransfer_selectTypes;
99
100     private static final String JavaDoc SELECT_ALL_TITLE = DataTransferMessages.DataTransfer_selectAll;
101
102     private static final String JavaDoc DESELECT_ALL_TITLE = DataTransferMessages.DataTransfer_deselectAll;
103
104     private static final String JavaDoc SELECT_SOURCE_TITLE = DataTransferMessages.FileImport_selectSourceTitle;
105
106     private static final String JavaDoc SELECT_SOURCE_MESSAGE = DataTransferMessages.FileImport_selectSource;
107
108     protected static final String JavaDoc SOURCE_EMPTY_MESSAGE = DataTransferMessages.FileImport_sourceEmpty;
109
110     /**
111      * Creates an instance of this class
112      */

113     protected WizardFileSystemResourceImportPage1(String JavaDoc name,
114             IWorkbench aWorkbench, IStructuredSelection selection) {
115         super(name, selection);
116     }
117
118     /**
119      * Creates an instance of this class
120      *
121      * @param aWorkbench IWorkbench
122      * @param selection IStructuredSelection
123      */

124     public WizardFileSystemResourceImportPage1(IWorkbench aWorkbench,
125             IStructuredSelection selection) {
126         this("fileSystemImportPage1", aWorkbench, selection);//$NON-NLS-1$
127
setTitle(DataTransferMessages.DataTransfer_fileSystemTitle);
128         setDescription(DataTransferMessages.FileImport_importFileSystem);
129     }
130
131     /**
132      * Creates a new button with the given id.
133      * <p>
134      * The <code>Dialog</code> implementation of this framework method
135      * creates a standard push button, registers for selection events
136      * including button presses and registers
137      * default buttons with its shell.
138      * The button id is stored as the buttons client data.
139      * Note that the parent's layout is assumed to be a GridLayout and
140      * the number of columns in this layout is incremented.
141      * Subclasses may override.
142      * </p>
143      *
144      * @param parent the parent composite
145      * @param id the id of the button (see
146      * <code>IDialogConstants.*_ID</code> constants
147      * for standard dialog button ids)
148      * @param label the label from the button
149      * @param defaultButton <code>true</code> if the button is to be the
150      * default button, and <code>false</code> otherwise
151      */

152     protected Button createButton(Composite parent, int id, String JavaDoc label,
153             boolean defaultButton) {
154         // increment the number of columns in the button bar
155
((GridLayout) parent.getLayout()).numColumns++;
156
157         Button button = new Button(parent, SWT.PUSH);
158         button.setFont(parent.getFont());
159
160         GridData buttonData = new GridData(GridData.FILL_HORIZONTAL);
161         button.setLayoutData(buttonData);
162
163         button.setData(new Integer JavaDoc(id));
164         button.setText(label);
165
166         if (defaultButton) {
167             Shell shell = parent.getShell();
168             if (shell != null) {
169                 shell.setDefaultButton(button);
170             }
171             button.setFocus();
172         }
173         return button;
174     }
175
176     /**
177      * Creates the buttons for selecting specific types or selecting all or none of the
178      * elements.
179      *
180      * @param parent the parent control
181      */

182     protected final void createButtonsGroup(Composite parent) {
183         // top level group
184
Composite buttonComposite = new Composite(parent, SWT.NONE);
185         GridLayout layout = new GridLayout();
186         layout.numColumns = 3;
187         layout.makeColumnsEqualWidth = true;
188         buttonComposite.setLayout(layout);
189         buttonComposite.setFont(parent.getFont());
190         GridData buttonData = new GridData(GridData.VERTICAL_ALIGN_FILL
191                 | GridData.HORIZONTAL_ALIGN_FILL);
192         buttonData.horizontalSpan = 2;
193         buttonComposite.setLayoutData(buttonData);
194
195         // types edit button
196
selectTypesButton = createButton(buttonComposite,
197                 IDialogConstants.SELECT_TYPES_ID, SELECT_TYPES_TITLE, false);
198
199         SelectionListener listener = new SelectionAdapter() {
200             public void widgetSelected(SelectionEvent e) {
201                 handleTypesEditButtonPressed();
202             }
203         };
204         selectTypesButton.addSelectionListener(listener);
205         setButtonLayoutData(selectTypesButton);
206
207         selectAllButton = createButton(buttonComposite,
208                 IDialogConstants.SELECT_ALL_ID, SELECT_ALL_TITLE, false);
209
210         listener = new SelectionAdapter() {
211             public void widgetSelected(SelectionEvent e) {
212                 setAllSelections(true);
213                 updateWidgetEnablements();
214             }
215         };
216         selectAllButton.addSelectionListener(listener);
217         setButtonLayoutData(selectAllButton);
218
219         deselectAllButton = createButton(buttonComposite,
220                 IDialogConstants.DESELECT_ALL_ID, DESELECT_ALL_TITLE, false);
221
222         listener = new SelectionAdapter() {
223             public void widgetSelected(SelectionEvent e) {
224                 setAllSelections(false);
225                 updateWidgetEnablements();
226             }
227         };
228         deselectAllButton.addSelectionListener(listener);
229         setButtonLayoutData(deselectAllButton);
230
231     }
232
233     /* (non-Javadoc)
234      * Method declared on IDialogPage.
235      */

236     public void createControl(Composite parent) {
237         super.createControl(parent);
238         validateSourceGroup();
239         PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(),
240                 IDataTransferHelpContextIds.FILE_SYSTEM_IMPORT_WIZARD_PAGE);
241     }
242
243     /**
244      * Create the import options specification widgets.
245      */

246     protected void createOptionsGroupButtons(Group optionsGroup) {
247
248         // overwrite... checkbox
249
overwriteExistingResourcesCheckbox = new Button(optionsGroup, SWT.CHECK);
250         overwriteExistingResourcesCheckbox.setFont(optionsGroup.getFont());
251         overwriteExistingResourcesCheckbox.setText(DataTransferMessages.FileImport_overwriteExisting);
252
253         // create containers radio
254
createContainerStructureButton = new Button(optionsGroup, SWT.RADIO);
255         createContainerStructureButton.setFont(optionsGroup.getFont());
256         createContainerStructureButton.setText(DataTransferMessages.FileImport_createComplete);
257         createContainerStructureButton.setSelection(false);
258
259         // create selection only radio
260
createOnlySelectedButton = new Button(optionsGroup, SWT.RADIO);
261         createOnlySelectedButton.setFont(optionsGroup.getFont());
262         createOnlySelectedButton.setText(DataTransferMessages.FileImport_createSelectedFolders);
263         createOnlySelectedButton.setSelection(true);
264
265     }
266
267     /**
268      * Create the group for creating the root directory
269      */

270     protected void createRootDirectoryGroup(Composite parent) {
271         Composite sourceContainerGroup = new Composite(parent, SWT.NONE);
272         GridLayout layout = new GridLayout();
273         layout.numColumns = 3;
274         sourceContainerGroup.setLayout(layout);
275         sourceContainerGroup.setFont(parent.getFont());
276         sourceContainerGroup.setLayoutData(new GridData(
277                 GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
278
279         Label groupLabel = new Label(sourceContainerGroup, SWT.NONE);
280         groupLabel.setText(getSourceLabel());
281         groupLabel.setFont(parent.getFont());
282
283         // source name entry field
284
sourceNameField = new Combo(sourceContainerGroup, SWT.BORDER);
285         GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
286                 | GridData.GRAB_HORIZONTAL);
287         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
288         sourceNameField.setLayoutData(data);
289         sourceNameField.setFont(parent.getFont());
290
291         sourceNameField.addSelectionListener(new SelectionAdapter() {
292             public void widgetSelected(SelectionEvent e) {
293                 updateFromSourceField();
294             }
295         });
296
297         sourceNameField.addKeyListener(new KeyListener() {
298             /*
299              * @see KeyListener.keyPressed
300              */

301             public void keyPressed(KeyEvent e) {
302                 //If there has been a key pressed then mark as dirty
303
entryChanged = true;
304             }
305
306             /*
307              * @see KeyListener.keyReleased
308              */

309             public void keyReleased(KeyEvent e) {
310             }
311         });
312
313         sourceNameField.addFocusListener(new FocusListener() {
314             /*
315              * @see FocusListener.focusGained(FocusEvent)
316              */

317             public void focusGained(FocusEvent e) {
318                 //Do nothing when getting focus
319
}
320
321             /*
322              * @see FocusListener.focusLost(FocusEvent)
323              */

324             public void focusLost(FocusEvent e) {
325                 //Clear the flag to prevent constant update
326
if (entryChanged) {
327                     entryChanged = false;
328                     updateFromSourceField();
329                 }
330
331             }
332         });
333
334         // source browse button
335
sourceBrowseButton = new Button(sourceContainerGroup, SWT.PUSH);
336         sourceBrowseButton.setText(DataTransferMessages.DataTransfer_browse);
337         sourceBrowseButton.addListener(SWT.Selection, this);
338         sourceBrowseButton.setLayoutData(new GridData(
339                 GridData.HORIZONTAL_ALIGN_FILL));
340         sourceBrowseButton.setFont(parent.getFont());
341         setButtonLayoutData(sourceBrowseButton);
342     }
343
344     /**
345      * Update the receiver from the source name field.
346      */

347
348     private void updateFromSourceField() {
349
350         setSourceName(sourceNameField.getText());
351         //Update enablements when this is selected
352
updateWidgetEnablements();
353     }
354
355     /**
356      * Creates and returns a <code>FileSystemElement</code> if the specified
357      * file system object merits one. The criteria for this are:
358      * Also create the children.
359      */

360     protected MinimizedFileSystemElement createRootElement(
361             Object JavaDoc fileSystemObject, IImportStructureProvider provider) {
362         boolean isContainer = provider.isFolder(fileSystemObject);
363         String JavaDoc elementLabel = provider.getLabel(fileSystemObject);
364
365         // Use an empty label so that display of the element's full name
366
// doesn't include a confusing label
367
MinimizedFileSystemElement dummyParent = new MinimizedFileSystemElement(
368                 "", null, true);//$NON-NLS-1$
369
dummyParent.setPopulated();
370         MinimizedFileSystemElement result = new MinimizedFileSystemElement(
371                 elementLabel, dummyParent, isContainer);
372         result.setFileSystemObject(fileSystemObject);
373
374         //Get the files for the element so as to build the first level
375
result.getFiles(provider);
376
377         return dummyParent;
378     }
379
380     /**
381      * Create the import source specification widgets
382      */

383     protected void createSourceGroup(Composite parent) {
384
385         createRootDirectoryGroup(parent);
386         createFileSelectionGroup(parent);
387         createButtonsGroup(parent);
388     }
389
390     /**
391      * Enable or disable the button group.
392      */

393     protected void enableButtonGroup(boolean enable) {
394         selectTypesButton.setEnabled(enable);
395         selectAllButton.setEnabled(enable);
396         deselectAllButton.setEnabled(enable);
397     }
398
399     /**
400      * Answer a boolean indicating whether the specified source currently exists
401      * and is valid
402      */

403     protected boolean ensureSourceIsValid() {
404         if (new File JavaDoc(getSourceDirectoryName()).isDirectory()) {
405             return true;
406         }
407
408         setErrorMessage(DataTransferMessages.FileImport_invalidSource);
409         sourceNameField.setFocus();
410         return false;
411     }
412
413     /**
414      * Execute the passed import operation. Answer a boolean indicating success.
415      */

416     protected boolean executeImportOperation(ImportOperation op) {
417         initializeOperation(op);
418
419         try {
420             getContainer().run(true, true, op);
421         } catch (InterruptedException JavaDoc e) {
422             return false;
423         } catch (InvocationTargetException JavaDoc e) {
424             displayErrorDialog(e.getTargetException());
425             return false;
426         }
427
428         IStatus status = op.getStatus();
429         if (!status.isOK()) {
430             ErrorDialog
431                     .openError(getContainer().getShell(), DataTransferMessages.FileImport_importProblems,
432                             null, // no special message
433
status);
434             return false;
435         }
436
437         return true;
438     }
439
440     /**
441      * The Finish button was pressed. Try to do the required work now and answer
442      * a boolean indicating success. If false is returned then the wizard will
443      * not close.
444      *
445      * @return boolean
446      */

447     public boolean finish() {
448         if (!ensureSourceIsValid()) {
449             return false;
450         }
451
452         saveWidgetValues();
453
454         Iterator JavaDoc resourcesEnum = getSelectedResources().iterator();
455         List JavaDoc fileSystemObjects = new ArrayList JavaDoc();
456         while (resourcesEnum.hasNext()) {
457             fileSystemObjects.add(((FileSystemElement) resourcesEnum.next())
458                     .getFileSystemObject());
459         }
460
461         if (fileSystemObjects.size() > 0) {
462             return importResources(fileSystemObjects);
463         }
464
465         MessageDialog.openInformation(getContainer().getShell(),
466                 DataTransferMessages.DataTransfer_information,
467                 DataTransferMessages.FileImport_noneSelected);
468
469         return false;
470     }
471
472     /**
473      * Returns a content provider for <code>FileSystemElement</code>s that returns
474      * only files as children.
475      */

476     protected ITreeContentProvider getFileProvider() {
477         return new WorkbenchContentProvider() {
478             public Object JavaDoc[] getChildren(Object JavaDoc o) {
479                 if (o instanceof MinimizedFileSystemElement) {
480                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
481                     return element.getFiles(
482                             FileSystemStructureProvider.INSTANCE).getChildren(
483                             element);
484                 }
485                 return new Object JavaDoc[0];
486             }
487         };
488     }
489
490     /**
491      * Answer the root FileSystemElement that represents the contents of
492      * the currently-specified source. If this FileSystemElement is not
493      * currently defined then create and return it.
494      */

495     protected MinimizedFileSystemElement getFileSystemTree() {
496
497         File JavaDoc sourceDirectory = getSourceDirectory();
498         if (sourceDirectory == null) {
499             return null;
500         }
501
502         return selectFiles(sourceDirectory,
503                 FileSystemStructureProvider.INSTANCE);
504     }
505
506     /**
507      * Returns a content provider for <code>FileSystemElement</code>s that returns
508      * only folders as children.
509      */

510     protected ITreeContentProvider getFolderProvider() {
511         return new WorkbenchContentProvider() {
512             public Object JavaDoc[] getChildren(Object JavaDoc o) {
513                 if (o instanceof MinimizedFileSystemElement) {
514                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
515                     return element.getFolders(
516                             FileSystemStructureProvider.INSTANCE).getChildren(
517                             element);
518                 }
519                 return new Object JavaDoc[0];
520             }
521
522             public boolean hasChildren(Object JavaDoc o) {
523                 if (o instanceof MinimizedFileSystemElement) {
524                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
525                     if (element.isPopulated()) {
526                         return getChildren(element).length > 0;
527                     }
528
529                     //If we have not populated then wait until asked
530
return true;
531                 }
532                 return false;
533             }
534         };
535     }
536
537     /**
538      * Returns a File object representing the currently-named source directory iff
539      * it exists as a valid directory, or <code>null</code> otherwise.
540      */

541     protected File JavaDoc getSourceDirectory() {
542         return getSourceDirectory(this.sourceNameField.getText());
543     }
544
545     /**
546      * Returns a File object representing the currently-named source directory iff
547      * it exists as a valid directory, or <code>null</code> otherwise.
548      *
549      * @param path a String not yet formatted for java.io.File compatability
550      */

551     private File JavaDoc getSourceDirectory(String JavaDoc path) {
552         File JavaDoc sourceDirectory = new File JavaDoc(getSourceDirectoryName(path));
553         if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
554             return null;
555         }
556
557         return sourceDirectory;
558     }
559
560     /**
561      * Answer the directory name specified as being the import source.
562      * Note that if it ends with a separator then the separator is first
563      * removed so that java treats it as a proper directory
564      */

565     private String JavaDoc getSourceDirectoryName() {
566         return getSourceDirectoryName(this.sourceNameField.getText());
567     }
568
569     /**
570      * Answer the directory name specified as being the import source.
571      * Note that if it ends with a separator then the separator is first
572      * removed so that java treats it as a proper directory
573      */

574     private String JavaDoc getSourceDirectoryName(String JavaDoc sourceName) {
575         IPath result = new Path(sourceName.trim());
576
577         if (result.getDevice() != null && result.segmentCount() == 0) {
578             result = result.addTrailingSeparator();
579         } else {
580             result = result.removeTrailingSeparator();
581         }
582
583         return result.toOSString();
584     }
585
586     /**
587      * Answer the string to display as the label for the source specification field
588      */

589     protected String JavaDoc getSourceLabel() {
590         return DataTransferMessages.FileImport_fromDirectory;
591     }
592
593     /**
594      * Handle all events and enablements for widgets in this dialog
595      *
596      * @param event Event
597      */

598     public void handleEvent(Event event) {
599         if (event.widget == sourceBrowseButton) {
600             handleSourceBrowseButtonPressed();
601         }
602
603         super.handleEvent(event);
604     }
605
606     /**
607      * Open an appropriate source browser so that the user can specify a source
608      * to import from
609      */

610     protected void handleSourceBrowseButtonPressed() {
611
612         String JavaDoc currentSource = this.sourceNameField.getText();
613         DirectoryDialog dialog = new DirectoryDialog(
614                 sourceNameField.getShell(), SWT.SAVE);
615         dialog.setText(SELECT_SOURCE_TITLE);
616         dialog.setMessage(SELECT_SOURCE_MESSAGE);
617         dialog.setFilterPath(getSourceDirectoryName(currentSource));
618
619         String JavaDoc selectedDirectory = dialog.open();
620         if (selectedDirectory != null) {
621             //Just quit if the directory is not valid
622
if ((getSourceDirectory(selectedDirectory) == null)
623                     || selectedDirectory.equals(currentSource)) {
624                 return;
625             }
626             //If it is valid then proceed to populate
627
setErrorMessage(null);
628             setSourceName(selectedDirectory);
629             selectionGroup.setFocus();
630         }
631     }
632
633     /**
634      * Open a registered type selection dialog and note the selections
635      * in the receivers types-to-export field.,
636      * Added here so that inner classes can have access
637      */

638     protected void handleTypesEditButtonPressed() {
639
640         super.handleTypesEditButtonPressed();
641     }
642
643     /**
644      * Import the resources with extensions as specified by the user
645      */

646     protected boolean importResources(List JavaDoc fileSystemObjects) {
647         ImportOperation operation = new ImportOperation(getContainerFullPath(),
648                 getSourceDirectory(), FileSystemStructureProvider.INSTANCE,
649                 this, fileSystemObjects);
650
651         operation.setContext(getShell());
652         return executeImportOperation(operation);
653     }
654
655     /**
656      * Initializes the specified operation appropriately.
657      */

658     protected void initializeOperation(ImportOperation op) {
659         op.setCreateContainerStructure(createContainerStructureButton
660                 .getSelection());
661         op.setOverwriteResources(overwriteExistingResourcesCheckbox
662                 .getSelection());
663     }
664
665     /**
666      * Returns whether the extension provided is an extension that
667      * has been specified for export by the user.
668      *
669      * @param extension the resource name
670      * @return <code>true</code> if the resource name is suitable for export based
671      * upon its extension
672      */

673     protected boolean isExportableExtension(String JavaDoc extension) {
674         if (selectedTypes == null) {
675             return true;
676         }
677
678         Iterator JavaDoc itr = selectedTypes.iterator();
679         while (itr.hasNext()) {
680             if (extension.equalsIgnoreCase((String JavaDoc) itr.next())) {
681                 return true;
682             }
683         }
684
685         return false;
686     }
687
688     /**
689      * Repopulate the view based on the currently entered directory.
690      */

691     protected void resetSelection() {
692
693         MinimizedFileSystemElement currentRoot = getFileSystemTree();
694         this.selectionGroup.setRoot(currentRoot);
695
696     }
697
698     /**
699      * Use the dialog store to restore widget values to the values that they held
700      * last time this wizard was used to completion
701      */

702     protected void restoreWidgetValues() {
703         IDialogSettings settings = getDialogSettings();
704         if (settings != null) {
705             String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
706             if (sourceNames == null) {
707                 return; // ie.- no values stored, so stop
708
}
709
710             // set filenames history
711
for (int i = 0; i < sourceNames.length; i++) {
712                 sourceNameField.add(sourceNames[i]);
713             }
714
715             // radio buttons and checkboxes
716
overwriteExistingResourcesCheckbox.setSelection(settings
717                     .getBoolean(STORE_OVERWRITE_EXISTING_RESOURCES_ID));
718
719             boolean createStructure = settings
720                     .getBoolean(STORE_CREATE_CONTAINER_STRUCTURE_ID);
721             createContainerStructureButton.setSelection(createStructure);
722             createOnlySelectedButton.setSelection(!createStructure);
723
724         }
725     }
726
727     /**
728      * Since Finish was pressed, write widget values to the dialog store so that they
729      * will persist into the next invocation of this wizard page
730      */

731     protected void saveWidgetValues() {
732         IDialogSettings settings = getDialogSettings();
733         if (settings != null) {
734             // update source names history
735
String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
736             if (sourceNames == null) {
737                 sourceNames = new String JavaDoc[0];
738             }
739
740             sourceNames = addToHistory(sourceNames, getSourceDirectoryName());
741             settings.put(STORE_SOURCE_NAMES_ID, sourceNames);
742
743             // radio buttons and checkboxes
744
settings.put(STORE_OVERWRITE_EXISTING_RESOURCES_ID,
745                     overwriteExistingResourcesCheckbox.getSelection());
746
747             settings.put(STORE_CREATE_CONTAINER_STRUCTURE_ID,
748                     createContainerStructureButton.getSelection());
749
750         }
751     }
752
753     /**
754      * Invokes a file selection operation using the specified file system and
755      * structure provider. If the user specifies files to be imported then
756      * this selection is cached for later retrieval and is returned.
757      */

758     protected MinimizedFileSystemElement selectFiles(
759             final Object JavaDoc rootFileSystemObject,
760             final IImportStructureProvider structureProvider) {
761
762         final MinimizedFileSystemElement[] results = new MinimizedFileSystemElement[1];
763
764         BusyIndicator.showWhile(getShell().getDisplay(), new Runnable JavaDoc() {
765             public void run() {
766                 //Create the root element from the supplied file system object
767
results[0] = createRootElement(rootFileSystemObject,
768                         structureProvider);
769             }
770         });
771
772         return results[0];
773     }
774
775     /**
776      * Set all of the selections in the selection group to value. Implemented here
777      * to provide access for inner classes.
778      * @param value boolean
779      */

780     protected void setAllSelections(boolean value) {
781         super.setAllSelections(value);
782     }
783
784     /**
785      * Sets the source name of the import to be the supplied path.
786      * Adds the name of the path to the list of items in the
787      * source combo and selects it.
788      *
789      * @param path the path to be added
790      */

791     protected void setSourceName(String JavaDoc path) {
792
793         if (path.length() > 0) {
794
795             String JavaDoc[] currentItems = this.sourceNameField.getItems();
796             int selectionIndex = -1;
797             for (int i = 0; i < currentItems.length; i++) {
798                 if (currentItems[i].equals(path)) {
799                     selectionIndex = i;
800                 }
801             }
802             if (selectionIndex < 0) {
803                 int oldLength = currentItems.length;
804                 String JavaDoc[] newItems = new String JavaDoc[oldLength + 1];
805                 System.arraycopy(currentItems, 0, newItems, 0, oldLength);
806                 newItems[oldLength] = path;
807                 this.sourceNameField.setItems(newItems);
808                 selectionIndex = oldLength;
809             }
810             this.sourceNameField.select(selectionIndex);
811
812             resetSelection();
813         }
814     }
815
816     /**
817      * Update the tree to only select those elements that match the selected types
818      */

819     protected void setupSelectionsBasedOnSelectedTypes() {
820         ProgressMonitorDialog dialog = new ProgressMonitorJobsDialog(
821                 getContainer().getShell());
822         final Map JavaDoc selectionMap = new Hashtable JavaDoc();
823
824         final IElementFilter filter = new IElementFilter() {
825
826             public void filterElements(Collection JavaDoc files,
827                     IProgressMonitor monitor) throws InterruptedException JavaDoc {
828                 if (files == null) {
829                     throw new InterruptedException JavaDoc();
830                 }
831                 Iterator JavaDoc filesList = files.iterator();
832                 while (filesList.hasNext()) {
833                     if (monitor.isCanceled()) {
834                         throw new InterruptedException JavaDoc();
835                     }
836                     checkFile(filesList.next());
837                 }
838             }
839
840             public void filterElements(Object JavaDoc[] files, IProgressMonitor monitor)
841                     throws InterruptedException JavaDoc {
842                 if (files == null) {
843                     throw new InterruptedException JavaDoc();
844                 }
845                 for (int i = 0; i < files.length; i++) {
846                     if (monitor.isCanceled()) {
847                         throw new InterruptedException JavaDoc();
848                     }
849                     checkFile(files[i]);
850                 }
851             }
852
853             private void checkFile(Object JavaDoc fileElement) {
854                 MinimizedFileSystemElement file = (MinimizedFileSystemElement) fileElement;
855                 if (isExportableExtension(file.getFileNameExtension())) {
856                     List JavaDoc elements = new ArrayList JavaDoc();
857                     FileSystemElement parent = file.getParent();
858                     if (selectionMap.containsKey(parent)) {
859                         elements = (List JavaDoc) selectionMap.get(parent);
860                     }
861                     elements.add(file);
862                     selectionMap.put(parent, elements);
863                 }
864             }
865
866         };
867
868         IRunnableWithProgress runnable = new IRunnableWithProgress() {
869             public void run(final IProgressMonitor monitor)
870                     throws InterruptedException JavaDoc {
871                 monitor
872                         .beginTask(
873                                 DataTransferMessages.ImportPage_filterSelections, IProgressMonitor.UNKNOWN);
874                 getSelectedResources(filter, monitor);
875             }
876         };
877
878         try {
879             dialog.run(true, true, runnable);
880         } catch (InvocationTargetException JavaDoc exception) {
881             //Couldn't start. Do nothing.
882
return;
883         } catch (InterruptedException JavaDoc exception) {
884             //Got interrupted. Do nothing.
885
return;
886         }
887         // make sure that all paint operations caused by closing the progress
888
// dialog get flushed, otherwise extra pixels will remain on the screen until
889
// updateSelections is completed
890
getShell().update();
891         // The updateSelections method accesses SWT widgets so cannot be executed
892
// as part of the above progress dialog operation since the operation forks
893
// a new process.
894
if (selectionMap != null) {
895             updateSelections(selectionMap);
896         }
897     }
898
899     /* (non-Javadoc)
900      * Method declared on IDialogPage. Set the selection up when it becomes visible.
901      */

902     public void setVisible(boolean visible) {
903         super.setVisible(visible);
904         resetSelection();
905         if (visible) {
906             this.sourceNameField.setFocus();
907         }
908     }
909
910     /**
911      * Update the selections with those in map . Implemented here to give inner class
912      * visibility
913      * @param map Map - key tree elements, values Lists of list elements
914      */

915     protected void updateSelections(Map JavaDoc map) {
916         super.updateSelections(map);
917     }
918
919     /**
920      * Check if widgets are enabled or disabled by a change in the dialog.
921      * Provided here to give access to inner classes.
922      */

923     protected void updateWidgetEnablements() {
924         super.updateWidgetEnablements();
925         enableButtonGroup(ensureSourceIsValid());
926     }
927
928     /**
929      * Answer a boolean indicating whether self's source specification
930      * widgets currently all contain valid values.
931      */

932     protected boolean validateSourceGroup() {
933         File JavaDoc sourceDirectory = getSourceDirectory();
934         if (sourceDirectory == null) {
935             setMessage(SOURCE_EMPTY_MESSAGE);
936             enableButtonGroup(false);
937             return false;
938         }
939
940         if (sourceConflictsWithDestination(new Path(sourceDirectory.getPath()))) {
941             setMessage(null);
942             setErrorMessage(getSourceConflictMessage());
943             enableButtonGroup(false);
944             return false;
945         }
946
947         List JavaDoc resourcesToExport = selectionGroup.getAllWhiteCheckedItems();
948         if (resourcesToExport.size() == 0){
949             setMessage(null);
950             setErrorMessage(DataTransferMessages.FileImport_noneSelected);
951             return false;
952         }
953         
954         enableButtonGroup(true);
955         setErrorMessage(null);
956         return true;
957     }
958
959     /**
960      * Returns whether the source location conflicts
961      * with the destination resource. This will occur if
962      * the source is already under the destination.
963      *
964      * @param sourcePath the path to check
965      * @return <code>true</code> if there is a conflict, <code>false</code> if not
966      */

967     protected boolean sourceConflictsWithDestination(IPath sourcePath) {
968
969         IContainer container = getSpecifiedContainer();
970         if (container == null) {
971             return false;
972         }
973         
974         IPath destinationLocation = getSpecifiedContainer().getLocation();
975         if (destinationLocation != null) {
976             return destinationLocation.isPrefixOf(sourcePath);
977         }
978         // null destination location is handled in
979
// WizardResourceImportPage
980
return false;
981     }
982
983 }
984
Popular Tags