Changes:
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / obfuscator / export / WizardObfuscatorResourceExportPage1.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2003 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 net.sourceforge.phpeclipse.obfuscator.export;
12  
13 import java.io.File;
14 import java.lang.reflect.InvocationTargetException;
15 import java.util.List;
16
17 import org.eclipse.core.resources.IProject;
18 import org.eclipse.core.resources.IWorkspaceRoot;
19 import org.eclipse.core.resources.ResourcesPlugin;
20 import org.eclipse.core.runtime.IPath;
21 import org.eclipse.core.runtime.IStatus;
22 import org.eclipse.core.runtime.Path;
23 import org.eclipse.jface.dialogs.ErrorDialog;
24 import org.eclipse.jface.dialogs.IDialogSettings;
25 import org.eclipse.jface.dialogs.MessageDialog;
26 import org.eclipse.jface.viewers.IStructuredSelection;
27 import org.eclipse.swt.SWT;
28 import org.eclipse.swt.graphics.Font;
29 import org.eclipse.swt.layout.GridData;
30 import org.eclipse.swt.layout.GridLayout;
31 import org.eclipse.swt.widgets.Button;
32 import org.eclipse.swt.widgets.Combo;
33 import org.eclipse.swt.widgets.Composite;
34 import org.eclipse.swt.widgets.DirectoryDialog;
35 import org.eclipse.swt.widgets.Event;
36 import org.eclipse.swt.widgets.Group;
37 import org.eclipse.swt.widgets.Label;
38 import org.eclipse.swt.widgets.Listener;
39 import org.eclipse.swt.widgets.Widget;
40 import org.eclipse.ui.dialogs.WizardExportResourcesPage;
41
42 /**
43  *      Page 1 of the base resource export-to-file-system Wizard
44  */
45 /*package*/
46 class WizardObfuscatorResourceExportPage1
47         extends WizardExportResourcesPage
48         implements Listener {
49
50         // widgets
51         private Combo destinationNameField;
52         private Button destinationBrowseButton;
53         protected Button overwriteExistingFilesCheckbox;
54 //      protected Button createDirectoryStructureButton;
55 //      protected Button createSelectionOnlyButton;
56
57         // constants
58         private static final int SIZING_TEXT_FIELD_WIDTH = 250;
59
60         // dialog store id constants
61         private static final String STORE_DESTINATION_NAMES_ID =
62                 "WizardObfuscatorResourceExportPage1.STORE_DESTINATION_NAMES_ID";       //$NON-NLS-1$
63         private static final String STORE_OVERWRITE_EXISTING_FILES_ID =
64                 "WizardObfuscatorResourceExportPage1.STORE_OVERWRITE_EXISTING_FILES_ID";        //$NON-NLS-1$
65 //      private static final String STORE_CREATE_STRUCTURE_ID =
66 //              "WizardObfuscatorResourceExportPage1.STORE_CREATE_STRUCTURE_ID";        //$NON-NLS-1$
67         //messages
68         private static final String SELECT_DESTINATION_MESSAGE = ObfuscatorExportMessages.getString("FileExport.selectDestinationMessage"); //$NON-NLS-1$
69         private static final String SELECT_DESTINATION_TITLE = ObfuscatorExportMessages.getString("FileExport.selectDestinationTitle"); //$NON-NLS-1$
70         /**
71          *      Create an instance of this class
72          */
73         protected WizardObfuscatorResourceExportPage1(
74                 String name,
75                 IStructuredSelection selection) {
76                 super(name, selection);
77         }
78         /**
79          *      Create an instance of this class
80          */
81         public WizardObfuscatorResourceExportPage1(IStructuredSelection selection) {
82                 this("fileSystemExportPage1", selection); //$NON-NLS-1$
83                 setTitle(ObfuscatorExportMessages.getString("ObfuscatorTransfer.fileSystemTitle")); //$NON-NLS-1$
84                 setDescription(ObfuscatorExportMessages.getString("FileExport.exportLocalFileSystem")); //$NON-NLS-1$
85         }
86         /**
87          *      Add the passed value to self's destination widget's history
88          *
89          *      @param value java.lang.String
90          */
91         protected void addDestinationItem(String value) {
92                 destinationNameField.add(value);
93         }
94         /** (non-Javadoc)
95          * Method declared on IDialogPage.
96          */
97         public void createControl(Composite parent) {
98                 super.createControl(parent);
99                 giveFocusToDestination();
100 //              WorkbenchHelp.setHelp(
101 //                      getControl(),
102 //                      IDataTransferHelpContextIds.FILE_SYSTEM_EXPORT_WIZARD_PAGE);
103         }
104         /**
105          *      Create the export destination specification widgets
106          *
107          *      @param parent org.eclipse.swt.widgets.Composite
108          */
109         protected void createDestinationGroup(Composite parent) {
110
111                 Font font = parent.getFont();
112                 // destination specification group
113                 Composite destinationSelectionGroup = new Composite(parent, SWT.NONE);
114                 GridLayout layout = new GridLayout();
115                 layout.numColumns = 3;
116                 destinationSelectionGroup.setLayout(layout);
117                 destinationSelectionGroup.setLayoutData(
118                         new GridData(
119                                 GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
120                 destinationSelectionGroup.setFont(font);
121
122                 Label destinationLabel = new Label(destinationSelectionGroup, SWT.NONE);
123                 destinationLabel.setText(getDestinationLabel());
124                 destinationLabel.setFont(font);
125
126                 // destination name entry field
127                 destinationNameField =
128                         new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
129                 destinationNameField.addListener(SWT.Modify, this);
130                 destinationNameField.addListener(SWT.Selection, this);
131                 GridData data =
132                         new GridData(
133                                 GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
134                 data.widthHint = SIZING_TEXT_FIELD_WIDTH;
135                 destinationNameField.setLayoutData(data);
136                 destinationNameField.setFont(font);
137
138                 // destination browse button
139                 destinationBrowseButton =
140                         new Button(destinationSelectionGroup, SWT.PUSH);
141                 destinationBrowseButton.setText(ObfuscatorExportMessages.getString("ObfuscatorTransfer.browse")); //$NON-NLS-1$
142                 destinationBrowseButton.addListener(SWT.Selection, this);
143                 destinationBrowseButton.setFont(font);
144                 setButtonLayoutData(destinationBrowseButton);
145
146                 new Label(parent, SWT.NONE); // vertical spacer
147         }
148
149         /**
150          * Create the buttons in the options group.
151          */
152
153         protected void createOptionsGroupButtons(Group optionsGroup) {
154
155                 Font font = optionsGroup.getFont();
156                 createOverwriteExisting(optionsGroup, font);
157
158 //              createDirectoryStructureOptions(optionsGroup, font);
159         }
160
161         /**
162          * Create the buttons for the group that determine if the entire or
163          * selected directory structure should be created.
164          * @param optionsGroup
165          * @param font
166          */
167 //      protected void createDirectoryStructureOptions(
168 //              Group optionsGroup,
169 //              Font font) {
170 //              // create directory structure radios
171 //              createDirectoryStructureButton =
172 //                      new Button(optionsGroup, SWT.RADIO | SWT.LEFT);
173 //              createDirectoryStructureButton.setText(ObfuscatorExportMessages.getString("FileExport.createDirectoryStructure")); //$NON-NLS-1$
174 //              createDirectoryStructureButton.setSelection(false);
175 //              createDirectoryStructureButton.setFont(font);
176 //
177 //              // create directory structure radios
178 //              createSelectionOnlyButton =
179 //                      new Button(optionsGroup, SWT.RADIO | SWT.LEFT);
180 //              createSelectionOnlyButton.setText(
181 //                      ObfuscatorExportMessages.getString(
182 //                              "FileExport.createSelectedDirectories"));//$NON-NLS-1$
183 //              createSelectionOnlyButton.setSelection(true);
184 //              createSelectionOnlyButton.setFont(font);
185 //      }
186
187         /**
188          * Create the button for checking if we should ask if we are going to
189          * overwrite existing files.
190          * @param optionsGroup
191          * @param font
192          */
193         protected void createOverwriteExisting(Group optionsGroup, Font font) {
194                 // overwrite... checkbox
195                 overwriteExistingFilesCheckbox =
196                         new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
197                 overwriteExistingFilesCheckbox.setText(ObfuscatorExportMessages.getString("ExportFile.overwriteExisting")); //$NON-NLS-1$
198                 overwriteExistingFilesCheckbox.setFont(font);
199         }
200
201         /**
202          * Attempts to ensure that the specified directory exists on the local file system.
203          * Answers a boolean indicating success.
204          *
205          * @return boolean
206          * @param directory java.io.File
207          */
208         protected boolean ensureDirectoryExists(File directory) {
209                 if (!directory.exists()) {
210                         if (!queryYesNoQuestion(ObfuscatorExportMessages.getString("ObfuscatorTransfer.createTargetDirectory"))) //$NON-NLS-1$
211                                 return false;
212
213                         if (!directory.mkdirs()) {
214                                 displayErrorDialog(ObfuscatorExportMessages.getString("ObfuscatorTransfer.directoryCreationError")); //$NON-NLS-1$
215                                 giveFocusToDestination();
216                                 return false;
217                         }
218                 }
219
220                 return true;
221         }
222         /**
223          *      If the target for export does not exist then attempt to create it.
224          *      Answer a boolean indicating whether the target exists (ie.- if it
225          *      either pre-existed or this method was able to create it)
226          *
227          *      @return boolean
228          */
229         protected boolean ensureTargetIsValid(File targetDirectory) {
230                 if (targetDirectory.exists() && !targetDirectory.isDirectory()) {
231                         displayErrorDialog(ObfuscatorExportMessages.getString("FileExport.directoryExists")); //$NON-NLS-1$
232                         giveFocusToDestination();
233                         return false;
234                 }
235
236                 return ensureDirectoryExists(targetDirectory);
237         }
238         /**
239          *  Set up and execute the passed Operation.  Answer a boolean indicating success.
240          *
241          *  @return boolean
242          */
243         protected boolean executeExportOperation(ObfuscatorExportOperation op) {
244 //              op.setCreateLeadupStructure(
245 //                      createDirectoryStructureButton.getSelection());
246                 op.setOverwriteFiles(overwriteExistingFilesCheckbox.getSelection());
247
248                 try {
249                         getContainer().run(true, true, op);
250                 } catch (InterruptedException e) {
251                         return false;
252                 } catch (InvocationTargetException e) {
253                         displayErrorDialog(e.getTargetException());
254                         return false;
255                 }
256
257                 IStatus status = op.getStatus();
258                 if (!status.isOK()) {
259                         ErrorDialog.openError(getContainer().getShell(), ObfuscatorExportMessages.getString("ObfuscatorTransfer.exportProblems"), //$NON-NLS-1$
260                         null, // no special message
261                         status);
262                         return false;
263                 }
264
265                 return true;
266         }
267         /**
268          *      The Finish button was pressed.  Try to do the required work now and answer
269          *      a boolean indicating success.  If false is returned then the wizard will
270          *      not close.
271          *
272          *      @return boolean
273          */
274         public boolean finish() {
275                 if (!ensureTargetIsValid(new File(getDestinationValue())))
276                         return false;
277
278                 List resourcesToExport = getWhiteCheckedResources();
279
280                 //Save dirty editors if possible but do not stop if not all are saved
281                 saveDirtyEditors();
282                 // about to invoke the operation so save our state
283                 saveWidgetValues();
284
285                 if (resourcesToExport.size() > 0)
286                         return executeExportOperation(
287                                 new ObfuscatorExportOperation(
288                                         null,
289                                         resourcesToExport,
290                                         getDestinationValue(),
291                                         this));
292
293                 MessageDialog.openInformation(getContainer().getShell(), ObfuscatorExportMessages.getString("ObfuscatorTransfer.information"), //$NON-NLS-1$
294                 ObfuscatorExportMessages.getString("FileExport.noneSelected")); //$NON-NLS-1$
295
296                 return false;
297         }
298         /**
299          *      Answer the string to display in self as the destination type
300          *
301          *      @return java.lang.String
302          */
303         protected String getDestinationLabel() {
304                 return ObfuscatorExportMessages.getString("FileExport.toDirectory"); //$NON-NLS-1$
305         }
306         /**
307          *      Answer the contents of self's destination specification widget
308          *
309          *      @return java.lang.String
310          */
311         protected String getDestinationValue() {
312                 return destinationNameField.getText().trim();
313         }
314         /**
315          *      Set the current input focus to self's destination entry field
316          */
317         protected void giveFocusToDestination() {
318                 destinationNameField.setFocus();
319         }
320         /**
321          *      Open an appropriate destination browser so that the user can specify a source
322          *      to import from
323          */
324         protected void handleDestinationBrowseButtonPressed() {
325                 DirectoryDialog dialog =
326                         new DirectoryDialog(getContainer().getShell(), SWT.SAVE);
327                 dialog.setMessage(SELECT_DESTINATION_MESSAGE);
328                 dialog.setText(SELECT_DESTINATION_TITLE);
329                 dialog.setFilterPath(getDestinationValue());
330                 String selectedDirectoryName = dialog.open();
331
332                 if (selectedDirectoryName != null) {
333                         setErrorMessage(null);
334                         setDestinationValue(selectedDirectoryName);
335                 }
336         }
337         /**
338          * Handle all events and enablements for widgets in this page
339          * @param e Event
340          */
341         public void handleEvent(Event e) {
342                 Widget source = e.widget;
343
344                 if (source == destinationBrowseButton)
345                         handleDestinationBrowseButtonPressed();
346
347                 updatePageCompletion();
348         }
349         /**
350          *      Hook method for saving widget values for restoration by the next instance
351          *      of this class.
352          */
353         protected void internalSaveWidgetValues() {
354                 // update directory names history
355                 IDialogSettings settings = getDialogSettings();
356                 if (settings != null) {
357                         String[] directoryNames =
358                                 settings.getArray(STORE_DESTINATION_NAMES_ID);
359                         if (directoryNames == null)
360                                 directoryNames = new String[0];
361
362                         directoryNames =
363                                 addToHistory(directoryNames, getDestinationValue());
364                         settings.put(STORE_DESTINATION_NAMES_ID, directoryNames);
365
366                         // options
367                         settings.put(
368                                 STORE_OVERWRITE_EXISTING_FILES_ID,
369                                 overwriteExistingFilesCheckbox.getSelection());
370
371 //                      settings.put(
372 //                              STORE_CREATE_STRUCTURE_ID,
373 //                              createDirectoryStructureButton.getSelection());
374
375                 }
376         }
377         /**
378          *      Hook method for restoring widget values to the values that they held
379          *      last time this wizard was used to completion.
380          */
381         protected void restoreWidgetValues() {
382                 IDialogSettings settings = getDialogSettings();
383                 if (settings != null) {
384                         String[] directoryNames =
385                                 settings.getArray(STORE_DESTINATION_NAMES_ID);
386                         if (directoryNames == null)
387                                 return; // ie.- no settings stored
388
389                         // destination
390                         setDestinationValue(directoryNames[0]);
391                         for (int i = 0; i < directoryNames.length; i++)
392                                 addDestinationItem(directoryNames[i]);
393
394                         // options
395                         overwriteExistingFilesCheckbox.setSelection(
396                                 settings.getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID));
397
398 //                      boolean createDirectories =
399 //                              settings.getBoolean(STORE_CREATE_STRUCTURE_ID);
400 //                      createDirectoryStructureButton.setSelection(createDirectories);
401 //                      createSelectionOnlyButton.setSelection(!createDirectories);
402                 }
403         }
404         /**
405          *      Set the contents of the receivers destination specification widget to
406          *      the passed value
407          *
408          */
409         protected void setDestinationValue(String value) {
410                 destinationNameField.setText(value);
411         }
412         /**
413          *      Answer a boolean indicating whether the receivers destination specification
414          *      widgets currently all contain valid values.
415          */
416         protected boolean validateDestinationGroup() {
417                 String destinationValue = getDestinationValue();
418                 if (destinationValue.length() == 0) {
419                         setMessage(destinationEmptyMessage());
420                         return false;
421                 }
422
423                 String conflictingContainer =
424                         getConflictingContainerNameFor(destinationValue);
425                 if (conflictingContainer == null)
426                         setErrorMessage(""); //$NON-NLS-1$
427                 else {
428                         setErrorMessage(ObfuscatorExportMessages.format("FileExport.conflictingContainer", //$NON-NLS-1$
429                         new Object[] { conflictingContainer }));
430                         giveFocusToDestination();
431                         return false;
432                 }
433
434                 return true;
435         }
436         
437         /**
438          * Get the message used to denote an empty destination.
439          */
440         protected String destinationEmptyMessage(){
441                 return ObfuscatorExportMessages.getString("FileExport.destinationEmpty"); //$NON-NLS-1$
442         }
443
444         /**
445          * Returns the name of a container with a location that encompasses targetDirectory.
446          * Returns null if there is no conflict.
447          * 
448          * @param targetDirectory the path of the directory to check.
449          * @return the conflicting container name or <code>null</code>
450          */
451         protected String getConflictingContainerNameFor(String targetDirectory) {
452
453                 IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
454                 IPath testPath = new Path(targetDirectory);
455
456                 if (root.getLocation().isPrefixOf(testPath))
457                         return ObfuscatorExportMessages.getString("FileExport.rootName"); //$NON-NLS-1$
458
459                 IProject[] projects = root.getProjects();
460
461                 for (int i = 0; i < projects.length; i++) {
462                         if (projects[i].getLocation().isPrefixOf(testPath))
463                                 return projects[i].getName();
464                 }
465
466                 return null;
467
468         }
469
470 }