KickJava   Java API By Example, From Geeks To Geeks.

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


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

11 package org.eclipse.ui.wizards.datatransfer;
12
13
14 import java.io.File;
15 import java.lang.reflect.InvocationTargetException;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Hashtable;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Map;
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.dialogs.FileSystemElement;
57 import org.eclipse.ui.dialogs.WizardResourceImportPage;
58 import org.eclipse.ui.help.WorkbenchHelp;
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
63 /**
64  * Page 1 of the base resource import-from-file-system Wizard
65  */

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

90     private static final String SELECT_TYPES_TITLE = DataTransferMessages.getString("DataTransfer.selectTypes"); //$NON-NLS-1$
91
private static final String SELECT_ALL_TITLE = DataTransferMessages.getString("DataTransfer.selectAll"); //$NON-NLS-1$
92
private static final String DESELECT_ALL_TITLE = DataTransferMessages.getString("DataTransfer.deselectAll"); //$NON-NLS-1$
93
private static final String SELECT_SOURCE_TITLE =
94             DataTransferMessages.getString("FileImport.selectSourceTitle"); //$NON-NLS-1$
95
private static final String SELECT_SOURCE_MESSAGE =
96         DataTransferMessages.getString("FileImport.selectSource"); //$NON-NLS-1$
97
protected static final String SOURCE_EMPTY_MESSAGE = DataTransferMessages.getString("FileImport.sourceEmpty"); //$NON-NLS-1$
98
/**
99  * Creates an instance of this class
100  */

101 protected WizardFileSystemResourceImportPage1(String name, IWorkbench aWorkbench, IStructuredSelection selection) {
102     super(name,selection);
103 }
104 /**
105  * Creates an instance of this class
106  *
107  * @param aWorkbench IWorkbench
108  * @param selection IStructuredSelection
109  */

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

136 protected Button createButton(Composite parent, int id, String label, 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     button.setFont(parent.getFont());
142
143     GridData buttonData = new GridData(GridData.FILL_HORIZONTAL);
144     button.setLayoutData(buttonData);
145
146     button.setData(new Integer(id));
147     button.setText(label);
148     
149     if (defaultButton) {
150         Shell shell = parent.getShell();
151         if (shell != null) {
152             shell.setDefaultButton(button);
153         }
154         button.setFocus();
155     }
156     return button;
157 }
158 /**
159  * Creates the buttons for selecting specific types or selecting all or none of the
160  * elements.
161  *
162  * @param parent the parent control
163  */

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

228 public void createControl(Composite parent) {
229     super.createControl(parent);
230     validateSourceGroup();
231     WorkbenchHelp.setHelp(getControl(), IDataTransferHelpContextIds.FILE_SYSTEM_IMPORT_WIZARD_PAGE);
232 }
233 /**
234  * Create the import options specification widgets.
235  */

236 protected void createOptionsGroupButtons(Group optionsGroup) {
237
238         // overwrite... checkbox
239
overwriteExistingResourcesCheckbox = new Button(optionsGroup, SWT.CHECK);
240         overwriteExistingResourcesCheckbox.setFont(optionsGroup.getFont());
241         overwriteExistingResourcesCheckbox.setText(
242             DataTransferMessages.getString("FileImport.overwriteExisting")); //$NON-NLS-1$
243

244         // create containers radio
245
createContainerStructureButton = new Button(optionsGroup, SWT.RADIO);
246         createContainerStructureButton.setFont(optionsGroup.getFont());
247         createContainerStructureButton.setText(
248             DataTransferMessages.getString("FileImport.createComplete")); //$NON-NLS-1$
249
createContainerStructureButton.setSelection(false);
250         
251         // create selection only radio
252
createOnlySelectedButton = new Button(optionsGroup, SWT.RADIO);
253         createOnlySelectedButton.setFont(optionsGroup.getFont());
254         createOnlySelectedButton.setText(
255             DataTransferMessages.getString("FileImport.createSelectedFolders")); //$NON-NLS-1$
256
createOnlySelectedButton.setSelection(true);
257         
258
259     }
260 /**
261  * Create the group for creating the root directory
262  */

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

