Excluded the download cache dir from the clean
[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
63                                 .getString("WizardNewProjectCreationPage.windowTitle"));
64         }
65
66         /**
67          * Adding the page to the wizard.
68          */
69         public void addPages() {
70                 page = new PHPFileWizardPage(selection);
71                 addPage(page);
72         }
73
74         /**
75          * This method is called when 'Finish' button is pressed in the wizard. We
76          * will create an operation and run it using wizard as execution context.
77          */
78         public boolean performFinish() {
79                 final String containerName = page.getContainerName();
80                 final String fileName = page.getFileName();
81                 IRunnableWithProgress op = new IRunnableWithProgress() {
82                         public void run(IProgressMonitor monitor)
83                                         throws InvocationTargetException {
84                                 try {
85                                         doFinish(containerName, fileName, monitor);
86                                 } catch (CoreException e) {
87                                         throw new InvocationTargetException(e);
88                                 } finally {
89                                         monitor.done();
90                                 }
91                         }
92                 };
93                 try {
94                         getContainer().run(true, false, op);
95                 } catch (InterruptedException e) {
96                         return false;
97                 } catch (InvocationTargetException e) {
98                         Throwable realException = e.getTargetException();
99                         MessageDialog.openError(getShell(), PHPWizardMessages
100                                         .getString("Wizard.error"), realException.getMessage());
101                         return false;
102                 }
103                 return true;
104         }
105
106         /**
107          * The worker method. It will find the container, create the file if missing
108          * or just replace its contents, and open the editor on the newly created
109          * file.
110          */
111         private void doFinish(String containerName, String fileName,
112                         IProgressMonitor monitor) throws CoreException {
113                 // create a sample file
114                 monitor.beginTask(PHPWizardMessages
115                                 .getString("Wizard.Monitor.creating")
116                                 + " " + fileName, 2);
117                 IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
118                 IResource resource = root.findMember(new Path(containerName));
119                 if (!resource.exists() || !(resource instanceof IContainer)) {
120                         throwCoreException(PHPWizardMessages
121                                         .getString("Wizard.Monitor.containerDoesNotExistException"));
122                 }
123                 IContainer container = (IContainer) resource;
124                 final IFile file = container.getFile(new Path(fileName));
125                 IProject project = file.getProject();
126                 String projectName = project.getName();
127                 String className = getClassName(fileName);
128
129                 try {
130                         InputStream stream;
131                         if (className == null) {
132                                 stream = openContentStream(fileName, projectName);
133                         } else {
134                                 stream = openContentStreamClass(className);
135                         }
136                         if (file.exists()) {
137                                 file.setContents(stream, true, true, monitor);
138                         } else {
139                                 file.create(stream, true, monitor);
140                         }
141                         stream.close();
142                 } catch (IOException e) {
143                 }
144                 monitor.worked(1);
145                 monitor.setTaskName(PHPWizardMessages
146                                 .getString("Wizard.Monitor.openingFile"));
147                 getShell().getDisplay().asyncExec(new Runnable() {
148                         public void run() {
149                                 IWorkbenchPage page = PlatformUI.getWorkbench()
150                                                 .getActiveWorkbenchWindow().getActivePage();
151                                 try {
152                                         IDE.openEditor(page, file, true);
153                                 } catch (PartInitException e) {
154                                 }
155                         }
156                 });
157                 monitor.worked(1);
158         }
159
160         /**
161          * Check if the filename is like this anyname.class.php
162          * 
163          * @param fFileName
164          *            the filename
165          * @return the anyname or null
166          */
167         private static final String getClassName(final String fileName) {
168                 final int lastDot = fileName.lastIndexOf('.');
169                 if (lastDot == -1)
170                         return null;
171                 final int precLastDot = fileName.lastIndexOf('.', lastDot - 1);
172                 if (precLastDot == -1)
173                         return null;
174                 if (!fileName.substring(precLastDot + 1, lastDot).toUpperCase().equals(
175                                 "CLASS"))
176                         return null;
177                 return fileName.substring(0, precLastDot);
178         }
179
180         /**
181          * We will initialize file contents for a class
182          * 
183          * @param className
184          *            the classname
185          */
186         private InputStream openContentStreamClass(final String className) {
187                 StringBuffer contents = new StringBuffer("<?php\n\n");
188                 contents.append("class ");
189                 contents.append(className);
190                 contents.append(" {\n\n");
191                 contents.append("    function ");
192                 contents.append(className);
193                 contents.append("() {\n");
194                 contents.append("    }\n}\n?>");
195                 return new ByteArrayInputStream(contents.toString().getBytes());
196         }
197
198         /**
199          * We will initialize file contents with a sample text.
200          */
201         private InputStream openContentStream(String fileName, String projectname) {
202                 try {
203                         Template template = PHPeclipsePlugin.getDefault()
204                                         .getCodeTemplateStore().findTemplate(
205                                                         CodeTemplateContextType.NEWTYPE);
206                         if (template == null) {
207                                 return null;
208                         }
209                         String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
210                         CodeTemplateContext context = new CodeTemplateContext(template
211                                         .getContextTypeId(), null, lineDelimiter);
212                         context.setFileNameVariable(fileName, projectname);
213                         String content = StubUtility.evaluateTemplate(context, template);
214                         if (content == null) {
215                                 content = "";
216                         }
217                         return new ByteArrayInputStream(content.getBytes());
218                 } catch (CoreException e) {
219                         e.printStackTrace();
220                         return null;
221                 }
222
223         }
224
225         private void throwCoreException(String message) throws CoreException {
226                 IStatus status = new Status(IStatus.ERROR,
227                                 "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null);
228                 throw new CoreException(status);
229         }
230
231         /**
232          * We will accept the selection in the workbench to see if we can initialize
233          * from it.
234          * 
235          * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
236          */
237         public void init(IWorkbench workbench, IStructuredSelection selection) {
238                 this.selection = selection;
239         }
240
241 }