From: axelcl Date: Fri, 11 Feb 2005 20:25:39 +0000 (+0000) Subject: * added a first PDF Exporter (menu File->Export...) X-Git-Url: http://git.phpeclipse.com * added a first PDF Exporter (menu File->Export...) * works only for 100% correctly generated HTML from the preview renderer. * not very stable at the moment! --- diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/CreatePageAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/CreatePageAction.java index 02546eb..1e4a8db 100644 --- a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/CreatePageAction.java +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/CreatePageAction.java @@ -87,6 +87,47 @@ public class CreatePageAction implements IObjectActionDelegate { public void selectionChanged(IAction action, ISelection selection) { } + public static void createFragmentPage(IFile file, StringBuffer htmlBuffer) { + BufferedInputStream stream = null; + try { +// String templateFileName = Util.getLocalTemplate(file); + // String cssUrl = Util.getLocalCssUrl(file); + String srcBasePath = Util.getWikiTextsPath(file); + String binBasePath = Util.getProjectsWikiOutputPath(file.getProject(), WikiEditorPlugin.HTML_OUTPUT_PATH); + IContentRenderer renderer = RendererFactory.createContentRenderer(file.getProject()); + stream = new BufferedInputStream(file.getContents()); + + String fileName = Util.getHTMLFileName(file, binBasePath, srcBasePath); + String content = new String(getInputStreamAsCharArray(stream, -1, "utf-8")); + String filePath = file.getLocation().toString(); // file.getProjectRelativePath().toString() + if (filePath.startsWith(srcBasePath)) { + filePath = filePath.substring(srcBasePath.length() + 1); + } + // calculate the depth of the file (i.e. ../../../ as much as needed) + int index = 0; + int level = 0; + while (index >= 0) { + index = fileName.indexOf('/', index); + if (index >= 0) { + level++; + index++; + } + } + renderer.render(null, content, htmlBuffer, level, false); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + + } + public static void createPage(IFile file) { String templateFileName = Util.getLocalTemplate(file); String cssUrl = Util.getLocalCssUrl(file); @@ -95,12 +136,12 @@ public class CreatePageAction implements IObjectActionDelegate { createPage(templateFileName, file, binBasePath, srcBasePath); } - public static void createPage(String templateFileName, IFile file, String binBasepath, String srcBasePath) { + public static void createPage(String templateFileName, IFile file, String binBasePath, String srcBasePath) { // only interested in files with the "wp" extension if ("wp".equalsIgnoreCase(file.getFileExtension())) { try { IContentRenderer renderer = RendererFactory.createContentRenderer(file.getProject()); - convertWikiFile(templateFileName, file, binBasepath, srcBasePath, renderer); + convertWikiFile(templateFileName, file, binBasePath, srcBasePath, renderer); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -114,7 +155,7 @@ public class CreatePageAction implements IObjectActionDelegate { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { - // TODO Auto-generated catch block + // TODO Auto-generated catch block e.printStackTrace(); } } else { @@ -129,7 +170,7 @@ public class CreatePageAction implements IObjectActionDelegate { InputStream contentStream = null; try { - String filename = Util.getHTMLFileName(file, binBasepath, srcBasePath); + String filename = Util.getHTMLFileName(file, binBasePath, srcBasePath); if (filename != null) { int index = filename.lastIndexOf('/'); if (index >= 0) { @@ -164,8 +205,8 @@ public class CreatePageAction implements IObjectActionDelegate { } } - public static void convertWikiFile(String templateFileName, IFile file, String binBasePath, String srcBasePath, IContentRenderer renderer) - throws CoreException { + public static void convertWikiFile(String templateFileName, IFile file, String binBasePath, String srcBasePath, + IContentRenderer renderer) throws CoreException { StringBuffer htmlBuffer = new StringBuffer(); convertWikiBuffer(templateFileName, htmlBuffer, file, renderer, true); String htmlName = Util.getHTMLFileName(file, binBasePath, srcBasePath); @@ -193,15 +234,15 @@ public class CreatePageAction implements IObjectActionDelegate { return; } - public static void convertWikiBuffer(String templateFileName, StringBuffer htmlBuffer, IFile file, IContentRenderer renderer, boolean completeHTML) - throws CoreException { + public static void convertWikiBuffer(String templateFileName, StringBuffer htmlBuffer, IFile file, IContentRenderer renderer, + boolean completeHTML) throws CoreException { BufferedInputStream stream = new BufferedInputStream(file.getContents()); try { String content = new String(getInputStreamAsCharArray(stream, -1, null)); String srcPath = Util.getWikiTextsPath(file); String filePath = file.getLocation().toString(); // file.getProjectRelativePath().toString() if (filePath.startsWith(srcPath)) { - filePath = filePath.substring(srcPath.length()+1); + filePath = filePath.substring(srcPath.length() + 1); } createWikiBuffer(templateFileName, htmlBuffer, filePath, content, renderer, completeHTML); } catch (IOException e) { @@ -222,8 +263,8 @@ public class CreatePageAction implements IObjectActionDelegate { * @param content * @param renderer */ - public static void createWikiBuffer(String templateFileName, StringBuffer htmlBuffer, String fileName, String content, IContentRenderer renderer, - boolean completeHTML) { + public static void createWikiBuffer(String templateFileName, StringBuffer htmlBuffer, String fileName, String content, + IContentRenderer renderer, boolean completeHTML) { // calculate the depth of the file (i.e. ../../../ as much as needed) int index = 0; int level = 0; diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/WikiBuilder.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/WikiBuilder.java index f20fddb..81cbc16 100644 --- a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/WikiBuilder.java +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/WikiBuilder.java @@ -4,7 +4,7 @@ import java.io.IOException; import java.util.Map; import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; -import net.sourceforge.phpeclipse.wiki.export.WikiExporter; +import net.sourceforge.phpeclipse.wiki.export.html.WikiHTMLExporter; import net.sourceforge.phpeclipse.wiki.preferences.Util; import org.eclipse.core.internal.resources.Folder; @@ -127,7 +127,7 @@ public class WikiBuilder extends IncrementalProjectBuilder { private void fullBuild(IProgressMonitor monitor) throws CoreException, IOException { try { - WikiExporter wikiExporter = new WikiExporter(); + WikiHTMLExporter wikiExporter = new WikiHTMLExporter(); String srcBasePath = Util.getProjectsWikiTextsPath(fProject); String basePath = Util.getProjectsWikiOutputPath(fProject, WikiEditorPlugin.HTML_OUTPUT_PATH); wikiExporter.export(fProject, basePath, srcBasePath, monitor); diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/BrowserUtil.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/BrowserUtil.java index a066abf..a136b6e 100644 --- a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/BrowserUtil.java +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/BrowserUtil.java @@ -17,6 +17,7 @@ import org.eclipse.ui.texteditor.ITextEditor; public class BrowserUtil { public static void setBrowserPreview(ITextEditor editor) { + IWorkbenchPage page = WikiEditorPlugin.getDefault().getActivePage(); try { IViewPart part = page.findView(BrowserView.ID_BROWSER); diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExportWizard.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExportWizard.java new file mode 100644 index 0000000..97e7f94 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExportWizard.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2002 Team in a Box Ltd. All rights reserved. This file is made available under the terms and conditions of the + * Common Public License v 1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v1.0.html + * + * Contributors: Team in a Box Ltd http://www.teaminabox.co.uk/ + */ + +package net.sourceforge.phpeclipse.wiki.export.html; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; + +public final class WikiHTMLExportWizard extends Wizard implements INewWizard { + static final QualifiedName DIRECTORY_QUALIFIED_NAME = new QualifiedName(WikiEditorPlugin.PLUGIN_ID, "exportDirectory"); + + private WikiHTMLExportWizardPage page; + + private ISelection selection; + + public WikiHTMLExportWizard() { + super(); + setNeedsProgressMonitor(true); + } + + public void addPages() { + page = new WikiHTMLExportWizardPage(selection); + addPage(page); + } + + public boolean performFinish() { + persistExportProperties(); + + final IContainer folder = page.getFolder(); + final String exportDirectory = page.getExportDirectoryPath(); + + return runOperationForContainer(new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) throws InvocationTargetException { + try { + startExport(monitor, folder, exportDirectory); + } catch (Exception e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }); + } + + private boolean runOperationForContainer(IRunnableWithProgress op) { + try { + getContainer().run(true, true, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + WikiEditorPlugin.getDefault().log("", e); + MessageDialog.openError(getShell(), "Error", e.getTargetException().getMessage()); + return false; + } + + return true; + } + + private void startExport(IProgressMonitor monitor, IContainer folder, String exportDirectory) throws CoreException { + try { + final String srcBasePath = Util.getWikiTextsPath(folder); + new WikiHTMLExporter().export(folder, exportDirectory, srcBasePath, monitor); + } catch (Exception ioex) { + throw new CoreException(new Status(IStatus.ERROR, "Failed to write Wiki Documents", IStatus.OK, ioex.getMessage(), ioex)); + } + } + + private void persistExportProperties() { + IProject project = page.getFolder().getProject(); + try { + project.setPersistentProperty(WikiHTMLExportWizard.DIRECTORY_QUALIFIED_NAME, new File(page.getExportDirectoryPath()) + .getAbsolutePath()); + } catch (CoreException cex) { + noteException(cex); + } + } + + private void noteException(CoreException cex) { + WikiEditorPlugin.getDefault().log("Export Error", cex); + throw new RuntimeException("An error occurred. Please see the log for details."); + } + + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExportWizardPage.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExportWizardPage.java new file mode 100644 index 0000000..762dffd --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExportWizardPage.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2002 Team in a Box Ltd. All rights reserved. This file is made available under the terms and conditions of the + * Common Public License v 1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v1.0.html + * + * Contributors: Team in a Box Ltd http://www.teaminabox.co.uk/ + */ + +package net.sourceforge.phpeclipse.wiki.export.html; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.preference.StringFieldEditor; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.DirectoryDialog; +import org.eclipse.swt.widgets.Label; +import org.eclipse.ui.dialogs.ContainerSelectionDialog; + +public final class WikiHTMLExportWizardPage extends WizardPage implements IPropertyChangeListener, SelectionListener { + private StringFieldEditor folderText; + + private StringFieldEditor exportDirectoryText; + + private ISelection selection; + + public WikiHTMLExportWizardPage(ISelection selection) { + super(WikiEditorPlugin.getResourceString("Export.wizardTitle")); + setTitle(WikiEditorPlugin.getResourceString("Export.wizardTitle")); + setDescription(WikiEditorPlugin.getResourceString("Export.wizardDescription")); + this.selection = selection; + } + + public void createControl(Composite parent) { + Composite rootComposite = createControlsContainer(parent); + + try { + initialize(); + } catch (RuntimeException rex) { + throw rex; + } catch (CoreException cex) { + WikiEditorPlugin.getDefault().log("", cex); + throw new RuntimeException("Caught CoreException. See log for details."); + } + dialogChanged(); + setControl(rootComposite); + } + + private Composite createControlsContainer(Composite parent) { + Composite container = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.verticalSpacing = 20; + container.setLayout(layout); + container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + + createCommonControls(container); + return container; + } + + private void createCommonControls(Composite parent) { + Composite container = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 3; + layout.verticalSpacing = 9; + container.setLayout(layout); + container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + + createFolderControls(container); + createExportDirectoryControls(container); + } + + private void createExportDirectoryControls(Composite container) { + exportDirectoryText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardExportDirectory")); + + Button button = new Button(container, SWT.PUSH); + button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse")); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + handleBrowseHtmlExportLocation(); + } + }); + } + + private void createFolderControls(Composite container) { + folderText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardFolder")); + + Button button = new Button(container, SWT.PUSH); + button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse")); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + try { + handleBrowseFolders(); + } catch (CoreException cex) { + WikiEditorPlugin.getDefault().log("", cex); + throw new RuntimeException("Caught CoreException. See log for details."); + } + } + }); + } + + private StringFieldEditor addStringFieldEditor(Composite container, String labelText) { + Label label = new Label(container, SWT.NULL); + label.setText(labelText); + + Composite editorComposite = new Composite(container, SWT.NULL); + editorComposite.setLayout(new GridLayout()); + editorComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + StringFieldEditor editor = new StringFieldEditor("", "", editorComposite); + + editor.setPropertyChangeListener(this); + + return editor; + } + + private void initialize() throws CoreException { + if (selection == null || selection.isEmpty() || !(selection instanceof IStructuredSelection)) { + return; + } + + IStructuredSelection ssel = (IStructuredSelection) selection; + if (ssel.size() == 1) { + initialiseFromSelectedObject(ssel.getFirstElement()); + } + } + + private void initialiseFromSelectedObject(Object obj) throws CoreException { + if (obj instanceof IFolder || obj instanceof IProject) { + initialiseFolder(((IResource) obj)); + } + } + + private void initialiseFolder(IResource resource) throws CoreException { + folderText.setStringValue(resource.getFullPath().toString()); + initialiseExportDirectoryText(resource); + } + + private void initialiseExportDirectoryText(IResource resource) throws CoreException { + String exportDir = resource.getProject().getPersistentProperty(WikiHTMLExportWizard.DIRECTORY_QUALIFIED_NAME); + if (exportDir != null) { + exportDirectoryText.setStringValue(exportDir); + } else { + exportDirectoryText.setStringValue(""); + } + } + + private void handleBrowseHtmlExportLocation() { + DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SINGLE | SWT.OPEN); + String path = dialog.open(); + if (path != null) { + exportDirectoryText.setStringValue(path); + } + } + + private void handleBrowseFolders() throws CoreException { + ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, + WikiEditorPlugin.getResourceString("Export.wizardSelectFolder")); + if (dialog.open() == Window.OK) { + Object[] result = dialog.getResult(); + if (result != null && result.length == 1) { + IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember((IPath) result[0]); + if (resource instanceof IFile) { + return; + } + initialiseFolder(resource); + } + } + } + + private void dialogChanged() { + if (getFolderText().length() == 0) { + updateStatus("Folder must be specified"); + } else if (getExportDirectoryPath().length() == 0) { + updateStatus("Directory must be specified"); + } else { + updateStatus(null); + } + } + + private void updateStatus(String message) { + setErrorMessage(message); + setPageComplete(message == null); + } + + public String getExportDirectoryPath() { + return exportDirectoryText.getStringValue(); + } + + public void propertyChange(PropertyChangeEvent event) { + dialogChanged(); + } + + public void widgetSelected(SelectionEvent e) { + dialogChanged(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + dialogChanged(); + } + + String getFolderText() { + return folderText.getStringValue(); + } + + public IContainer getFolder() { + return (IContainer) ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getFolderText())); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExporter.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExporter.java new file mode 100644 index 0000000..a3ea0c6 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/html/WikiHTMLExporter.java @@ -0,0 +1,90 @@ +package net.sourceforge.phpeclipse.wiki.export.html; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.util.TreeSet; + +import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +//import de.java2html.converter.JavaSource2HTMLConverter; +//import de.java2html.javasource.JavaSource; +//import de.java2html.javasource.JavaSourceParser; +//import de.java2html.options.Java2HtmlConversionOptions; + +public final class WikiHTMLExporter { + + public static final String HTML_EXTENSION = ".html"; + + public static final String WORKSPACE = "workspace"; + + // private File exportDirectory; + + // private ExportLinkMaker exportLinkMaker; + private TreeSet index; + + public WikiHTMLExporter() { + // exportLinkMaker = new ExportLinkMaker(); + index = new TreeSet(String.CASE_INSENSITIVE_ORDER); + } + + public void export(IContainer folder, String exportDirectoryName, String srcBasePath, IProgressMonitor monitor) throws IOException, CoreException, + InstantiationException, IllegalAccessException, ClassNotFoundException { + // exportDirectory = new File(exportDirectoryName); + IResource[] resources = folder.members(IResource.FILE); + String templateFileName = Util.getExportTemplate(folder); +// monitor.beginTask(WikiEditorPlugin.getResourceString("Export.wikiPages"), resources.length + 1); + for (int i = 0; i < resources.length; i++) { + if (resources[i] instanceof IFile) { + monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile")+resources[i].getLocation()); + CreatePageAction.createPage(templateFileName, (IFile) resources[i], exportDirectoryName, srcBasePath); + monitor.worked(1); + } else if (resources[i] instanceof IFolder) { + monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFolder")+resources[i].getLocation()); + export((IFolder) resources[i], exportDirectoryName, srcBasePath, monitor); + monitor.worked(1); + } + } + } + + private void copy(File source, File dest) throws IOException { + FileChannel in = null; + FileChannel out = null; + try { + in = new FileInputStream(source).getChannel(); + out = new FileOutputStream(dest).getChannel(); + long size = in.size(); + MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); + out.write(buf); + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + } + + private boolean isWikiFile(IResource resource) { + return resource instanceof IFile && resource.getFileExtension().equals("wp"); + } + + // private File createHtmlFile(String name) { + // return new File(exportDirectory, name + WikiPDFExporter.HTML_EXTENSION); + // } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/IFileComparator.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/IFileComparator.java new file mode 100644 index 0000000..27d0800 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/IFileComparator.java @@ -0,0 +1,21 @@ +package net.sourceforge.phpeclipse.wiki.export.pdf; + +import java.util.Comparator; + +import org.eclipse.core.resources.IFile; + + +public class IFileComparator implements Comparator { + + /* (non-Javadoc) + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + public int compare(Object o1, Object o2) { + if (o1 instanceof IFile && o2 instanceof IFile) { + IFile f1 = (IFile) o1; + IFile f2 = (IFile) o2; + return f1.getName().compareTo(f2.getName()); + } + return 0; + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiFilesVisitor.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiFilesVisitor.java new file mode 100644 index 0000000..ae42ba0 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiFilesVisitor.java @@ -0,0 +1,42 @@ +package net.sourceforge.phpeclipse.wiki.export.pdf; + +import java.util.ArrayList; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceVisitor; +import org.eclipse.core.runtime.CoreException; + +public class WikiFilesVisitor implements IResourceVisitor { + List list; + + public WikiFilesVisitor() { + list = new ArrayList(100); + } + + public boolean visit(IResource resource) { + switch (resource.getType()) { + case IResource.FILE: + if (resource.getFileExtension().equalsIgnoreCase(WikiEditorPlugin.WP_EXTENSION)) { + list.add(resource); + } + break; +// case IResource.FOLDER: +// try { +// resource.accept(this); +// } catch (CoreException e) { +// e.printStackTrace(); +// } +// break; + } + return true; + } + /** + * @return Returns the list. + */ + public List getList() { + return list; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExportWizard.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExportWizard.java new file mode 100644 index 0000000..891c0ea --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExportWizard.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2002 Team in a Box Ltd. All rights reserved. This file is made available under the terms and conditions of the + * Common Public License v 1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v1.0.html + * + * Contributors: Team in a Box Ltd http://www.teaminabox.co.uk/ + */ + +package net.sourceforge.phpeclipse.wiki.export.pdf; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; + +public final class WikiPDFExportWizard extends Wizard implements INewWizard { + static final QualifiedName DIRECTORY_QUALIFIED_NAME = new QualifiedName(WikiEditorPlugin.PLUGIN_ID, "exportDirectory"); + + private WikiPDFExportWizardPage page; + + private IStructuredSelection selection; + + public WikiPDFExportWizard() { + super(); + setNeedsProgressMonitor(true); + } + + public void addPages() { + page = new WikiPDFExportWizardPage(selection); + addPage(page); + } + + public boolean performFinish() { + return page.finish(); + } + + private boolean runOperationForContainer(IRunnableWithProgress op) { + try { + getContainer().run(true, true, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + WikiEditorPlugin.getDefault().log("", e); + MessageDialog.openError(getShell(), "Error", e.getTargetException().getMessage()); + return false; + } + + return true; + } + + private void persistExportProperties() { + IProject project = page.getFolder().getProject(); + try { + project.setPersistentProperty(WikiPDFExportWizard.DIRECTORY_QUALIFIED_NAME, new File(page.getExportDirectoryPath()) + .getAbsolutePath()); + } catch (CoreException cex) { + noteException(cex); + } + } + + private void noteException(CoreException cex) { + WikiEditorPlugin.getDefault().log("Export Error", cex); + throw new RuntimeException("An error occurred. Please see the log for details."); + } + + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExportWizardPage.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExportWizardPage.java new file mode 100644 index 0000000..729effe --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExportWizardPage.java @@ -0,0 +1,496 @@ +/* + * Copyright (c) 2002 Team in a Box Ltd. All rights reserved. This file is made available under the terms and conditions of the + * Common Public License v 1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v1.0.html + * + * Contributors: Team in a Box Ltd http://www.teaminabox.co.uk/ + */ + +package net.sourceforge.phpeclipse.wiki.export.pdf; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.preference.StringFieldEditor; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.DirectoryDialog; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Widget; +import org.eclipse.ui.dialogs.ContainerSelectionDialog; +import org.eclipse.ui.dialogs.WizardExportResourcesPage; +import org.eclipse.ui.internal.ide.IDEWorkbenchMessages; + +public final class WikiPDFExportWizardPage extends WizardExportResourcesPage implements IPropertyChangeListener, SelectionListener { + private StringFieldEditor folderText; + + private static final String[] PDF_EXTENSION = { "pdf" }; + + //dialog store id constants + private static final String STORE_DESTINATION_NAMES_ID = "WikiPDFExportWizardPage.STORE_DESTINATION_NAMES_ID"; //$NON-NLS-1$ + + private static final String STORE_OVERWRITE_EXISTING_FILES_ID = "WikiPDFExportWizardPage.STORE_OVERWRITE_EXISTING_FILES_ID"; //$NON-NLS-1$ + + private StringFieldEditor exportFileText; + + private Combo destinationNameField; + + private Button destinationBrowseButton; + + protected Button overwriteExistingFilesCheckbox; + + private ISelection selection; + + public WikiPDFExportWizardPage(IStructuredSelection selection) { + super(WikiEditorPlugin.getResourceString("Export.wizardTitle"), selection); + setTitle(WikiEditorPlugin.getResourceString("Export.wizardTitle")); + setDescription(WikiEditorPlugin.getResourceString("Export.wizardDescription")); + this.selection = selection; + } + + /** + * Create the export destination specification widgets + * + * @param parent + * org.eclipse.swt.widgets.Composite + */ + protected void createDestinationGroup(Composite parent) { + + Font font = parent.getFont(); + // destination specification group + Composite destinationSelectionGroup = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 3; + destinationSelectionGroup.setLayout(layout); + destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL)); + destinationSelectionGroup.setFont(font); + + Label destinationLabel = new Label(destinationSelectionGroup, SWT.NONE); + destinationLabel.setText("PDF output filename:"); + destinationLabel.setFont(font); + + // destination name entry field + destinationNameField = new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER); + destinationNameField.addListener(SWT.Modify, this); + destinationNameField.addListener(SWT.Selection, this); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); + data.widthHint = SIZING_TEXT_FIELD_WIDTH; + destinationNameField.setLayoutData(data); + destinationNameField.setFont(font); + + // destination browse button + destinationBrowseButton = new Button(destinationSelectionGroup, SWT.PUSH); + destinationBrowseButton.setText("Browse..."); //$NON-NLS-1$ + destinationBrowseButton.addListener(SWT.Selection, this); + destinationBrowseButton.setFont(font); + setButtonLayoutData(destinationBrowseButton); + + new Label(parent, SWT.NONE); // vertical spacer + } + /** + * Create the options specification widgets. + * + * @param parent org.eclipse.swt.widgets.Composite + */ + protected void createOptionsGroup(Composite parent) { + // options group + Group optionsGroup = new Group(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + optionsGroup.setLayout(layout); + optionsGroup.setLayoutData( + new GridData( + GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + optionsGroup.setText(IDEWorkbenchMessages.getString("WizardExportPage.options")); //$NON-NLS-1$ + optionsGroup.setFont(parent.getFont()); + + createOptionsGroupButtons(optionsGroup); + + } + /** + * Create the buttons in the options group. + */ + + protected void createOptionsGroupButtons(Group optionsGroup) { + + Font font = optionsGroup.getFont(); + createOverwriteExisting(optionsGroup, font); + +// createDirectoryStructureOptions(optionsGroup, font); + } + /** + * Create the button for checking if we should ask if we are going to overwrite existing files. + * + * @param optionsGroup + * @param font + */ + protected void createOverwriteExisting(Group optionsGroup, Font font) { + // overwrite... checkbox + overwriteExistingFilesCheckbox = new Button(optionsGroup, SWT.CHECK | SWT.LEFT); + overwriteExistingFilesCheckbox.setText("Overwrite existing files"); //$NON-NLS-1$ + overwriteExistingFilesCheckbox.setFont(font); + } + + /** + * Handle all events and enablements for widgets in this page + * + * @param e + * Event + */ + public void handleEvent(Event e) { + Widget source = e.widget; + + if (source == destinationBrowseButton) + handleDestinationBrowseButtonPressed(); + + updatePageCompletion(); + } + + /** + * Open an appropriate destination browser so that the user can specify a source to import from + */ + protected void handleDestinationBrowseButtonPressed() { + DirectoryDialog dialog = new DirectoryDialog(getContainer().getShell(), SWT.SAVE); + dialog.setMessage("Select destination"); + dialog.setText("Select title"); + dialog.setFilterPath(getDestinationValue()); + String selectedDirectoryName = dialog.open(); + + if (selectedDirectoryName != null) { + setErrorMessage(null); + setDestinationValue(selectedDirectoryName); + } + } + + /** + * Answer the contents of self's destination specification widget + * + * @return java.lang.String + */ + protected String getDestinationValue() { + return destinationNameField.getText().trim(); + } + + /** + * Set the contents of the receivers destination specification widget to the passed value + * + */ + protected void setDestinationValue(String value) { + destinationNameField.setText(value); + } + + /** + * Hook method for saving widget values for restoration by the next instance of this class. + */ + protected void internalSaveWidgetValues() { + // update directory names history + IDialogSettings settings = getDialogSettings(); + if (settings != null) { + String[] directoryNames = settings.getArray(STORE_DESTINATION_NAMES_ID); + if (directoryNames == null) + directoryNames = new String[0]; + + directoryNames = addToHistory(directoryNames, getDestinationValue()); + settings.put(STORE_DESTINATION_NAMES_ID, directoryNames); + + // options + settings.put(STORE_OVERWRITE_EXISTING_FILES_ID, overwriteExistingFilesCheckbox.getSelection()); + + // settings.put( + // STORE_CREATE_STRUCTURE_ID, + // createDirectoryStructureButton.getSelection()); + + } + } + + /** + * Hook method for restoring widget values to the values that they held last time this wizard was used to completion. + */ + protected void restoreWidgetValues() { + IDialogSettings settings = getDialogSettings(); + if (settings != null) { + String[] directoryNames = settings.getArray(STORE_DESTINATION_NAMES_ID); + if (directoryNames == null) + return; // ie.- no settings stored + + // destination + setDestinationValue(directoryNames[0]); + for (int i = 0; i < directoryNames.length; i++) + addDestinationItem(directoryNames[i]); + + // options + overwriteExistingFilesCheckbox.setSelection(settings.getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID)); + + // boolean createDirectories = + // settings.getBoolean(STORE_CREATE_STRUCTURE_ID); + // createDirectoryStructureButton.setSelection(createDirectories); + // createSelectionOnlyButton.setSelection(!createDirectories); + } + } + /** + * Add the passed value to self's destination widget's history + * + * @param value java.lang.String + */ + protected void addDestinationItem(String value) { + destinationNameField.add(value); + } + /** + * (non-Javadoc) Method declared on IDialogPage. + */ + public void createControl(Composite parent) { + super.createControl(parent); + giveFocusToDestination(); + // WorkbenchHelp.setHelp( + // getControl(), + // IDataTransferHelpContextIds.FILE_SYSTEM_EXPORT_WIZARD_PAGE); + } + + /** + * Set the current input focus to self's destination entry field + */ + protected void giveFocusToDestination() { + destinationNameField.setFocus(); + } + + // private Composite createControlsContainer(Composite parent) { + // Composite container = new Composite(parent, SWT.NULL); + // GridLayout layout = new GridLayout(); + // layout.numColumns = 1; + // layout.verticalSpacing = 20; + // container.setLayout(layout); + // container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + // + // createCommonControls(container); + // return container; + // } + + // private void createCommonControls(Composite parent) { + // Composite container = new Composite(parent, SWT.NULL); + // GridLayout layout = new GridLayout(); + // layout.numColumns = 3; + // layout.verticalSpacing = 9; + // container.setLayout(layout); + // container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + // + // createFolderControls(container); + // createExportDirectoryControls(container); + // } + + // private void createExportDirectoryControls(Composite container) { + // exportFileText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardExportDirectory")); + // + // Button button = new Button(container, SWT.PUSH); + // button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse")); + // button.addSelectionListener(new SelectionAdapter() { + // public void widgetSelected(SelectionEvent e) { + // handleBrowseHtmlExportLocation(); + // } + // }); + // } + + // private void createFolderControls(Composite container) { + // folderText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardFolder")); + // + // Button button = new Button(container, SWT.PUSH); + // button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse")); + // button.addSelectionListener(new SelectionAdapter() { + // public void widgetSelected(SelectionEvent e) { + // try { + // handleBrowseFolders(); + // } catch (CoreException cex) { + // WikiEditorPlugin.getDefault().log("", cex); + // throw new RuntimeException("Caught CoreException. See log for details."); + // } + // } + // }); + // } + + // private StringFieldEditor addStringFieldEditor(Composite container, String labelText) { + // Label label = new Label(container, SWT.NULL); + // label.setText(labelText); + // + // Composite editorComposite = new Composite(container, SWT.NULL); + // editorComposite.setLayout(new GridLayout()); + // editorComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + // StringFieldEditor editor = new StringFieldEditor("", "", editorComposite); + // + // editor.setPropertyChangeListener(this); + // + // return editor; + // } + + private void initialize() throws CoreException { + if (selection == null || selection.isEmpty() || !(selection instanceof IStructuredSelection)) { + return; + } + + IStructuredSelection ssel = (IStructuredSelection) selection; + if (ssel.size() == 1) { + initialiseFromSelectedObject(ssel.getFirstElement()); + } + } + + private void initialiseFromSelectedObject(Object obj) throws CoreException { + if (obj instanceof IFolder || obj instanceof IProject) { + initialiseFolder(((IResource) obj)); + } + } + + private void initialiseFolder(IResource resource) throws CoreException { + folderText.setStringValue(resource.getFullPath().toString()); + initialiseExportDirectoryText(resource); + } + + private void initialiseExportDirectoryText(IResource resource) throws CoreException { + String exportDir = resource.getProject().getPersistentProperty(WikiPDFExportWizard.DIRECTORY_QUALIFIED_NAME); + if (exportDir != null) { + exportFileText.setStringValue(exportDir); + } else { + exportFileText.setStringValue(""); + } + } + + private void handleBrowseHtmlExportLocation() { + FileDialog dialog = new FileDialog(getShell(), SWT.SINGLE | SWT.OPEN); + dialog.setFilterExtensions(PDF_EXTENSION); + String path = dialog.open(); + if (path != null) { + exportFileText.setStringValue(path); + } + } + + private void handleBrowseFolders() throws CoreException { + ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, + WikiEditorPlugin.getResourceString("Export.wizardSelectFolder")); + if (dialog.open() == Window.OK) { + Object[] result = dialog.getResult(); + if (result != null && result.length == 1) { + IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember((IPath) result[0]); + if (resource instanceof IFile) { + return; + } + initialiseFolder(resource); + } + } + } + + private void dialogChanged() { + if (getFolderText().length() == 0) { + updateStatus("Folder must be specified"); + } else if (getExportDirectoryPath().length() == 0) { + updateStatus("Directory must be specified"); + } else { + updateStatus(null); + } + } + + private void updateStatus(String message) { + setErrorMessage(message); + setPageComplete(message == null); + } + + public String getExportDirectoryPath() { + return exportFileText.getStringValue(); + } + + public void propertyChange(PropertyChangeEvent event) { + dialogChanged(); + } + + public void widgetSelected(SelectionEvent e) { + dialogChanged(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + dialogChanged(); + } + + String getFolderText() { + return folderText.getStringValue(); + } + + public IContainer getFolder() { + return (IContainer) ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getFolderText())); + } + + protected boolean executeExportOperation(WikiPDFExporter op) { + // op.setCreateLeadupStructure( + // createDirectoryStructureButton.getSelection()); + op.setOverwriteFiles(overwriteExistingFilesCheckbox.getSelection()); + + try { + getContainer().run(true, true, op); + } catch (InterruptedException e) { + return true; + } catch (InvocationTargetException e) { + displayErrorDialog(e.getTargetException()); + return true; + } + + IStatus status = op.getStatus(); + if (!status.isOK()) { + ErrorDialog.openError(getContainer().getShell(), "PDF export problems", //$NON-NLS-1$ + null, // no special message + status); + return true; + } + + return true; + } + + /** + * The Finish button was pressed. Try to do the required work now and answer a boolean indicating success. If false is returned + * then the wizard will not close. + * + * @return boolean + */ + public boolean finish() { + // if (!ensureTargetIsValid(new File(getDestinationValue()))) + // return false; + + List resourcesToExport = getWhiteCheckedResources(); + + //Save dirty editors if possible but do not stop if not all are saved + saveDirtyEditors(); + // about to invoke the operation so save our state + saveWidgetValues(); + + if (resourcesToExport.size() > 0) + return executeExportOperation(new WikiPDFExporter(resourcesToExport, getDestinationValue(), this)); + + MessageDialog.openInformation(getContainer().getShell(), "PDF export", //$NON-NLS-1$ + "No file selected"); //$NON-NLS-1$ + + return false; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExporter.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExporter.java new file mode 100644 index 0000000..8ab96ef --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/pdf/WikiPDFExporter.java @@ -0,0 +1,302 @@ +package net.sourceforge.phpeclipse.wiki.export.pdf; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.MultiStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.dialogs.IOverwriteQuery; + +import com.lowagie.text.Document; +import com.lowagie.text.DocumentException; +import com.lowagie.text.html.HtmlParser; +import com.lowagie.text.pdf.PdfWriter; + +//import de.java2html.converter.JavaSource2HTMLConverter; +//import de.java2html.javasource.JavaSource; +//import de.java2html.javasource.JavaSourceParser; +//import de.java2html.options.Java2HtmlConversionOptions; + +public final class WikiPDFExporter implements IRunnableWithProgress { + //The constants for the overwrite 3 state + private static final int OVERWRITE_NOT_SET = 0; + + private static final int OVERWRITE_NONE = 1; + + private static final int OVERWRITE_ALL = 2; + + private int overwriteState = OVERWRITE_NOT_SET; + + private List errorTable = new ArrayList(1); + + private List fResourcesToExport; + + private IPath fPath; + + private IOverwriteQuery fOverwriteCallback; + + public WikiPDFExporter(List resources, String destinationPath, IOverwriteQuery overwriteImplementor) { + super(); + fResourcesToExport = resources; + fPath = new Path(destinationPath); + fOverwriteCallback = overwriteImplementor; + } + + // public void export(IContainer folder, String exportDirectoryName, String srcBasePath, IProgressMonitor monitor) throws + // IOException, CoreException, + // InstantiationException, IllegalAccessException, ClassNotFoundException { + // // exportDirectory = new File(exportDirectoryName); + // IResource[] resources = folder.members(IResource.FILE); + // String templateFileName = Util.getExportTemplate(folder); + //// monitor.beginTask(WikiEditorPlugin.getResourceString("Export.wikiPages"), resources.length + 1); + // for (int i = 0; i < resources.length; i++) { + // if (resources[i] instanceof IFile) { + // monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile")+resources[i].getLocation()); + // CreatePageAction.createPage(templateFileName, (IFile) resources[i], exportDirectoryName, srcBasePath); + // monitor.worked(1); + // } else if (resources[i] instanceof IFolder) { + // monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFolder")+resources[i].getLocation()); + // export((IFolder) resources[i], exportDirectoryName, srcBasePath, monitor); + // monitor.worked(1); + // } + // } + // // monitor.subTask(WikiEditorPlugin.getResourceString("Export.linkedResources")); + // // exportLinkedResources(); + // // createIndex(); + //// monitor.worked(1); + // } + + /** + * TODO: This is a horrible hack for a quick solution. + */ + // private void createIndex() throws IOException { + // File indexFile = createHtmlFile("index"); + // + // PrintWriter writer = new PrintWriter(new FileWriter(indexFile)); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(" "); + // writer.print(" Index"); + // writer.println(" "); + // writer.println(" "); + // + // Iterator iterator = index.iterator(); + // while (iterator.hasNext()) { + // String name = (String) iterator.next(); + // writer.print("
"); + // writer.println("" + name + ""); + // } + // + // writer.println(" "); + // writer.println(" "); + // writer.flush(); + // writer.close(); + // } + // private void exportLinkedResources() throws IOException { + // if (!exportLinkMaker.hasLinkedDocuments()) { + // return; + // } + // File workspaceExport = new File(exportDirectory, WikiPDFExporter.WORKSPACE); + // if (!workspaceExport.exists()) { + // workspaceExport.mkdir(); + // } + // HashMap map = exportLinkMaker.getLinkedResources(); + // Iterator iterator = map.keySet().iterator(); + // while (iterator.hasNext()) { + // IResource resource = (IResource) iterator.next(); + // String location = (String) map.get(resource); + // export(resource, location); + // } + // } + // private void export(IResource resource, String location) throws IOException { + // File destination = new File(exportDirectory, location); + // + // if (destination.isDirectory()) { + // return; + // } + // if (!destination.exists()) { + // destination.getParentFile().mkdirs(); + // } + // File source = new File(resource.getLocation().toString()); + // if (isJavaResource(resource)) { + // javaToHtml(source, new File(destination.getParentFile(), destination.getName())); + // } else { + // copy(source, destination); + // } + // } + // private boolean isJavaResource(IResource resource) { + // return "java".equals(resource.getFileExtension()); + // } + // private void javaToHtml(File source, File destination) throws IOException { + // JavaSource java = new JavaSourceParser().parse(new FileReader(source)); + // JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter(java); + // Java2HtmlConversionOptions options = Java2HtmlConversionOptions.getDefault(); + // options.setShowLineNumbers(true); + // options.setShowFileName(true); + // options.setShowJava2HtmlLink(true); + // converter.setConversionOptions(options); + // FileWriter writer = new FileWriter(destination); + // converter.convert(writer); + // writer.flush(); + // writer.close(); + // } + // private void copy(File source, File dest) throws IOException { + // FileChannel in = null; + // FileChannel out = null; + // try { + // in = new FileInputStream(source).getChannel(); + // out = new FileOutputStream(dest).getChannel(); + // long size = in.size(); + // MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); + // out.write(buf); + // } finally { + // if (in != null) { + // in.close(); + // } + // if (out != null) { + // out.close(); + // } + // } + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor) + */ +public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + + WikiFilesVisitor visitor = new WikiFilesVisitor(); + for (int i = 0; i < fResourcesToExport.size(); i++) { + try { + ((IResource) fResourcesToExport.get(i)).accept(visitor); + } catch (CoreException e) { + e.printStackTrace(); + } + } + + List list = visitor.getList(); + Collections.sort(list, new IFileComparator()); + IFile file; + StringBuffer htmlBuffer = new StringBuffer(); + htmlBuffer.append(""); + for (int i = 0; i < list.size(); i++) { + try { + file = (IFile) list.get(i); + monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile") + file.getLocation()); + System.out.println(file.getLocation().toString()); + // TODO add the real title here: + htmlBuffer.append("