295         public void keyPressed(KeyEvent e){
296             //If there has been a key pressed then mark as dirty
297
entryChanged = true;
298         }
299
300         /*
301          * @see KeyListener.keyReleased
302          */

303         public void keyReleased(KeyEvent e){}
304     });
305     
306     sourceNameField.addFocusListener(new FocusListener(){
307         /*
308          * @see FocusListener.focusGained(FocusEvent)
309          */

310         public void focusGained(FocusEvent e){
311             //Do nothing when getting focus
312
}
313         
314         /*
315          * @see FocusListener.focusLost(FocusEvent)
316          */

317         public void focusLost(FocusEvent e){
318             //Clear the flag to prevent constant update
319
if(entryChanged){
320                 entryChanged = false;
321                 updateFromSourceField();
322             }
323             
324         }
325     });
326
327     // source browse button
328
sourceBrowseButton = new Button(sourceContainerGroup, SWT.PUSH);
329     sourceBrowseButton.setText(DataTransferMessages.getString("DataTransfer.browse")); //$NON-NLS-1$
330
sourceBrowseButton.addListener(SWT.Selection, this);
331     sourceBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
332     sourceBrowseButton.setFont(parent.getFont());
333     setButtonLayoutData(sourceBrowseButton);
334 }
335
336 /**
337  * Update the receiver from the source name field.
338  */

339
340 private void updateFromSourceField(){
341     
342     setSourceName(sourceNameField.getText());
343     //Update enablements when this is selected
344
updateWidgetEnablements();
345 }
346     
347 /**
348  * Creates and returns a <code>FileSystemElement</code> if the specified
349  * file system object merits one. The criteria for this are:
350  * Also create the children.
351  */

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

375 protected void createSourceGroup(Composite parent) {
376
377     createRootDirectoryGroup(parent);
378     createFileSelectionGroup(parent);
379     createButtonsGroup(parent);
380 }
381 /**
382  * Enable or disable the button group.
383  */

384 protected void enableButtonGroup(boolean enable) {
385     selectTypesButton.setEnabled(enable);
386     selectAllButton.setEnabled(enable);
387     deselectAllButton.setEnabled(enable);
388 }
389 /**
390  * Answer a boolean indicating whether the specified source currently exists
391  * and is valid
392  */

393 protected boolean ensureSourceIsValid() {
394     if (new File(getSourceDirectoryName()).isDirectory())
395         return true;
396
397     displayErrorDialog(DataTransferMessages.getString("FileImport.invalidSource")); //$NON-NLS-1$
398
sourceNameField.setFocus();
399     return false;
400 }
401 /**
402  * Execute the passed import operation. Answer a boolean indicating success.
403  */

404 protected boolean executeImportOperation(ImportOperation op) {
405     initializeOperation(op);
406      
407     try {
408         getContainer().run(true, true, op);
409     } catch (InterruptedException e) {
410         return false;
411     } catch (InvocationTargetException e) {
412         displayErrorDialog(e.getTargetException());
413         return false;
414     }
415
416     IStatus status = op.getStatus();
417     if (!status.isOK()) {
418         ErrorDialog.openError(getContainer().getShell(),
419             DataTransferMessages.getString("FileImport.importProblems"), //$NON-NLS-1$
420
null, // no special message
421
status);
422         return false;
423     }
424
425     return true;
426 }
427 /**
428  * The Finish button was pressed. Try to do the required work now and answer
429  * a boolean indicating success. If false is returned then the wizard will
430  * not close.
431  *
432  * @return boolean
433  */

