get category
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / export / pdf / WikiPDFExportWizardPage.java
1 /*
2  * Copyright (c) 2002 Team in a Box Ltd. All rights reserved. This file is made available under the terms and conditions of the
3  * Common Public License v 1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v1.0.html
4  * 
5  * Contributors: Team in a Box Ltd http://www.teaminabox.co.uk/
6  */
7
8 package net.sourceforge.phpeclipse.wiki.export.pdf;
9
10 import java.lang.reflect.InvocationTargetException;
11 import java.util.List;
12
13 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
14
15 import org.eclipse.core.resources.IContainer;
16 import org.eclipse.core.resources.ResourcesPlugin;
17 import org.eclipse.core.runtime.IStatus;
18 import org.eclipse.core.runtime.Path;
19 import org.eclipse.jface.dialogs.DialogSettings;
20 import org.eclipse.jface.dialogs.ErrorDialog;
21 import org.eclipse.jface.dialogs.IDialogSettings;
22 import org.eclipse.jface.dialogs.MessageDialog;
23 import org.eclipse.jface.util.IPropertyChangeListener;
24 import org.eclipse.jface.util.PropertyChangeEvent;
25 import org.eclipse.jface.viewers.ISelection;
26 import org.eclipse.jface.viewers.IStructuredSelection;
27 import org.eclipse.swt.SWT;
28 import org.eclipse.swt.events.SelectionEvent;
29 import org.eclipse.swt.events.SelectionListener;
30 import org.eclipse.swt.graphics.Font;
31 import org.eclipse.swt.layout.GridData;
32 import org.eclipse.swt.layout.GridLayout;
33 import org.eclipse.swt.widgets.Button;
34 import org.eclipse.swt.widgets.Combo;
35 import org.eclipse.swt.widgets.Composite;
36 import org.eclipse.swt.widgets.Event;
37 import org.eclipse.swt.widgets.FileDialog;
38 import org.eclipse.swt.widgets.Group;
39 import org.eclipse.swt.widgets.Label;
40 import org.eclipse.swt.widgets.Widget;
41 import org.eclipse.ui.dialogs.WizardExportResourcesPage;
42 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
43
44 public final class WikiPDFExportWizardPage extends WizardExportResourcesPage implements IPropertyChangeListener, SelectionListener {
45 //  private StringFieldEditor folderText;
46
47   private static final String[] PDF_EXTENSION = { "*.pdf" };
48
49   //dialog store id constants
50   private static final String PAGE_NAME = "WikiPDFExportWizardPage"; //$NON-NLS-1$
51   
52   private static final String STORE_DESTINATION_NAMES = PAGE_NAME+".STORE_DESTINATION_NAMES"; //$NON-NLS-1$
53
54   private static final String STORE_OVERWRITE_EXISTING_FILES_ID = PAGE_NAME+".STORE_OVERWRITE_EXISTING_FILES_ID"; //$NON-NLS-1$
55
56 //  private StringFieldEditor exportFileText;
57
58   private Combo fDestinationNamesCombo;
59
60   private Button destinationBrowseButton;
61
62   protected Button overwriteExistingFilesCheckbox;
63
64   private ISelection fInitialSelection;
65   private IDialogSettings fSettings = null;
66
67   public WikiPDFExportWizardPage(IStructuredSelection selection) {
68     super(PAGE_NAME, selection);
69     setTitle(WikiEditorPlugin.getResourceString("Export.wizardTitle"));
70     setDescription(WikiEditorPlugin.getResourceString("Export.wizardDescription"));
71     this.fInitialSelection = selection;
72   }
73
74   /**
75    * Create the export destination specification widgets
76    * 
77    * @param parent
78    *          org.eclipse.swt.widgets.Composite
79    */
80   protected void createDestinationGroup(Composite parent) {
81
82     Font font = parent.getFont();
83     // destination specification group
84     Composite destinationSelectionGroup = new Composite(parent, SWT.NONE);
85     GridLayout layout = new GridLayout();
86     layout.numColumns = 3;
87     destinationSelectionGroup.setLayout(layout);
88     destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
89     destinationSelectionGroup.setFont(font);
90
91     Label destinationLabel = new Label(destinationSelectionGroup, SWT.NONE);
92     destinationLabel.setText("PDF output filename:");
93     destinationLabel.setFont(font);
94
95     // destination name entry field
96     fDestinationNamesCombo = new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
97     fDestinationNamesCombo.addListener(SWT.Modify, this);
98     fDestinationNamesCombo.addListener(SWT.Selection, this);
99     GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
100     data.widthHint = SIZING_TEXT_FIELD_WIDTH;
101     fDestinationNamesCombo.setLayoutData(data);
102     fDestinationNamesCombo.setFont(font);
103
104     // destination browse button
105     destinationBrowseButton = new Button(destinationSelectionGroup, SWT.PUSH);
106     destinationBrowseButton.setText("Browse..."); //$NON-NLS-1$
107     destinationBrowseButton.addListener(SWT.Selection, this);
108     destinationBrowseButton.setFont(font);
109     setButtonLayoutData(destinationBrowseButton);
110
111     new Label(parent, SWT.NONE); // vertical spacer
112   }
113
114   /**
115    * Create the options specification widgets.
116    * 
117    * @param parent
118    *          org.eclipse.swt.widgets.Composite
119    */
120   protected void createOptionsGroup(Composite parent) {
121     // options group
122     Group optionsGroup = new Group(parent, SWT.NONE);
123     GridLayout layout = new GridLayout();
124     optionsGroup.setLayout(layout);
125     optionsGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
126     optionsGroup.setText(IDEWorkbenchMessages.getString("WizardExportPage.options")); //$NON-NLS-1$
127     optionsGroup.setFont(parent.getFont());
128
129     createOptionsGroupButtons(optionsGroup);
130
131   }
132
133   /**
134    * Create the buttons in the options group.
135    */
136
137   protected void createOptionsGroupButtons(Group optionsGroup) {
138
139     Font font = optionsGroup.getFont();
140     createOverwriteExisting(optionsGroup, font);
141
142     //          createDirectoryStructureOptions(optionsGroup, font);
143   }
144
145   /**
146    * Create the button for checking if we should ask if we are going to overwrite existing files.
147    * 
148    * @param optionsGroup
149    * @param font
150    */
151   protected void createOverwriteExisting(Group optionsGroup, Font font) {
152     // overwrite... checkbox
153     overwriteExistingFilesCheckbox = new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
154     overwriteExistingFilesCheckbox.setText("Overwrite existing files"); //$NON-NLS-1$
155     overwriteExistingFilesCheckbox.setFont(font);
156   }
157
158   /**
159    * Handle all events and enablements for widgets in this page
160    * 
161    * @param e
162    *          Event
163    */
164   public void handleEvent(Event e) {
165     Widget source = e.widget;
166
167     if (source == destinationBrowseButton)
168       handleDestinationBrowseButtonPressed();
169
170     updatePageCompletion();
171   }
172
173   /**
174    * Open an appropriate destination browser so that the user can specify a source to import from
175    */
176   protected void handleDestinationBrowseButtonPressed() {
177     FileDialog dialog = new FileDialog(getContainer().getShell(), SWT.SAVE);
178     dialog.setFilterExtensions(PDF_EXTENSION); 
179     dialog.setText("Select pdf file");
180     dialog.setFilterPath(getDestinationValue());
181     String selectedFileName = dialog.open();
182
183     if (selectedFileName != null) {
184       setErrorMessage(null);
185       setDestinationValue(selectedFileName);
186     }
187   }
188
189 //  /**
190 //   * Answer the contents of self's destination specification widget
191 //   * 
192 //   * @return java.lang.String
193 //   */
194 //  protected String getDestinationValue() {
195 //    
196 //    return fDestinationNamesCombo.getText().trim();
197 //  }
198   /**
199          *      Answer the contents of the destination specification widget. If this
200          *      value does not have the required suffix then add it first.
201          *
202          *      @return java.lang.String
203          */
204         protected String getDestinationValue() {
205                 String destinationText= fDestinationNamesCombo.getText().trim();
206                 if (destinationText.indexOf('.') < 0)
207                         destinationText += getOutputSuffix();
208                 return destinationText;
209         }
210         
211         /**
212          *      Answer the suffix that files exported from this wizard must have.
213          *      If this suffix is a file extension (which is typically the case)
214          *      then it must include the leading period character.
215          *
216          *      @return java.lang.String
217          */
218         protected String getOutputSuffix() {
219                 return ".pdf"; //$NON-NLS-1$
220         }
221
222   /**
223    * Set the contents of the receivers destination specification widget to the passed value
224    *  
225    */
226   protected void setDestinationValue(String value) {
227     fDestinationNamesCombo.setText(value);
228   }
229
230   /**
231    * Hook method for saving widget values for restoration by the next instance of this class.
232    */
233   protected void internalSaveWidgetValues() {
234     
235   }
236
237   /**
238          * Persists resource specification control setting that are to be restored
239          * in the next instance of this page. Subclasses wishing to persist
240          * settings for their controls should extend the hook method 
241          * <code>internalSaveWidgetValues</code>.
242          */
243         public final void saveWidgetValues() {
244                 // update directory names history
245                 IDialogSettings settings= getDialogSettings();
246                 if (settings != null) {
247                         String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
248                         if (directoryNames == null)
249                                 directoryNames= new String[0];
250                         directoryNames= addToHistory(directoryNames, getDestinationValue());
251                         settings.put(STORE_DESTINATION_NAMES, directoryNames);
252
253                         // options
254                         settings.put(STORE_OVERWRITE_EXISTING_FILES_ID, overwriteExistingFilesCheckbox.getSelection());
255                 }
256                 // Allow subclasses to save values
257                 internalSaveWidgetValues();
258         }
259
260   /**
261    * Hook method for restoring widget values to the values that they held last time this wizard was used to completion.
262    */
263   protected void restoreWidgetValues() {
264     IDialogSettings settings = getDialogSettings();
265     if (settings != null) {
266       String[] fileNames = settings.getArray(STORE_DESTINATION_NAMES);
267       if (fileNames == null)
268         return; // ie.- no settings stored
269
270       // destination
271       setDestinationValue(fileNames[0]);
272       for (int i = 0; i < fileNames.length; i++)
273         addDestinationItem(fileNames[i]);
274
275       // options
276       overwriteExistingFilesCheckbox.setSelection(settings.getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID));
277
278       //                        boolean createDirectories =
279       //                                settings.getBoolean(STORE_CREATE_STRUCTURE_ID);
280       //                        createDirectoryStructureButton.setSelection(createDirectories);
281       //                        createSelectionOnlyButton.setSelection(!createDirectories);
282     }
283   }
284
285   /**
286    * Add the passed value to self's destination widget's history
287    * 
288    * @param value
289    *          java.lang.String
290    */
291   protected void addDestinationItem(String value) {
292     fDestinationNamesCombo.add(value);
293   }
294
295   /**
296    * (non-Javadoc) Method declared on IDialogPage.
297    */
298   public void createControl(Composite parent) {
299     super.createControl(parent);
300 //    update();
301     giveFocusToDestination();
302     //          WorkbenchHelp.setHelp(
303     //                  getControl(),
304     //                  IDataTransferHelpContextIds.FILE_SYSTEM_EXPORT_WIZARD_PAGE);
305   }
306
307   /**
308    * Set the current input focus to self's destination entry field
309    */
310   protected void giveFocusToDestination() {
311     fDestinationNamesCombo.setFocus();
312   }
313
314   //  private Composite createControlsContainer(Composite parent) {
315   //    Composite container = new Composite(parent, SWT.NULL);
316   //    GridLayout layout = new GridLayout();
317   //    layout.numColumns = 1;
318   //    layout.verticalSpacing = 20;
319   //    container.setLayout(layout);
320   //    container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
321   //
322   //    createCommonControls(container);
323   //    return container;
324   //  }
325
326   //  private void createCommonControls(Composite parent) {
327   //    Composite container = new Composite(parent, SWT.NULL);
328   //    GridLayout layout = new GridLayout();
329   //    layout.numColumns = 3;
330   //    layout.verticalSpacing = 9;
331   //    container.setLayout(layout);
332   //    container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
333   //
334   //    createFolderControls(container);
335   //    createExportDirectoryControls(container);
336   //  }
337
338   //  private void createExportDirectoryControls(Composite container) {
339   //    exportFileText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardExportDirectory"));
340   //
341   //    Button button = new Button(container, SWT.PUSH);
342   //    button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse"));
343   //    button.addSelectionListener(new SelectionAdapter() {
344   //      public void widgetSelected(SelectionEvent e) {
345   //        handleBrowseHtmlExportLocation();
346   //      }
347   //    });
348   //  }
349
350   //  private void createFolderControls(Composite container) {
351   //    folderText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardFolder"));
352   //
353   //    Button button = new Button(container, SWT.PUSH);
354   //    button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse"));
355   //    button.addSelectionListener(new SelectionAdapter() {
356   //      public void widgetSelected(SelectionEvent e) {
357   //        try {
358   //          handleBrowseFolders();
359   //        } catch (CoreException cex) {
360   //          WikiEditorPlugin.getDefault().log("", cex);
361   //          throw new RuntimeException("Caught CoreException. See log for details.");
362   //        }
363   //      }
364   //    });
365   //  }
366
367   //  private StringFieldEditor addStringFieldEditor(Composite container, String labelText) {
368   //    Label label = new Label(container, SWT.NULL);
369   //    label.setText(labelText);
370   //
371   //    Composite editorComposite = new Composite(container, SWT.NULL);
372   //    editorComposite.setLayout(new GridLayout());
373   //    editorComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
374   //    StringFieldEditor editor = new StringFieldEditor("", "", editorComposite);
375   //
376   //    editor.setPropertyChangeListener(this);
377   //
378   //    return editor;
379   //  }
380
381 //  private void initialize() throws CoreException {
382 //    if (fInitialSelection == null || fInitialSelection.isEmpty() || !(fInitialSelection instanceof IStructuredSelection)) {
383 //      return;
384 //    }
385 //
386 //    IStructuredSelection ssel = (IStructuredSelection) fInitialSelection;
387 //    if (ssel.size() == 1) {
388 //      initialiseFromSelectedObject(ssel.getFirstElement());
389 //    }
390 //  }
391
392 //  private void initialiseFromSelectedObject(Object obj) throws CoreException {
393 //    if (obj instanceof IFolder || obj instanceof IProject) {
394 //      initialiseFolder(((IResource) obj));
395 //    }
396 //  }
397
398 //  private void initialiseFolder(IResource resource) throws CoreException {
399 //    folderText.setStringValue(resource.getFullPath().toString());
400 //    initialiseExportDirectoryText(resource);
401 //  }
402
403 //  private void initialiseExportDirectoryText(IResource resource) throws CoreException {
404 //    String exportDir = resource.getProject().getPersistentProperty(WikiPDFExportWizard.DIRECTORY_QUALIFIED_NAME);
405 //    if (exportDir != null) {
406 //      exportFileText.setStringValue(exportDir);
407 //    } else {
408 //      exportFileText.setStringValue("");
409 //    }
410 //  }
411
412 //  private void handleBrowseHtmlExportLocation() {
413 //    FileDialog dialog = new FileDialog(getShell(), SWT.SINGLE | SWT.OPEN);
414 //    dialog.setFilterExtensions(PDF_EXTENSION);
415 //    String path = dialog.open();
416 //    if (path != null) {
417 //      setDestinationValue(path);
418 ////      exportFileText.setStringValue(path);
419 //    }
420 //  }
421 //
422 //  private void handleBrowseFolders() throws CoreException {
423 //    FileDialog dialog = new FileDialog(getShell());
424 //    //, ResourcesPlugin.getWorkspace().getRoot(), false,
425 //    //  WikiEditorPlugin.getResourceString("Export.wizardSelectFolder"));
426 //    String filePath = dialog.open();
427 //    //    if (dialog.open() == Window.OK) {
428 //    //      Object[] result = dialog.getResult();
429 //    if (filePath != null) {
430 //      //      if (result != null && result.length == 1) {
431 //      //        IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember((IPath) result[0]);
432 //      IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(filePath);
433 //      if (!(resource instanceof IFile)) {
434 //        return;
435 //      }
436 ////      initialiseFolder(resource);
437 //      //      }
438 //    }
439 //  }
440
441   
442   private void dialogChanged() {
443 //    if (getFolderText().length() == 0) {
444 //      updateStatus("File must be specified");
445 //    } else 
446       
447     if (getDestinationValue().length() == 0) {
448       updateStatus("PDF export file must be specified");
449     } else {
450       updateStatus(null);
451     }
452   }
453
454   private void updateStatus(String message) {
455     setErrorMessage(message);
456     setPageComplete(message == null);
457   }
458
459 //  public String getExportDirectoryPath() {
460 //    return exportFileText.getStringValue();
461 //  }
462
463   public void propertyChange(PropertyChangeEvent event) {
464     dialogChanged();
465   }
466
467   public void widgetSelected(SelectionEvent e) {
468     dialogChanged();
469   }
470
471   public void widgetDefaultSelected(SelectionEvent e) {
472     dialogChanged();
473   }
474
475 //  String getFolderText() {
476 //    return folderText.getStringValue();
477 //  }
478
479   public IContainer getFile() {
480     return (IContainer) ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getDestinationValue()));
481   }
482
483   protected boolean executeExportOperation(WikiPDFExporter op) {
484     //  op.setCreateLeadupStructure(
485     //          createDirectoryStructureButton.getSelection());
486     op.setOverwriteFiles(overwriteExistingFilesCheckbox.getSelection());
487
488     try {
489       getContainer().run(true, true, op);
490     } catch (InterruptedException e) {
491       return true;
492     } catch (InvocationTargetException e) {
493       displayErrorDialog(e.getTargetException());
494       return true;
495     }
496
497     IStatus status = op.getStatus();
498     if (!status.isOK()) {
499       ErrorDialog.openError(getContainer().getShell(), "PDF export problems", //$NON-NLS-1$
500           null, // no special message
501           status);
502       return true;
503     }
504
505     return true;
506   }
507
508   /**
509    * The Finish button was pressed. Try to do the required work now and answer a boolean indicating success. If false is returned
510    * then the wizard will not close.
511    * 
512    * @return boolean
513    */
514   public boolean finish() {
515     //          if (!ensureTargetIsValid(new File(getDestinationValue())))
516     //                  return false;
517
518     List resourcesToExport = getWhiteCheckedResources();
519
520     //Save dirty editors if possible but do not stop if not all are saved
521     saveDirtyEditors();
522     // about to invoke the operation so save our state
523     saveWidgetValues();
524
525     if (resourcesToExport.size() > 0)
526       return executeExportOperation(new WikiPDFExporter(resourcesToExport, getDestinationValue(), this));
527
528     MessageDialog.openInformation(getContainer().getShell(), "PDF export", //$NON-NLS-1$
529         "No file selected"); //$NON-NLS-1$
530
531     return false;
532   }
533   
534   /**
535          * Returns a boolean indicating whether the passed File handle is
536          * is valid and available for use.
537          *
538          * @return boolean
539          */
540 //      protected boolean ensureTargetFileIsValid(File targetFile) {
541 //              if (targetFile.exists() && targetFile.isDirectory() && fDestinationNamesCombo.getText().length() > 0) {
542 //                      setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
543 //                      fDestinationNamesCombo.setFocus();
544 //                      return false;
545 //              }
546 //              if (targetFile.exists()) {
547 //                      if (!targetFile.canWrite()) {
548 //                              setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.jarFileExistsAndNotWritable")); //$NON-NLS-1$
549 //                              fDestinationNamesCombo.setFocus();
550 //                              return false;
551 //                      }
552 //              }
553 //              return true;
554 //      }
555
556 }