unified title and description handling in wizards
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / wizards / PHPFileWizard.java
1 package net.sourceforge.phpeclipse.wizards;
2
3 /**********************************************************************
4  Copyright (c) 2000, 2002 IBM Corp. and others.
5  All rights reserved. This program and the accompanying materials
6  are made available under the terms of the Common Public License v1.0
7  which accompanies this distribution, and is available at
8  http://www.eclipse.org/legal/cpl-v10.html
9
10  Contributors:
11  IBM Corporation - Initial implementation
12  www.phpeclipse.de
13  **********************************************************************/
14
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.lang.reflect.InvocationTargetException;
19
20 import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility;
21 import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext;
22 import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType;
23 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
24
25 import org.eclipse.core.resources.IContainer;
26 import org.eclipse.core.resources.IFile;
27 import org.eclipse.core.resources.IProject;
28 import org.eclipse.core.resources.IResource;
29 import org.eclipse.core.resources.IWorkspaceRoot;
30 import org.eclipse.core.resources.ResourcesPlugin;
31 import org.eclipse.core.runtime.CoreException;
32 import org.eclipse.core.runtime.IProgressMonitor;
33 import org.eclipse.core.runtime.IStatus;
34 import org.eclipse.core.runtime.Path;
35 import org.eclipse.core.runtime.Status;
36 import org.eclipse.jface.dialogs.MessageDialog;
37 import org.eclipse.jface.operation.IRunnableWithProgress;
38 import org.eclipse.jface.text.templates.Template;
39 import org.eclipse.jface.viewers.ISelection;
40 import org.eclipse.jface.viewers.IStructuredSelection;
41 import org.eclipse.jface.wizard.Wizard;
42 import org.eclipse.ui.INewWizard;
43 import org.eclipse.ui.IWorkbench;
44 import org.eclipse.ui.IWorkbenchPage;
45 import org.eclipse.ui.IWorkbenchWizard;
46 import org.eclipse.ui.PartInitException;
47 import org.eclipse.ui.PlatformUI;
48 import org.eclipse.ui.ide.IDE;
49
50 /**
51  * This wizard creates one file with the extension "php".
52  */
53 public class PHPFileWizard extends Wizard implements INewWizard {
54
55   private PHPFileWizardPage page;
56
57   private ISelection selection;
58
59   public PHPFileWizard() {
60     super();
61     setNeedsProgressMonitor(true);
62     setWindowTitle(PHPWizardMessages.getString("WizardNewProjectCreationPage.windowTitle"));
63   }
64
65   /**
66    * Adding the page to the wizard.
67    */
68   public void addPages() {
69     page = new PHPFileWizardPage(selection);
70     addPage(page);
71   }
72
73   /**
74    * This method is called when 'Finish' button is pressed in the wizard. We will create an operation and run it using wizard as
75    * execution context.
76    */
77   public boolean performFinish() {
78     final String containerName = page.getContainerName();
79     final String fileName = page.getFileName();
80     IRunnableWithProgress op = new IRunnableWithProgress() {
81       public void run(IProgressMonitor monitor) throws InvocationTargetException {
82         try {
83           doFinish(containerName, fileName, monitor);
84         } catch (CoreException e) {
85           throw new InvocationTargetException(e);
86         } finally {
87           monitor.done();
88         }
89       }
90     };
91     try {
92       getContainer().run(true, false, op);
93     } catch (InterruptedException e) {
94       return false;
95     } catch (InvocationTargetException e) {
96       Throwable realException = e.getTargetException();
97       MessageDialog.openError(getShell(), PHPWizardMessages.getString("Wizard.error"), realException.getMessage());
98       return false;
99     }
100     return true;
101   }
102
103   /**
104    * The worker method. It will find the container, create the file if missing or just replace its contents, and open the editor on
105    * the newly created file.
106    */
107   private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException {
108     // create a sample file
109     monitor.beginTask(PHPWizardMessages.getString("Wizard.Monitor.creating") + " " + fileName, 2);
110     IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
111     IResource resource = root.findMember(new Path(containerName));
112     if (!resource.exists() || !(resource instanceof IContainer)) {
113       throwCoreException(PHPWizardMessages.getString("Wizard.Monitor.containerDoesNotExistException"));
114     }
115     IContainer container = (IContainer) resource;
116     final IFile file = container.getFile(new Path(fileName));
117     IProject project = file.getProject();
118     String projectName = project.getName();
119     String className = getClassName(fileName);
120
121     try {
122       InputStream stream;
123       if (className == null) {
124         stream = openContentStream(fileName, projectName);
125       } else {
126         stream = openContentStreamClass(className);
127       }
128       if (file.exists()) {
129         file.setContents(stream, true, true, monitor);
130       } else {
131         file.create(stream, true, monitor);
132       }
133       stream.close();
134     } catch (IOException e) {
135     }
136     monitor.worked(1);
137     monitor.setTaskName(PHPWizardMessages.getString("Wizard.Monitor.openingFile"));
138     getShell().getDisplay().asyncExec(new Runnable() {
139       public void run() {
140         IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
141         try {
142           IDE.openEditor(page, file, true);
143         } catch (PartInitException e) {
144         }
145       }
146     });
147     monitor.worked(1);
148   }
149
150   /**
151    * Check if the filename is like this anyname.class.php
152    *
153    * @param fFileName
154    *          the filename
155    * @return the anyname or null
156    */
157   private static final String getClassName(final String fileName) {
158     final int lastDot = fileName.lastIndexOf('.');
159     if (lastDot == -1)
160       return null;
161     final int precLastDot = fileName.lastIndexOf('.', lastDot - 1);
162     if (precLastDot == -1)
163       return null;
164     if (!fileName.substring(precLastDot + 1, lastDot).toUpperCase().equals("CLASS"))
165       return null;
166     return fileName.substring(0, precLastDot);
167   }
168
169   /**
170    * We will initialize file contents for a class
171    *
172    * @param className
173    *          the classname
174    */
175   private InputStream openContentStreamClass(final String className) {
176     StringBuffer contents = new StringBuffer("<?php\n\n");
177     contents.append("class ");
178     contents.append(className);
179     contents.append(" {\n\n");
180     contents.append("    function ");
181     contents.append(className);
182     contents.append("() {\n");
183     contents.append("    }\n}\n?>");
184     return new ByteArrayInputStream(contents.toString().getBytes());
185   }
186
187   /**
188    * We will initialize file contents with a sample text.
189    */
190   private InputStream openContentStream(String fileName, String projectname) {
191     try {
192       Template template = PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWTYPE);
193       if (template == null) {
194         return null;
195       }
196       String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
197       CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), null, lineDelimiter);
198       context.setFileNameVariable(fileName, projectname);
199       String content=StubUtility.evaluateTemplate(context, template);
200       if (content==null) {
201           content="";
202       }
203       return new ByteArrayInputStream(content.getBytes());
204     } catch (CoreException e) {
205       e.printStackTrace();
206       return null;
207     }
208
209   }
210
211   private void throwCoreException(String message) throws CoreException {
212     IStatus status = new Status(IStatus.ERROR, "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null);
213     throw new CoreException(status);
214   }
215
216   /**
217    * We will accept the selection in the workbench to see if we can initialize from it.
218    *
219    * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
220    */
221   public void init(IWorkbench workbench, IStructuredSelection selection) {
222     this.selection = selection;
223   }
224
225 }