434 public boolean finish() {
435     if (!ensureSourceIsValid())
436         return false;
437
438     saveWidgetValues();
439
440     Iterator resourcesEnum = getSelectedResources().iterator();
441     List fileSystemObjects = new ArrayList();
442     while (resourcesEnum.hasNext()) {
443         fileSystemObjects.add(
444             ((FileSystemElement) resourcesEnum.next()).getFileSystemObject());
445     }
446
447     if (fileSystemObjects.size() > 0)
448         return importResources(fileSystemObjects);
449
450     MessageDialog
451         .openInformation(
452             getContainer().getShell(),
453             DataTransferMessages.getString("DataTransfer.information"), //$NON-NLS-1$
454
DataTransferMessages.getString("FileImport.noneSelected")); //$NON-NLS-1$
455

456     return false;
457 }
458 /**
459  * Returns a content provider for <code>FileSystemElement</code>s that returns
460  * only files as children.
461  */

462 protected ITreeContentProvider getFileProvider() {
463     return new WorkbenchContentProvider() {
464         public Object[] getChildren(Object o) {
465             if (o instanceof MinimizedFileSystemElement) {
466                 MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
467                 return element.getFiles(FileSystemStructureProvider.INSTANCE).getChildren(
468                     element);
469             }
470             return new Object[0];
471         }
472     };
473 }
474 /**
475  * Answer the root FileSystemElement that represents the contents of
476  * the currently-specified source. If this FileSystemElement is not
477  * currently defined then create and return it.
478  */

479 protected MinimizedFileSystemElement getFileSystemTree() {
480
481     File sourceDirectory = getSourceDirectory();
482     if (sourceDirectory == null)
483         return null;
484
485     return selectFiles(sourceDirectory, FileSystemStructureProvider.INSTANCE);
486 }
487 /**
488  * Returns a content provider for <code>FileSystemElement</code>s that returns
489  * only folders as children.
490  */

491 protected ITreeContentProvider getFolderProvider() {
492     return new WorkbenchContentProvider() {
493         public Object[] getChildren(Object o) {
494             if (o instanceof MinimizedFileSystemElement) {
495                 MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
496                 return element.getFolders(FileSystemStructureProvider.INSTANCE).getChildren(
497                     element);
498             }
499             return new Object[0];
500         }
501         public boolean hasChildren(Object o) {
502             if (o instanceof MinimizedFileSystemElement) {
503                 MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
504                 if (element.isPopulated())
505                     return getChildren(element).length > 0;
506                 else {
507                     //If we have not populated then wait until asked
508
return true;
509                 }
510             }
511             return false;
512         }
513     };
514 }
515
516 /**
517  * Returns a File object representing the currently-named source directory iff
518  * it exists as a valid directory, or <code>null</code> otherwise.
519  */

520 protected File getSourceDirectory() {
521     return getSourceDirectory(this.sourceNameField.getText());
522 }
523 /**
524  * Returns a File object representing the currently-named source directory iff
525  * it exists as a valid directory, or <code>null</code> otherwise.
526  *
527  * @param path a String not yet formatted for java.io.File compatability
528  */

529 private File getSourceDirectory(String path) {
530     File sourceDirectory = new File(getSourceDirectoryName(path));
531     if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
532         return null;
533     }
534
535     return sourceDirectory;
536 }
537 /**
538  * Answer the directory name specified as being the import source.
539  * Note that if it ends with a separator then the separator is first
540  * removed so that java treats it as a proper directory
541  */

542 private String getSourceDirectoryName() {
543     return getSourceDirectoryName(this.sourceNameField.getText());
544 }
545 /**
546  * Answer the directory name specified as being the import source.
547  * Note that if it ends with a separator then the separator is first
548  * removed so that java treats it as a proper directory
549  */

550 private String getSourceDirectoryName(String sourceName) {
551     IPath result = new Path(sourceName.trim());
552
553     if (result.getDevice() != null && result.segmentCount() == 0) // something like "c:"
554
result = result.addTrailingSeparator();
555     else
556         result = result.removeTrailingSeparator();
557
558     return result.toOSString();
559 }
560 /**
561  * Answer the string to display as the label for the source specification field
562  */

