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