source: trunk/src/org/modelica/mdt/NewClassWizard.java @ 19

Last change on this file since 19 was 19, checked in by boris, 19 years ago
  • new modelica class finished
File size: 10.6 KB
Line 
1package org.modelica.mdt;
2
3
4import java.io.ByteArrayInputStream;
5import java.io.IOException;
6import java.io.InputStream;
7import java.lang.reflect.InvocationTargetException;
8import java.util.regex.Pattern;
9
10import org.eclipse.core.resources.IContainer;
11import org.eclipse.core.resources.IFile;
12import org.eclipse.core.resources.IResource;
13import org.eclipse.core.resources.IWorkspaceRoot;
14import org.eclipse.core.resources.ResourcesPlugin;
15import org.eclipse.core.runtime.CoreException;
16import org.eclipse.core.runtime.IPath;
17import org.eclipse.core.runtime.IProgressMonitor;
18import org.eclipse.core.runtime.Path;
19import org.eclipse.jface.dialogs.DialogPage;
20import org.eclipse.jface.dialogs.MessageDialog;
21import org.eclipse.jface.operation.IRunnableWithProgress;
22import org.eclipse.jface.viewers.IStructuredSelection;
23import org.eclipse.jface.wizard.Wizard;
24import org.eclipse.jface.wizard.WizardPage;
25import org.eclipse.swt.SWT;
26import org.eclipse.swt.events.ModifyEvent;
27import org.eclipse.swt.events.ModifyListener;
28import org.eclipse.swt.events.SelectionAdapter;
29import org.eclipse.swt.events.SelectionEvent;
30import org.eclipse.swt.layout.GridData;
31import org.eclipse.swt.layout.GridLayout;
32import org.eclipse.swt.widgets.Combo;
33import org.eclipse.swt.widgets.Composite;
34import org.eclipse.swt.widgets.Label;
35import org.eclipse.swt.widgets.Text;
36import org.eclipse.swt.widgets.Button;
37import org.eclipse.ui.INewWizard;
38import org.eclipse.ui.IWorkbench;
39import org.eclipse.ui.IWorkbenchPage;
40import org.eclipse.ui.PartInitException;
41import org.eclipse.ui.PlatformUI;
42import org.eclipse.ui.dialogs.ContainerSelectionDialog;
43import org.eclipse.ui.ide.IDE;
44
45public class NewClassWizard extends Wizard implements INewWizard
46{
47    public class NewClassPage extends WizardPage
48    {
49        private Text sourceFolder;
50        private Text className;
51        private Combo classType;
52       
53   
54        private IPath selection = null;
55       
56       
57        /* regexp pattern of a valid modelica class name */
58        //TODO add complete regexp for modelcia class name
59        // see modelica specification page 9 (and perhaps some other pages as well)
60        // http://www.modelica.org/documents/ModelicaSpec22.pdf
61        Pattern classNamePattern = Pattern.compile("[a-zA-Z]\\w*");
62       
63        private boolean classNameValid = false;
64        private boolean sourceFolderValid = false;     
65       
66        public NewClassPage()
67        {
68            super("");
69        }
70
71        public void createControl(Composite parent)
72        {
73            setPageComplete(false);
74            /*
75             * configure description of this page
76             */
77            setTitle("Modelica Class");
78            setDescription("Create a new Modelica class.");
79           
80            // TODO set image descriptor           
81            //setImageDescriptor(...);
82           
83            /*
84             * setup widgets for this page
85             */
86            Composite composite= new Composite(parent, SWT.NONE);
87            setControl(composite);
88            composite.setFont(parent.getFont());
89           
90            GridLayout layout = new GridLayout();
91            layout.numColumns = 3;
92            composite.setLayout(layout);
93           
94            GridData gd;
95
96            /* source folder field */
97            Label l = new Label(composite, SWT.LEFT | SWT.WRAP);
98            l.setText("Source folder:");
99            gd = new GridData();
100            gd.horizontalAlignment = GridData.BEGINNING;
101            l.setLayoutData(gd);
102           
103            sourceFolder = new Text(composite,  SWT.SINGLE | SWT.BORDER);
104            gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
105            sourceFolder.setLayoutData(gd);
106            setSourceFolder(selection);
107           
108            sourceFolder.addModifyListener(new ModifyListener()
109            {
110                    /* check if entered path exists */
111                    public void modifyText(ModifyEvent e)
112                    {
113                        sourceFolderChanged();
114                    }
115            });
116
117
118            Button b = new Button(composite, SWT.PUSH);
119            b.setText("Browse...");
120            gd = new GridData();
121            gd.horizontalAlignment = GridData.END;
122            b.setLayoutData(gd);
123            b.addSelectionListener(new SelectionAdapter()
124            {
125                public void widgetSelected(SelectionEvent e)
126                {
127                    handleBrowse();
128                }
129            });
130
131           
132            /* class name field */
133            l = new Label(composite, SWT.LEFT | SWT.WRAP);
134            l.setText("Name:");
135            gd = new GridData();
136            gd.horizontalAlignment = GridData.BEGINNING;
137            l.setLayoutData(gd);
138           
139            className = new Text(composite,  SWT.SINGLE | SWT.BORDER);
140            gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
141            gd.horizontalSpan = 2;
142            className.setLayoutData(gd);
143
144            className.addModifyListener(new ModifyListener()
145            {
146                /* check if entered classname is valid */
147                public void modifyText(ModifyEvent e)
148                {
149                    if (!isLegalClassName(className.getText()))
150                    {
151                        classNameValid  = false;
152                        updateStatus("Class name is not valid. Illegal identifier.",
153                                    DialogPage.WARNING);
154                    }
155                    else
156                    {
157                        classNameValid  = true;
158                        updateStatus(null, DialogPage.NONE);
159                    }
160                }
161            });
162            className.setFocus();
163
164            /* class type field */
165            l = new Label(composite, SWT.LEFT | SWT.WRAP);
166            l.setText("Type:");
167            gd = new GridData();
168            gd.horizontalAlignment = GridData.BEGINNING;
169            l.setLayoutData(gd);
170           
171            classType = new Combo(composite, SWT.READ_ONLY);
172            classType.setItems(new String [] {"class", "model", "connector", "record",
173                    "block", "type", "function"});
174            classType.setVisibleItemCount(7);
175            classType.select(0);
176                   
177            gd = new GridData();
178            gd.horizontalAlignment = GridData.BEGINNING;
179            classType.setLayoutData(gd);
180
181        }
182
183        private void sourceFolderChanged()
184        {
185            IResource container = ResourcesPlugin.getWorkspace().getRoot()
186                    .findMember(new Path(sourceFolder.getText()));
187
188            sourceFolderValid = false;
189            if (sourceFolder.getText().length() == 0) {
190                updateStatus("File container must be specified", DialogPage.ERROR);
191                return;
192            }
193            if (container == null
194                    || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
195                updateStatus("File container must exist", DialogPage.ERROR);
196                return;
197            }
198            if (!container.isAccessible()) {
199                updateStatus("Project must be writable", DialogPage.ERROR);
200                return;
201            }
202            sourceFolderValid = true;
203            updateStatus(null, DialogPage.NONE);
204        }
205
206        /**
207         * @return true if name is a valid modelica class name
208         */
209        protected boolean isLegalClassName(String name)
210        {
211            return classNamePattern.matcher(name).matches();
212        }
213
214        public void init(IStructuredSelection selection)
215        {
216            if (selection == null || selection.size() != 1)
217            {
218                return;
219            }
220            if (!(selection.getFirstElement() instanceof IResource))
221            {
222                return;
223            }
224           
225            /*
226             * now we know that a single element of type IResource is selected
227             */
228            IResource sel = (IResource) selection.getFirstElement();
229
230            this.selection = sel.getFullPath();
231            if (sel.getType() == IResource.FILE)
232            {
233                this.selection = this.selection.removeLastSegments(1);
234            }
235        }
236       
237        private void handleBrowse()
238        {
239            ContainerSelectionDialog dialog =
240                new ContainerSelectionDialog(
241                    getShell(), ResourcesPlugin.getWorkspace().getRoot(), false,
242                    "Choose a source folder:");
243           
244            if (dialog.open() == ContainerSelectionDialog.OK)
245            {
246                Object[] result = dialog.getResult();
247                if (result.length == 1)
248                {
249                    setSourceFolder((IPath) result[0]);
250                }
251            }
252        }
253       
254        private void updateStatus(String message, int messageType)
255        {
256            setMessage(message, messageType);
257            setPageComplete((classNameValid && sourceFolderValid));
258        }
259
260
261        public void setSourceFolder(IPath path)
262        {
263            if (path != null)
264            {               
265                sourceFolder.setText(path.makeRelative().toString());
266                setPageComplete(isPageComplete());
267                sourceFolderValid = true;
268            }                       
269        }
270
271    }
272
273
274    private NewClassPage classPage = new NewClassPage();
275
276    public NewClassWizard()
277    {
278        super();
279    }
280
281    @Override
282    public boolean performFinish()
283    {
284        final String sourceFolder = classPage.sourceFolder.getText();
285        final String className = classPage.className.getText();
286        final String classType = classPage.classType.getText();
287       
288        IRunnableWithProgress op = new IRunnableWithProgress() {
289            public void run(IProgressMonitor monitor) 
290                                throws InvocationTargetException
291             {
292                try 
293                {
294                    doFinish(sourceFolder, className, classType, monitor);
295                } 
296                catch (CoreException e)
297                {
298                    throw new InvocationTargetException(e);
299                }
300                finally 
301                {
302                    monitor.done();
303                }
304            }
305        };
306        try {
307            getContainer().run(true, false, op);
308        } catch (InterruptedException e) {
309            return false;
310        } catch (InvocationTargetException e) {
311            Throwable realException = e.getTargetException();
312            MessageDialog.openError(getShell(), "Error", realException.getMessage());
313            return false;
314        }
315        return true;
316    }
317
318    protected void doFinish(String sourceFolder, String className, 
319            String classType, IProgressMonitor monitor)
320    throws CoreException
321    {
322        // create a sample file
323        monitor.beginTask("Creating " + className, 2);
324       
325        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
326        IResource resource = root.findMember(new Path(sourceFolder));
327       
328        IContainer container = (IContainer) resource;
329       
330        final IFile file = container.getFile(new Path(className+".mo"));
331        String contents = 
332            classType + " " + className + "\n\n" +
333            (classType.equals("record") ? "" : "equation\n\n" ) + 
334            "end " + className + ";";
335       
336        try {
337            InputStream stream = new ByteArrayInputStream(contents.getBytes());
338            if (file.exists()) {
339                file.appendContents(stream, true, true, monitor);
340            } else {
341                file.create(stream, true, monitor);
342            }
343            stream.close();
344        } catch (IOException e) {
345        }
346        monitor.worked(1);
347        monitor.setTaskName("Opening file for editing...");
348        getShell().getDisplay().asyncExec(new Runnable() {
349            public void run() {
350                IWorkbenchPage page =
351                    PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
352                try {
353                    IDE.openEditor(page, file, true);
354                } catch (PartInitException e) {
355                }
356            }
357        });
358        monitor.worked(1);
359
360    }
361
362    public void init(IWorkbench workbench, IStructuredSelection selection)
363    {
364        classPage.init(selection);
365        setWindowTitle("New Modelica Class");
366    }
367
368    @Override
369    public void addPages()
370    {
371        addPage(classPage);
372    }
373}
Note: See TracBrowser for help on using the repository browser.