563 protected String getSourceLabel() {
564     return DataTransferMessages.getString("FileImport.fromDirectory"); //$NON-NLS-1$
565
}
566 /**
567  * Handle all events and enablements for widgets in this dialog
568  *
569  * @param event Event
570  */

571 public void handleEvent(Event event) {
572     if (event.widget == sourceBrowseButton)
573         handleSourceBrowseButtonPressed();
574
575     super.handleEvent(event);
576 }
577 /**
578  * Open an appropriate source browser so that the user can specify a source
579  * to import from
580  */

581 protected void handleSourceBrowseButtonPressed() {
582
583     String currentSource = this.sourceNameField.getText();
584     DirectoryDialog dialog =
585         new DirectoryDialog(sourceNameField.getShell(), SWT.SAVE);
586     dialog.setText(SELECT_SOURCE_TITLE);
587     dialog.setMessage(SELECT_SOURCE_MESSAGE);
588     dialog.setFilterPath(getSourceDirectoryName(currentSource));
589
590     String selectedDirectory = dialog.open();
591     if (selectedDirectory != null) {
592         //Just quit if the directory is not valid
593
if ((getSourceDirectory(selectedDirectory) == null)
594             || selectedDirectory.equals(currentSource))
595             return;
596         else { //If it is valid then proceed to populate
597
setErrorMessage(null);
598             setSourceName(selectedDirectory);
599             selectionGroup.setFocus();
600         }
601     }
602 }
603 /**
604  * Open a registered type selection dialog and note the selections
605  * in the receivers types-to-export field.,
606  * Added here so that inner classes can have access
607  */

608 protected void handleTypesEditButtonPressed() {
609
610     super.handleTypesEditButtonPressed();
611 }
612 /**
613  * Import the resources with extensions as specified by the user
614  */

615 protected boolean importResources(List fileSystemObjects) {
616     ImportOperation operation = new ImportOperation(
617         getContainerFullPath(),
618         getSourceDirectory(),
619         FileSystemStructureProvider.INSTANCE,
620         this,
621         fileSystemObjects);
622         
623     operation.setContext(getShell());
624     return executeImportOperation(operation);
625 }
626 /**
627  * Initializes the specified operation appropriately.
628  */

629 protected void initializeOperation(ImportOperation op) {
630     op.setCreateContainerStructure(createContainerStructureButton.getSelection());
631     op.setOverwriteResources(overwriteExistingResourcesCheckbox.getSelection());
632 }
633 /**
634  * Returns whether the extension provided is an extension that
635  * has been specified for export by the user.
636  *
637  * @param extension the resource name
638  * @return <code>true</code> if the resource name is suitable for export based
639  * upon its extension
640  */

641 protected boolean isExportableExtension(String extension) {
642     if (selectedTypes == null) // ie.- all extensions are acceptable
643
return true;
644
645     Iterator enum = selectedTypes.iterator();
646     while (enum.hasNext()) {
647         if (extension.equalsIgnoreCase((String)enum.next()))
648             return true;
649     }
650     
651     return false;
652 }
653 /**
654  * Repopulate the view based on the currently entered directory.
655  */

656 protected void resetSelection() {
657
658     MinimizedFileSystemElement currentRoot = getFileSystemTree();
659     this.selectionGroup.setRoot(currentRoot);
660     
661
662 }
663 /**
664  * Use the dialog store to restore widget values to the values that they held
665  * last time this wizard was used to completion
666  */