"+file.getName()+"


"); + CreatePageAction.createFragmentPage(file, htmlBuffer); + if (i < list.size()-1) { +// TODO create a boolean flag to determine, if we would like a new page or only horizontal ruler + htmlBuffer.append("
"); + } + System.out.println(htmlBuffer.toString()); + // CreatePageAction.createPage(templateFileName, (IFile) resources[i], exportDirectoryName, srcBasePath); + monitor.worked(1); + } catch (Exception e) { + addError("PDF export exception", e); + } + } + htmlBuffer.append(""); + + StringReader stream = null; + String pdffilename = fPath.toString(); + FileOutputStream os = null; + try { + + HtmlParser parser = new HtmlParser(); + Document document = new Document(); + document.open(); + os = new FileOutputStream(pdffilename); + monitor.subTask("Generating PDF file: "+pdffilename); + stream = new StringReader(htmlBuffer.toString()); + PdfWriter pdfWriter = PdfWriter.getInstance(document, os); +// pdfWriter.s + parser.go(document, stream); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (stream!=null) { + stream.close(); + } + if (os!=null) { + try { + os.close(); + } catch (IOException e1) { + } + } + } + + System.out.println(fPath.toString()); + } + /** + * Add a new entry to the error table with the passed information + */ + protected void addError(String message, Throwable e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, message, e)); + } + + /** + * Set this boolean indicating whether exported resources should automatically overwrite existing files when a conflict occurs. If + * not query the user. + * + * @param value + * boolean + */ + public void setOverwriteFiles(boolean value) { + if (value) + overwriteState = OVERWRITE_ALL; + } + + /** + * Returns the status of the export operation. If there were any errors, the result is a status object containing individual + * status objects for each error. If there were no errors, the result is a status object with error code OK. + * + * @return the status + */ + public IStatus getStatus() { + IStatus[] errors = new IStatus[errorTable.size()]; + errorTable.toArray(errors); + return new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, errors, "PDF export problems occured", //$NON-NLS-1$ + null); + } + + // test +// public static void main(String[] args) { +// try { +// HtmlParser parser = new HtmlParser(); +// Document document = new Document(); +// String htmlfilename = "C:/eclipse/wikibooks/wpbin/Synästhesie.html"; +// String pdffilename = "C:/eclipse/wikibooks/wpbin/code_java1.pdf"; +// +// PdfWriter.getInstance(document, new FileOutputStream(pdffilename)); +// parser.go(document, htmlfilename); +// } catch (FileNotFoundException e) { +// e.printStackTrace(); +// } catch (DocumentException e) { +// e.printStackTrace(); +// } +// } +} \ No newline at end of file