b3b14f820123c7fc2c3dce9592e083ebda3bd1ac
[phpeclipse.git] / net.sourceforge.phpeclipse / src / com / xaraya / wizard / XarayaModuleContainerPage.java
1 package com.xaraya.wizard;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.InputStream;
5 import java.io.PipedInputStream;
6 import java.io.PipedOutputStream;
7 import java.io.PrintStream;
8 import java.util.ArrayList;
9 import java.util.Iterator;
10 import java.util.StringTokenizer;
11
12 import net.sourceforge.phpdt.internal.ui.util.StringUtil;
13
14 import org.eclipse.core.resources.IContainer;
15 import org.eclipse.core.resources.IFile;
16 import org.eclipse.core.resources.IFolder;
17 import org.eclipse.core.resources.IResource;
18 import org.eclipse.core.resources.IResourceStatus;
19 import org.eclipse.core.resources.IWorkspace;
20 import org.eclipse.core.runtime.CoreException;
21 import org.eclipse.core.runtime.IAdaptable;
22 import org.eclipse.core.runtime.IPath;
23 import org.eclipse.core.runtime.IProgressMonitor;
24 import org.eclipse.core.runtime.IStatus;
25 import org.eclipse.core.runtime.OperationCanceledException;
26 import org.eclipse.core.runtime.SubProgressMonitor;
27 import org.eclipse.jface.viewers.IStructuredSelection;
28 import org.eclipse.jface.wizard.WizardPage;
29 import org.eclipse.swt.SWT;
30 import org.eclipse.swt.layout.GridData;
31 import org.eclipse.swt.layout.GridLayout;
32 import org.eclipse.swt.widgets.Composite;
33 import org.eclipse.swt.widgets.Event;
34 import org.eclipse.swt.widgets.Listener;
35 import org.eclipse.ui.actions.WorkspaceModifyOperation;
36 import org.eclipse.ui.dialogs.ContainerGenerator;
37 import org.eclipse.ui.help.WorkbenchHelp;
38 import org.eclipse.ui.internal.IHelpContextIds;
39 import org.eclipse.ui.internal.WorkbenchMessages;
40 import org.eclipse.ui.internal.WorkbenchPlugin;
41 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
42 import org.eclipse.ui.internal.ide.misc.ResourceAndContainerGroup;
43
44 public class XarayaModuleContainerPage extends WizardPage implements Listener {
45         private static final int SIZING_CONTAINER_GROUP_HEIGHT = 250;
46         private IStructuredSelection currentSelection;
47         private IContainer currentParent;
48         NewXarayaResourceWizard wizard;
49         private IPath newModulePath;
50         private IFolder newModule;
51         
52         // widgets
53         private ResourceAndContainerGroup resourceGroup;
54
55 public XarayaModuleContainerPage(String pageName, IStructuredSelection selection) {
56         super(XarayaModuleMessages.getString("Xaraya.label.container"));
57         setTitle(pageName);
58         setDescription(XarayaModuleMessages.getString("Xaraya.label.container")); 
59         this.currentSelection = selection;
60 }
61
62 public void createControl(Composite parent) {
63         initializeDialogUnits(parent);
64         // top level group
65         Composite composite = new Composite(parent,SWT.NONE);
66         composite.setFont(parent.getFont());
67         composite.setLayout(new GridLayout());
68         composite.setLayoutData(new GridData(
69                 GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
70
71         WorkbenchHelp.setHelp(composite, IHelpContextIds.NEW_FOLDER_WIZARD_PAGE);
72
73         resourceGroup = new ResourceAndContainerGroup(composite,this,
74                 XarayaModuleMessages.getString("Xaraya.label.container"),
75                 XarayaModuleMessages.getString("Xaraya.label.modversionname"),
76                         false, SIZING_CONTAINER_GROUP_HEIGHT); //$NON-NLS-2$ //$NON-NLS-1$
77         resourceGroup.setAllowExistingResources(false);
78         initializePage();
79         validatePage();
80         // Show description on opening
81         setErrorMessage(null);
82         setMessage(null);
83         setControl(composite);
84 }
85
86 protected void createFolder(IFolder folderHandle, IProgressMonitor monitor) throws CoreException {
87     try {
88         // Create the folder resource in the workspace
89         // Update: Recursive to create any folders which do not exist already
90         if (!folderHandle.exists()) {
91             IContainer parent= folderHandle.getParent();
92             if (parent instanceof IFolder && (!((IFolder)parent).exists())) {
93                 createFolder((IFolder)parent, monitor);
94             }
95                         folderHandle.create(false, true, monitor);
96         }
97     }
98     catch (CoreException e) {
99         // If the folder already existed locally, just refresh to get contents
100         if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
101             folderHandle.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 500));
102         else
103             throw e;
104     }
105
106     if (monitor.isCanceled())
107         throw new OperationCanceledException();
108 }
109
110 protected IFolder createFolderHandle(IPath folderPath) {
111         return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(folderPath);
112 }
113
114 public IFolder createNewModuleFolder() {
115         if (newModule != null)
116                 return newModule;
117
118         // create the new folder and cache it if successful
119         final IPath containerPath = resourceGroup.getContainerFullPath();
120         newModulePath = containerPath.append(resourceGroup.getResource());
121         final IFolder newModuleHandle = createFolderHandle(newModulePath);
122
123         WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
124                 public void execute(IProgressMonitor monitor) throws CoreException {
125                         try {
126                                 monitor.beginTask(WorkbenchMessages.getString("WizardNewFolderCreationPage.progress"), 2000); //$NON-NLS-1$
127                                 ContainerGenerator generator = new ContainerGenerator(containerPath);
128                                 generator.generateContainer(new SubProgressMonitor(monitor, 1000));
129                                 createFolder(newModuleHandle, new SubProgressMonitor(monitor, 1000));
130                         } finally {
131                                 monitor.done();
132                         }
133                 }
134         };
135
136         try {
137                 getContainer().run(true, true, op);
138         } catch (Exception e) {
139                 return null;
140         }
141         newModule = newModuleHandle;
142         return newModule;
143 }
144
145 public boolean createNewGuiFolder() {
146         final IPath containerPath = newModulePath;
147         IPath newFolderPath = containerPath.append(XarayaModuleMessages.getString("Xaraya.folder.gui"));
148         final IFolder newFolderHandle = createFolderHandle(newFolderPath);
149
150         WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
151                 public void execute(IProgressMonitor monitor) throws CoreException {
152                         try {
153                                 monitor.beginTask(WorkbenchMessages.getString("WizardNewFolderCreationPage.progress"), 2000); //$NON-NLS-1$
154                                 ContainerGenerator generator = new ContainerGenerator(containerPath);
155                                 generator.generateContainer(new SubProgressMonitor(monitor, 1000));
156                                 createFolder(newFolderHandle, new SubProgressMonitor(monitor, 1000));
157                         } finally {
158                                 monitor.done();
159                         }
160                 }
161         };
162
163         try {
164                 getContainer().run(true, true, op);
165         } catch (Exception e) {
166                 return false;
167         } 
168         return true;
169 }
170
171 protected void createFile(IFile fileHandle, InputStream contents, IProgressMonitor monitor) throws CoreException {
172         if (contents == null)
173                 contents = new ByteArrayInputStream(new byte[0]);
174
175         try {
176                         fileHandle.create(contents, false, monitor);
177         }
178         catch (CoreException e) {
179                 // If the file already existed locally, just refresh to get contents
180                 if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
181                         fileHandle.refreshLocal(IResource.DEPTH_ZERO, null);
182                 else
183                         throw e;
184         }
185
186         if (monitor.isCanceled())
187                 throw new OperationCanceledException();
188 }
189
190 protected IFile createFileHandle(IPath filePath) {
191         return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFile(filePath);
192 }
193
194 public Object[] createNewModuleFiles(){
195         ArrayList fileAL = new ArrayList();
196         boolean isGuiDirCreated = false;
197         fileAL.add(createNewFile(XarayaModuleMessages.getString("Xaraya.files.init")));
198         fileAL.add(createNewFile(XarayaModuleMessages.getString("Xaraya.files.version")));
199         if (XarayaVersionModel.isAdminApi()) fileAL.add(createNewFile(XarayaModuleMessages.getString("Xaraya.files.adminApi"))); 
200         if (XarayaVersionModel.isAdminGui()) {
201                 fileAL.add(createNewFile(XarayaModuleMessages.getString("Xaraya.files.adminGui")));
202                 isGuiDirCreated=createNewGuiFolder();
203         }  
204         if (XarayaVersionModel.isUserApi()) fileAL.add(createNewFile(XarayaModuleMessages.getString("Xaraya.files.userApi")));  
205         if (XarayaVersionModel.isUserGui()) {
206                 fileAL.add(createNewFile(XarayaModuleMessages.getString("Xaraya.files.userGui")));
207                 if (!isGuiDirCreated) isGuiDirCreated=createNewGuiFolder();     
208         } 
209         return fileAL.toArray();
210 }
211
212 public IFile createNewFile(String fileName) {
213         final IPath containerPath = newModulePath;
214         IPath newFilePath = containerPath.append(fileName);
215         final IFile newFileHandle = createFileHandle(newFilePath);
216         final InputStream initialContents = getInitialContents(fileName);
217         WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
218                 protected void execute(IProgressMonitor monitor) throws CoreException,
219                         InterruptedException
220                 {
221                         try {
222                                 monitor.beginTask("Progress", 2000); //$NON-NLS-1$
223                                 ContainerGenerator generator = new ContainerGenerator(containerPath);
224                                 generator.generateContainer(new SubProgressMonitor(monitor, 1000));
225                                 createFile(newFileHandle,initialContents, new SubProgressMonitor(monitor, 1000));
226                         } finally {
227                                 monitor.done();
228                         }
229                 }
230         };
231
232         try {
233                 getContainer().run(true, true, op);
234         } catch (Exception e) {
235                 return null;
236         } 
237         return newFileHandle;
238 }
239
240         protected InputStream getInitialContents(String fileName) {
241                 StringBuffer inputString = new StringBuffer();
242                 if (fileName.equals(XarayaModuleMessages.getString("Xaraya.files.init"))) 
243                         inputString=XarayaModuleText.xarinit;
244                 if (fileName.equals(XarayaModuleMessages.getString("Xaraya.files.adminGui"))) 
245                         inputString=XarayaModuleText.xaradmin;
246                 if (fileName.equals(XarayaModuleMessages.getString("Xaraya.files.adminApi"))) 
247                         inputString=XarayaModuleText.xaradminapi;
248                 if (fileName.equals(XarayaModuleMessages.getString("Xaraya.files.userGui"))) 
249                         inputString=XarayaModuleText.xaruser;
250                 if (fileName.equals(XarayaModuleMessages.getString("Xaraya.files.userApi"))) 
251                         inputString=XarayaModuleText.xaruserapi;
252                 if (fileName.equals(XarayaModuleMessages.getString("Xaraya.files.version"))) 
253                         inputString=XarayaModuleText.xarversion;
254                 
255                 ArrayList inserts = new ArrayList();
256                 //makes things simpler to just refer to the arraylist...
257                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.name"));
258                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.id"));
259                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.version"));
260                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.description"));
261                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.official"));
262                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.author"));
263                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.contact"));
264                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.admin"));
265                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.user"));
266                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.securityschema"));
267                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.class"));
268                 inserts.add(XarayaModuleMessages.getString("Xaraya.insert.category"));
269         
270                 ArrayList names = new ArrayList();
271                 names.add(XarayaVersionModel.getModversionname());
272                 names.add(XarayaVersionModel.getModversionid());
273                 names.add(XarayaVersionModel.getModversionversion());
274                 names.add(XarayaVersionModel.getModversiondescription());
275                 names.add(XarayaVersionModel.getModversionofficial());
276                 names.add(XarayaVersionModel.getModversionauthor());
277                 names.add(XarayaVersionModel.getModversioncontact());
278                 names.add(XarayaVersionModel.getModversionadmin());
279                 names.add(XarayaVersionModel.getModversionuser());
280                 names.add(XarayaVersionModel.getModversionsecurityschema());
281                 names.add(XarayaVersionModel.getModversionclass());
282                 names.add(XarayaVersionModel.getModversioncategory());
283                 
284                 PipedOutputStream ps = null;
285                 PipedInputStream is = null;
286                 String buffer = inputString.toString();         
287                 for (int i=0; i<inserts.size(); i++)
288                 {
289                         String insert = (String)inserts.get(i);
290                         String replace = (String)names.get(i);
291         
292       buffer = StringUtil.replaceAll(buffer, insert, replace.toLowerCase());
293                         try {
294                                 ps = new PipedOutputStream();
295                                 is = new PipedInputStream(ps);
296                                 PrintStream os = new PrintStream(ps);
297                                 os.println(buffer);
298                                 os.close();
299                         } catch (Exception e) {
300                                 System.out.println("writing to file:"+fileName +"failed with:"+ e);
301                         }
302                 }
303                 return is;
304         }
305         
306
307 public void handleEvent(Event ev) {
308         setPageComplete(validatePage());
309 }
310
311 public boolean canFlipToNextPage() {
312         return isPageComplete();
313 }
314
315 protected void initializePage() {
316         Iterator enum = currentSelection.iterator();
317         if (enum.hasNext()) {
318                 Object next = enum.next();
319                 IResource selectedResource = null;
320                 if (next instanceof IResource) {
321                         selectedResource = (IResource)next;
322                 } else if (next instanceof IAdaptable) {
323                         selectedResource = (IResource)((IAdaptable)next).getAdapter(IResource.class);
324                 }
325                 if (selectedResource != null) {
326                         if (selectedResource.getType() == IResource.FILE)
327                                 selectedResource = selectedResource.getParent();
328                         if (selectedResource.isAccessible())
329                                 resourceGroup.setContainerFullPath(selectedResource.getFullPath());
330                 }
331         }
332         setPageComplete(false);
333 }
334
335 public void setVisible(boolean visible) {
336         super.setVisible(visible);
337         if(visible)
338                 resourceGroup.setFocus();
339 }
340
341 protected boolean validatePage() {
342         boolean valid = true;
343         String moduleName = new String();
344         IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
345     IStatus nameStatus = null;
346     String folderName = resourceGroup.getResource();
347     moduleName = folderName;
348     if (folderName.indexOf(IPath.SEPARATOR) != -1) {
349         StringTokenizer tok = new StringTokenizer(folderName, String.valueOf(IPath.SEPARATOR));
350         while (tok.hasMoreTokens()) {
351             String pathFragment = tok.nextToken();
352             nameStatus = workspace.validateName(pathFragment, IResource.FOLDER);
353             if (!nameStatus.isOK()) {
354                 break;
355             }
356                 }
357     }
358         //If the name status was not set validate using the name
359         if(nameStatus == null && folderName.length() > 0)
360         nameStatus = workspace.validateName(folderName, IResource.FOLDER);
361     if (nameStatus != null && !nameStatus.isOK()) {
362         setErrorMessage(nameStatus.getMessage());
363         return false;
364     }
365
366         if (!resourceGroup.areAllValuesValid()) {
367                 // if blank name then fail silently
368                 if (resourceGroup.getProblemType() == ResourceAndContainerGroup.PROBLEM_RESOURCE_EMPTY
369                         || resourceGroup.getProblemType() == ResourceAndContainerGroup.PROBLEM_CONTAINER_EMPTY) {
370                         setMessage(resourceGroup.getProblemMessage());
371                         setErrorMessage(null);
372                 } else {
373                         setErrorMessage(resourceGroup.getProblemMessage());
374                 }
375                 valid = false;
376         }
377         if (valid) {
378                 XarayaVersionModel.setModversionname(moduleName);
379                 setErrorMessage(null);
380         } 
381         return valid;
382 }
383
384 }
385