667 protected void restoreWidgetValues() {
668     IDialogSettings settings = getDialogSettings();
669     if (settings != null) {
670         String[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
671         if (sourceNames == null)
672             return; // ie.- no values stored, so stop
673

674         // set filenames history
675
for (int i = 0; i < sourceNames.length; i++)
676             sourceNameField.add(sourceNames[i]);
677
678         // radio buttons and checkboxes
679
overwriteExistingResourcesCheckbox.setSelection(
680             settings.getBoolean(STORE_OVERWRITE_EXISTING_RESOURCES_ID));
681
682         boolean createStructure =
683             settings.getBoolean(STORE_CREATE_CONTAINER_STRUCTURE_ID);
684         createContainerStructureButton.setSelection(createStructure);
685         createOnlySelectedButton.setSelection(!createStructure);
686
687     }
688 }
689 /**
690  * Since Finish was pressed, write widget values to the dialog store so that they
691  * will persist into the next invocation of this wizard page
692  */

693 protected void saveWidgetValues() {
694     IDialogSettings settings = getDialogSettings();
695     if (settings != null) {
696         // update source names history
697
String[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
698         if (sourceNames == null)
699             sourceNames = new String[0];
700
701         sourceNames = addToHistory(sourceNames, getSourceDirectoryName());
702         settings.put(STORE_SOURCE_NAMES_ID, sourceNames);
703
704         // radio buttons and checkboxes
705
settings.put(
706             STORE_OVERWRITE_EXISTING_RESOURCES_ID,
707             overwriteExistingResourcesCheckbox.getSelection());
708
709         settings.put(
710             STORE_CREATE_CONTAINER_STRUCTURE_ID,
711             createContainerStructureButton.getSelection());
712
713     }
714 }
715 /**
716  * Invokes a file selection operation using the specified file system and
717  * structure provider. If the user specifies files to be imported then
718  * this selection is cached for later retrieval and is returned.
719  */

720 protected MinimizedFileSystemElement selectFiles(
721     final Object rootFileSystemObject,
722     final IImportStructureProvider structureProvider) {
723
724     final MinimizedFileSystemElement[] results = new MinimizedFileSystemElement[1];
725
726     BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
727         public void run() {
728             //Create the root element from the supplied file system object
729
results[0] = createRootElement(rootFileSystemObject, structureProvider);
730         }
731     });
732
733     return results[0];
734 }
735 /**
736  * Set all of the selections in the selection group to value. Implemented here
737  * to provide access for inner classes.
738  * @param value boolean
739  */

740 protected void setAllSelections(boolean value) {
741     super.setAllSelections(value);
742 }
743 /**
744  * Sets the source name of the import to be the supplied path.
745  * Adds the name of the path to the list of items in the
746  * source combo and selects it.
747  *
748  * @param path the path to be added
749  */

750 protected void setSourceName(String path) {
751
752     if (path.length() > 0) {
753
754         String[] currentItems = this.sourceNameField.getItems();
755         int selectionIndex = -1;
756         for (int i = 0; i < currentItems.length; i++) {
757             if (currentItems[i].equals(path))
758                 selectionIndex = i;
759         }
760         if (selectionIndex < 0) {
761             int oldLength = currentItems.length;
762             String[] newItems = new String[oldLength + 1];
763             System.arraycopy(currentItems, 0, newItems, 0, oldLength);
764             newItems[oldLength] = path;
765             this.sourceNameField.setItems(newItems);
766             selectionIndex = oldLength;
767         }
768         this.sourceNameField.select(selectionIndex);
769
770         resetSelection();
771     }
772 }
773 /**
774  * Update the tree to only select those elements that match the selected types
775  */

