Improved PDF export (every article is a chapter, outline, FileDialog)
[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 STORE_DESTINATION_NAMES_ID = "WikiPDFExportWizardPage.STORE_DESTINATION_NAMES_ID"; //$NON-NLS-1$
51
52   private static final String STORE_OVERWRITE_EXISTING_FILES_ID = "WikiPDFExportWizardPage.STORE_OVERWRITE_EXISTING_FILES_ID"; //$NON-NLS-1$
53
54 //  private StringFieldEditor exportFileText;
55
56   private Combo destinationNameField;
57
58   private Button destinationBrowseButton;
59
60   protected Button overwriteExistingFilesCheckbox;
61
62   private ISelection selection;
63   private IDialogSettings fSettings = null;
64
65   public WikiPDFExportWizardPage(IStructuredSelection selection) {
66     super(WikiEditorPlugin.getResourceString("Export.wizardTitle"), selection);
67     setTitle(WikiEditorPlugin.getResourceString("Export.wizardTitle"));
68     setDescription(WikiEditorPlugin.getResourceString("Export.wizardDescription"));
69     this.selection = selection;
70   }
71
72   /**
73    * Create the export destination specification widgets
74    * 
75    * @param parent
76    *          org.eclipse.swt.widgets.Composite
77    */
78   protected void createDestinationGroup(Composite parent) {
79
80     Font font = parent.getFont();
81     // destination specification group
82     Composite destinationSelectionGroup = new Composite(parent, SWT.NONE);
83     GridLayout layout = new GridLayout();
84     layout.numColumns = 3;
85     destinationSelectionGroup.setLayout(layout);
86     destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
87     destinationSelectionGroup.setFont(font);
88
89     Label destinationLabel = new Label(destinationSelectionGroup, SWT.NONE);
90     destinationLabel.setText("PDF output filename:");
91     destinationLabel.setFont(font);
92
93     // destination name entry field
94     destinationNameField = new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
95     destinationNameField.addListener(SWT.Modify, this);
96     destinationNameField.addListener(SWT.Selection, this);
97     GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
98     data.widthHint = SIZING_TEXT_FIELD_WIDTH;
99     destinationNameField.setLayoutData(data);
100     destinationNameField.setFont(font);
101
102     // destination browse button
103     destinationBrowseButton = new Button(destinationSelectionGroup, SWT.PUSH);
104     destinationBrowseButton.setText("Browse..."); //$NON-NLS-1$
105     destinationBrowseButton.addListener(SWT.Selection, this);
106     destinationBrowseButton.setFont(font);
107     setButtonLayoutData(destinationBrowseButton);
108
109     new Label(parent, SWT.NONE); // vertical spacer
110   }
111
112   /**
113    * Create the options specification widgets.
114    * 
115    * @param parent
116    *          org.eclipse.swt.widgets.Composite
117    */
118   protected void createOptionsGroup(Composite parent) {
119     // options group
120     Group optionsGroup = new Group(parent, SWT.NONE);
121     GridLayout layout = new GridLayout();
122     optionsGroup.setLayout(layout);
123     optionsGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
124     optionsGroup.setText(IDEWorkbenchMessages.getString("WizardExportPage.options")); //$NON-NLS-1$
125     optionsGroup.setFont(parent.getFont());
126
127     createOptionsGroupButtons(optionsGroup);
128
129   }
130
131   /**
132    * Create the buttons in the options group.
133    */
134
135   protected void createOptionsGroupButtons(Group optionsGroup) {
136
137     Font font = optionsGroup.getFont();
138     createOverwriteExisting(optionsGroup, font);
139
140     //          createDirectoryStructureOptions(optionsGroup, font);
141   }
142
143   /**
144    * Create the button for checking if we should ask if we are going to overwrite existing files.
145    * 
146    * @param optionsGroup
147    * @param font
148    */
149   protected void createOverwriteExisting(Group optionsGroup, Font font) {
150     // overwrite... checkbox
151     overwriteExistingFilesCheckbox = new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
152     overwriteExistingFilesCheckbox.setText("Overwrite existing files"); //$NON-NLS-1$
153     overwriteExistingFilesCheckbox.setFont(font);
154   }
155
156   /**
157    * Handle all events and enablements for widgets in this page
158    * 
159    * @param e
160    *          Event
161    */
162   public void handleEvent(Event e) {
163     Widget source = e.widget;
164
165     if (source == destinationBrowseButton)
166       handleDestinationBrowseButtonPressed();
167
168     updatePageCompletion();
169   }
170
171   /**
172    * Open an appropriate destination browser so that the user can specify a source to import from
173    */
174   protected void handleDestinationBrowseButtonPressed() {
175     FileDialog dialog = new FileDialog(getContainer().getShell(), SWT.SAVE);
176     dialog.setFilterExtensions(PDF_EXTENSION);
177     dialog.setText("Select pdf file");
178     dialog.setFilterPath(getDestinationValue());
179     String selectedFileName = dialog.open();
180
181     if (selectedFileName != null) {
182       setErrorMessage(null);
183       setDestinationValue(selectedFileName);
184     }
185   }
186
187   /**
188    * Answer the contents of self's destination specification widget
189    * 
190    * @return java.lang.String
191    */
192   protected String getDestinationValue() {
193     return destinationNameField.getText().trim();
194   }
195
196   /**
197    * Set the contents of the receivers destination specification widget to the passed value
198    *  
199    */
200   protected void setDestinationValue(String value) {
201     destinationNameField.setText(value);
202   }
203
204   /**
205    * Hook method for saving widget values for restoration by the next instance of this class.
206    */
207   protected void internalSaveWidgetValues() {
208     // update directory names history
209     IDialogSettings settings = getDialogSettings();
210     if (settings != null) {
211       String[] fileNames = settings.getArray(STORE_DESTINATION_NAMES_ID);
212       if (fileNames == null)
213         fileNames = new String[0];
214
215       fileNames = addToHistory(fileNames, getDestinationValue());
216       settings.put(STORE_DESTINATION_NAMES_ID, fileNames);
217
218       // options
219       settings.put(STORE_OVERWRITE_EXISTING_FILES_ID, overwriteExistingFilesCheckbox.getSelection());
220
221       //                        settings.put(
222       //                                STORE_CREATE_STRUCTURE_ID,
223       //                                createDirectoryStructureButton.getSelection());
224
225     }
226   }
227
228   /**
229    * Hook method for restoring widget values to the values that they held last time this wizard was used to completion.
230    */
231   protected void restoreWidgetValues() {
232     IDialogSettings settings = getDialogSettings();
233     if (settings != null) {
234       String[] fileNames = settings.getArray(STORE_DESTINATION_NAMES_ID);
235       if (fileNames == null)
236         return; // ie.- no settings stored
237
238       // destination
239       setDestinationValue(fileNames[0]);
240       for (int i = 0; i < fileNames.length; i++)
241         addDestinationItem(fileNames[i]);
242
243       // options
244       overwriteExistingFilesCheckbox.setSelection(settings.getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID));
245
246       //                        boolean createDirectories =
247       //                                settings.getBoolean(STORE_CREATE_STRUCTURE_ID);
248       //                        createDirectoryStructureButton.setSelection(createDirectories);
249       //                        createSelectionOnlyButton.setSelection(!createDirectories);
250     }
251   }
252
253   /**
254    * Add the passed value to self's destination widget's history
255    * 
256    * @param value
257    *          java.lang.String
258    */
259   protected void addDestinationItem(String value) {
260     destinationNameField.add(value);
261   }
262
263   /**
264    * (non-Javadoc) Method declared on IDialogPage.
265    */
266   public void createControl(Composite parent) {
267     super.createControl(parent);
268     giveFocusToDestination();
269     //          WorkbenchHelp.setHelp(
270     //                  getControl(),
271     //                  IDataTransferHelpContextIds.FILE_SYSTEM_EXPORT_WIZARD_PAGE);
272   }
273
274   /**
275    * Set the current input focus to self's destination entry field
276    */
277   protected void giveFocusToDestination() {
278     destinationNameField.setFocus();
279   }
280
281   //  private Composite createControlsContainer(Composite parent) {
282   //    Composite container = new Composite(parent, SWT.NULL);
283   //    GridLayout layout = new GridLayout();
284   //    layout.numColumns = 1;
285   //    layout.verticalSpacing = 20;
286   //    container.setLayout(layout);
287   //    container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
288   //
289   //    createCommonControls(container);
290   //    return container;
291   //  }
292
293   //  private void createCommonControls(Composite parent) {
294   //    Composite container = new Composite(parent, SWT.NULL);
295   //    GridLayout layout = new GridLayout();
296   //    layout.numColumns = 3;
297   //    layout.verticalSpacing = 9;
298   //    container.setLayout(layout);
299   //    container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
300   //
301   //    createFolderControls(container);
302   //    createExportDirectoryControls(container);
303   //  }
304
305   //  private void createExportDirectoryControls(Composite container) {
306   //    exportFileText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardExportDirectory"));
307   //
308   //    Button button = new Button(container, SWT.PUSH);
309   //    button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse"));
310   //    button.addSelectionListener(new SelectionAdapter() {
311   //      public void widgetSelected(SelectionEvent e) {
312   //        handleBrowseHtmlExportLocation();
313   //      }
314   //    });
315   //  }
316
317   //  private void createFolderControls(Composite container) {
318   //    folderText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardFolder"));
319   //
320   //    Button button = new Button(container, SWT.PUSH);
321   //    button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse"));
322   //    button.addSelectionListener(new SelectionAdapter() {
323   //      public void widgetSelected(SelectionEvent e) {
324   //        try {
325   //          handleBrowseFolders();
326   //        } catch (CoreException cex) {
327   //          WikiEditorPlugin.getDefault().log("", cex);
328   //          throw new RuntimeException("Caught CoreException. See log for details.");
329   //        }
330   //      }
331   //    });
332   //  }
333
334   //  private StringFieldEditor addStringFieldEditor(Composite container, String labelText) {
335   //    Label label = new Label(container, SWT.NULL);
336   //    label.setText(labelText);
337   //
338   //    Composite editorComposite = new Composite(container, SWT.NULL);
339   //    editorComposite.setLayout(new GridLayout());
340   //    editorComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
341   //    StringFieldEditor editor = new StringFieldEditor("", "", editorComposite);
342   //
343   //    editor.setPropertyChangeListener(this);
344   //
345   //    return editor;
346   //  }
347
348 //  private void initialize() throws CoreException {
349 //    if (selection == null || selection.isEmpty() || !(selection instanceof IStructuredSelection)) {
350 //      return;
351 //    }
352 //
353 //    IStructuredSelection ssel = (IStructuredSelection) selection;
354 //    if (ssel.size() == 1) {
355 //      initialiseFromSelectedObject(ssel.getFirstElement());
356 //    }
357 //  }
358
359 //  private void initialiseFromSelectedObject(Object obj) throws CoreException {
360 //    if (obj instanceof IFolder || obj instanceof IProject) {
361 //      initialiseFolder(((IResource) obj));
362 //    }
363 //  }
364
365 //  private void initialiseFolder(IResource resource) throws CoreException {
366 //    folderText.setStringValue(resource.getFullPath().toString());
367 //    initialiseExportDirectoryText(resource);
368 //  }
369
370 //  private void initialiseExportDirectoryText(IResource resource) throws CoreException {
371 //    String exportDir = resource.getProject().getPersistentProperty(WikiPDFExportWizard.DIRECTORY_QUALIFIED_NAME);
372 //    if (exportDir != null) {
373 //      exportFileText.setStringValue(exportDir);
374 //    } else {
375 //      exportFileText.setStringValue("");
376 //    }
377 //  }
378
379 //  private void handleBrowseHtmlExportLocation() {
380 //    FileDialog dialog = new FileDialog(getShell(), SWT.SINGLE | SWT.OPEN);
381 //    dialog.setFilterExtensions(PDF_EXTENSION);
382 //    String path = dialog.open();
383 //    if (path != null) {
384 //      setDestinationValue(path);
385 ////      exportFileText.setStringValue(path);
386 //    }
387 //  }
388 //
389 //  private void handleBrowseFolders() throws CoreException {
390 //    FileDialog dialog = new FileDialog(getShell());
391 //    //, ResourcesPlugin.getWorkspace().getRoot(), false,
392 //    //  WikiEditorPlugin.getResourceString("Export.wizardSelectFolder"));
393 //    String filePath = dialog.open();
394 //    //    if (dialog.open() == Window.OK) {
395 //    //      Object[] result = dialog.getResult();
396 //    if (filePath != null) {
397 //      //      if (result != null && result.length == 1) {
398 //      //        IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember((IPath) result[0]);
399 //      IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(filePath);
400 //      if (!(resource instanceof IFile)) {
401 //        return;
402 //      }
403 ////      initialiseFolder(resource);
404 //      //      }
405 //    }
406 //  }
407
408   
409   private void dialogChanged() {
410 //    if (getFolderText().length() == 0) {
411 //      updateStatus("File must be specified");
412 //    } else 
413       
414     if (getDestinationValue().length() == 0) {
415       updateStatus("PDF export file must be specified");
416     } else {
417       updateStatus(null);
418     }
419   }
420
421   private void updateStatus(String message) {
422     setErrorMessage(message);
423     setPageComplete(message == null);
424   }
425
426 //  public String getExportDirectoryPath() {
427 //    return exportFileText.getStringValue();
428 //  }
429
430   public void propertyChange(PropertyChangeEvent event) {
431     dialogChanged();
432   }
433
434   public void widgetSelected(SelectionEvent e) {
435     dialogChanged();
436   }
437
438   public void widgetDefaultSelected(SelectionEvent e) {
439     dialogChanged();
440   }
441
442 //  String getFolderText() {
443 //    return folderText.getStringValue();
444 //  }
445
446   public IContainer getFile() {
447     return (IContainer) ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getDestinationValue()));
448   }
449
450   protected boolean executeExportOperation(WikiPDFExporter op) {
451     //  op.setCreateLeadupStructure(
452     //          createDirectoryStructureButton.getSelection());
453     op.setOverwriteFiles(overwriteExistingFilesCheckbox.getSelection());
454
455     try {
456       getContainer().run(true, true, op);
457     } catch (InterruptedException e) {
458       return true;
459     } catch (InvocationTargetException e) {
460       displayErrorDialog(e.getTargetException());
461       return true;
462     }
463
464     IStatus status = op.getStatus();
465     if (!status.isOK()) {
466       ErrorDialog.openError(getContainer().getShell(), "PDF export problems", //$NON-NLS-1$
467           null, // no special message
468           status);
469       return true;
470     }
471
472     return true;
473   }
474
475   /**
476    * The Finish button was pressed. Try to do the required work now and answer a boolean indicating success. If false is returned
477    * then the wizard will not close.
478    * 
479    * @return boolean
480    */
481   public boolean finish() {
482     //          if (!ensureTargetIsValid(new File(getDestinationValue())))
483     //                  return false;
484
485     List resourcesToExport = getWhiteCheckedResources();
486
487     //Save dirty editors if possible but do not stop if not all are saved
488     saveDirtyEditors();
489     // about to invoke the operation so save our state
490     saveWidgetValues();
491
492     if (resourcesToExport.size() > 0)
493       return executeExportOperation(new WikiPDFExporter(resourcesToExport, getDestinationValue(), this));
494
495     MessageDialog.openInformation(getContainer().getShell(), "PDF export", //$NON-NLS-1$
496         "No file selected"); //$NON-NLS-1$
497
498     return false;
499   }
500   /* (non-Javadoc)
501    * @see org.eclipse.jface.wizard.WizardPage#getDialogSettings()
502    */
503 //  protected IDialogSettings getDialogSettings() {
504 //    IDialogSettings dialogBounds= fSettings.getSection(DIALOG_BOUNDS_KEY);
505 //      if (dialogBounds == null) {
506 //              dialogBounds= new DialogSettings(DIALOG_BOUNDS_KEY);
507 //              fSettings.addSection(dialogBounds);
508 //      }
509 //      dialogBounds.put(X, bounds.x);
510 //      dialogBounds.put(Y, bounds.y);
511 //      dialogBounds.put(WIDTH, bounds.width);
512 //      dialogBounds.put(HEIGHT, bounds.height);
513 //    // TODO Auto-generated method stub
514 //    return super.getDialogSettings();
515 //  }
516 }