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