776 protected void setupSelectionsBasedOnSelectedTypes() {
777     ProgressMonitorDialog dialog = new ProgressMonitorJobsDialog(getContainer().getShell());
778     final Map selectionMap = new Hashtable();
779     
780     final IElementFilter filter = new IElementFilter() {
781         
782         public void filterElements(Collection files,IProgressMonitor monitor) throws InterruptedException{
783             if(files == null){
784                 throw new InterruptedException();
785             }
786             Iterator filesList = files.iterator();
787             while (filesList.hasNext()) {
788                 if(monitor.isCanceled())
789                     throw new InterruptedException();
790                 checkFile(filesList.next());
791             }
792         }
793         
794         public void filterElements(Object[] files,IProgressMonitor monitor) throws InterruptedException{
795             if(files == null){
796                 throw new InterruptedException();
797             }
798             for(int i =0; i < files.length; i ++){
799                 if(monitor.isCanceled())
800                     throw new InterruptedException();
801                 checkFile(files[i]);
802             }
803         }
804         
805         private void checkFile(Object fileElement){
806             MinimizedFileSystemElement file = (MinimizedFileSystemElement) fileElement;
807             if (isExportableExtension(file.getFileNameExtension())) {
808                 List elements = new ArrayList();
809                 FileSystemElement parent = file.getParent();
810                 if (selectionMap.containsKey(parent))
811                     elements = (List) selectionMap.get(parent);
812                 elements.add(file);
813                 selectionMap.put(parent, elements);
814             }
815         }
816
817     };
818     
819     IRunnableWithProgress runnable = new IRunnableWithProgress() {
820         public void run(final IProgressMonitor monitor) throws InterruptedException{
821             monitor.beginTask(DataTransferMessages.getString("ImportPage.filterSelections"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
822
getSelectedResources(filter,monitor);
823         }
824     };
825     
826     try{
827         dialog.run(true,true,runnable);
828     }
829     catch (InvocationTargetException exception){
830         //Couldn't start. Do nothing.
831
return;
832     }
833     catch (InterruptedException exception){
834         //Got interrupted. Do nothing.
835
return;
836     }
837     // make sure that all paint operations caused by closing the progress
838
// dialog get flushed, otherwise extra pixels will remain on the screen until
839
// updateSelections is completed
840
getShell().update();
841     // The updateSelections method accesses SWT widgets so cannot be executed
842
// as part of the above progress dialog operation since the operation forks
843
// a new process.
844
if (selectionMap != null) {
845         updateSelections(selectionMap);
846     }
847 }
848 /* (non-Javadoc)
849  * Method declared on IDialogPage. Set the selection up when it becomes visible.
850  */

851 public void setVisible(boolean visible) {
852     super.setVisible(visible);
853     resetSelection();
854     if(visible)
855         this.sourceNameField.setFocus();
856 }
857 /**
858  * Update the selections with those in map . Implemented here to give inner class
859  * visibility
860  * @param map Map - key tree elements, values Lists of list elements
861  */

862 protected void updateSelections(Map map) {
863     super.updateSelections(map);
864 }
865 /**
866  * Check if widgets are enabled or disabled by a change in the dialog.
867  * Provided here to give access to inner classes.
868  * @param event Event
869  */

870 protected void updateWidgetEnablements() {
871
872     super.updateWidgetEnablements();
873 }
874 /**
875  * Answer a boolean indicating whether self's source specification
876  * widgets currently all contain valid values.
877  */

878 protected boolean validateSourceGroup() {
879     File sourceDirectory = getSourceDirectory();
880     if (sourceDirectory == null) {
881         setMessage(SOURCE_EMPTY_MESSAGE);
882         enableButtonGroup(false);
883         return false;
884     }
885     
886     if(sourceConflictsWithDestination(new Path(sourceDirectory.getPath()))){
887         setErrorMessage(getSourceConflictMessage()); //$NON-NLS-1$
888
enableButtonGroup(false);
889         return false;
890     }
891     
892     enableButtonGroup(true);
893     return true;
894 }
895
896 /**
897  * Returns whether the source location conflicts
898  * with the destination resource. This will occur if
899  * the source is already under the destination.
900  *
901  * @param sourcePath the path to check
902  * @return <code>true</code> if there is a conflict, <code>false</code> if not
903  */

904 protected boolean sourceConflictsWithDestination(IPath sourcePath){
905     
906     IContainer container = getSpecifiedContainer();
907     if(container == null)
908         return false;
909     else {
910         IPath destinationLocation = getSpecifiedContainer().getLocation();
911         if (destinationLocation != null) {
912             return destinationLocation.isPrefixOf(sourcePath);
913         }
914         else {
915             // null destination location is handled in
916
// WizardResourceImportPage
917
return false;
918         }
919     }
920 }
921
922
923 }
924
Popular Tags