KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > emf > ecore > presentation > EcoreModelWizard


1 /**
2  * <copyright>
3  * </copyright>
4  *
5  * $Id: EcoreModelWizard.java,v 1.11 2005/06/08 12:34:41 marcelop Exp $
6  */

7 package org.eclipse.emf.ecore.presentation;
8
9
10 import java.util.ArrayList JavaDoc;
11 import java.util.Collection JavaDoc;
12 import java.util.Collections JavaDoc;
13 import java.util.HashMap JavaDoc;
14 import java.util.Iterator JavaDoc;
15 import java.util.List JavaDoc;
16 import java.util.Map JavaDoc;
17 import java.util.MissingResourceException JavaDoc;
18 import java.util.StringTokenizer JavaDoc;
19
20 import org.eclipse.core.resources.IContainer;
21 import org.eclipse.core.resources.IFile;
22 import org.eclipse.core.resources.IFolder;
23 import org.eclipse.core.resources.IProject;
24 import org.eclipse.core.resources.IResource;
25 import org.eclipse.core.resources.ResourcesPlugin;
26 import org.eclipse.core.runtime.IProgressMonitor;
27 import org.eclipse.core.runtime.Path;
28 import org.eclipse.jface.dialogs.MessageDialog;
29 import org.eclipse.jface.viewers.ISelection;
30 import org.eclipse.jface.viewers.IStructuredSelection;
31 import org.eclipse.jface.viewers.StructuredSelection;
32 import org.eclipse.jface.wizard.Wizard;
33 import org.eclipse.jface.wizard.WizardPage;
34 import org.eclipse.swt.SWT;
35 import org.eclipse.swt.events.ModifyListener;
36 import org.eclipse.swt.events.ModifyEvent;
37
38 import org.eclipse.swt.layout.GridData;
39 import org.eclipse.swt.layout.GridLayout;
40 import org.eclipse.swt.widgets.Composite;
41 import org.eclipse.swt.widgets.Combo;
42 import org.eclipse.swt.widgets.Label;
43 import org.eclipse.ui.INewWizard;
44 import org.eclipse.ui.IWorkbench;
45 import org.eclipse.ui.IWorkbenchPage;
46 import org.eclipse.ui.IWorkbenchPart;
47 import org.eclipse.ui.IWorkbenchWindow;
48 import org.eclipse.ui.PartInitException;
49 import org.eclipse.ui.actions.WorkspaceModifyOperation;
50 import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
51 import org.eclipse.ui.part.FileEditorInput;
52 import org.eclipse.ui.part.ISetSelectionTarget;
53
54 import org.eclipse.emf.common.util.URI;
55 import org.eclipse.emf.ecore.EClass;
56 import org.eclipse.emf.ecore.EClassifier;
57 import org.eclipse.emf.ecore.EObject;
58 import org.eclipse.emf.ecore.EcoreFactory;
59 import org.eclipse.emf.ecore.EcorePackage;
60 import org.eclipse.emf.ecore.plugin.EcorePlugin;
61 import org.eclipse.emf.ecore.provider.EcoreEditPlugin;
62
63
64 import org.eclipse.emf.ecore.resource.Resource;
65 import org.eclipse.emf.ecore.resource.ResourceSet;
66 import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
67 import org.eclipse.emf.ecore.xmi.XMLResource;
68 import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;
69
70
71 /**
72  * This is a simple wizard for creating a new model file.
73  * <!-- begin-user-doc -->
74  * <!-- end-user-doc -->
75  * @generated
76  */

77 public class EcoreModelWizard extends Wizard implements INewWizard
78 {
79   /**
80    * This caches an instance of the model package.
81    * <!-- begin-user-doc -->
82    * <!-- end-user-doc -->
83    * @generated
84    */

85   protected EcorePackage ecorePackage = EcorePackage.eINSTANCE;
86
87   /**
88    * This caches an instance of the model factory.
89    * <!-- begin-user-doc -->
90    * <!-- end-user-doc -->
91    * @generated
92    */

93   protected EcoreFactory ecoreFactory = ecorePackage.getEcoreFactory();
94
95   /**
96    * This is the file creation page.
97    * <!-- begin-user-doc -->
98    * <!-- end-user-doc -->
99    * @generated
100    */

101   protected EcoreModelWizardNewFileCreationPage newFileCreationPage;
102
103   /**
104    * This is the initial object creation page.
105    * <!-- begin-user-doc -->
106    * <!-- end-user-doc -->
107    * @generated
108    */

109   protected EcoreModelWizardInitialObjectCreationPage initialObjectCreationPage;
110
111   /**
112    * Remember the selection during initialization for populating the default container.
113    * <!-- begin-user-doc -->
114    * <!-- end-user-doc -->
115    * @generated
116    */

117   protected IStructuredSelection selection;
118
119   /**
120    * Remember the workbench during initialization.
121    * <!-- begin-user-doc -->
122    * <!-- end-user-doc -->
123    * @generated
124    */

125   protected IWorkbench workbench;
126
127   /**
128    * Caches the names of the types that can be created as the root object.
129    * <!-- begin-user-doc -->
130    * <!-- end-user-doc -->
131    * @generated
132    */

133   protected List JavaDoc initialObjectNames;
134
135   /**
136    * This just records the information.
137    * <!-- begin-user-doc -->
138    * <!-- end-user-doc -->
139    * @generated
140    */

141   public void init(IWorkbench workbench, IStructuredSelection selection)
142   {
143     this.workbench = workbench;
144     this.selection = selection;
145     setWindowTitle(EcoreEditorPlugin.INSTANCE.getString("_UI_Wizard_label"));
146     setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE.getImageDescriptor(EcoreEditorPlugin.INSTANCE.getImage("full/wizban/NewEcore")));
147   }
148
149   /**
150    * Returns the names of the types that can be created as the root object.
151    * <!-- begin-user-doc -->
152    * <!-- end-user-doc -->
153    * @generated
154    */

155   protected Collection JavaDoc getInitialObjectNames()
156   {
157     if (initialObjectNames == null)
158     {
159       initialObjectNames = new ArrayList JavaDoc();
160       for (Iterator JavaDoc classifiers = ecorePackage.getEClassifiers().iterator(); classifiers.hasNext(); )
161       {
162         EClassifier eClassifier = (EClassifier)classifiers.next();
163         if (eClassifier instanceof EClass)
164         {
165           EClass eClass = (EClass)eClassifier;
166           if (!eClass.isAbstract())
167           {
168             initialObjectNames.add(eClass.getName());
169           }
170         }
171       }
172       Collections.sort(initialObjectNames, java.text.Collator.getInstance());
173     }
174     return initialObjectNames;
175   }
176
177   /**
178    * Create a new model.
179    * <!-- begin-user-doc -->
180    * <!-- end-user-doc -->
181    * @generated
182    */

183   protected EObject createInitialModel()
184   {
185     EClass eClass = (EClass)ecorePackage.getEClassifier(initialObjectCreationPage.getInitialObjectName());
186     EObject rootObject = ecoreFactory.create(eClass);
187     return rootObject;
188   }
189
190   /**
191    * Do the work after everything is specified.
192    * <!-- begin-user-doc -->
193    * <!-- end-user-doc -->
194    * @generated NOT
195    */

196   public boolean performFinish()
197   {
198     try
199     {
200       // Remember the file.
201
//
202
final IFile modelFile = getModelFile();
203
204       // Do the work within an operation.
205
//
206
WorkspaceModifyOperation operation =
207         new WorkspaceModifyOperation()
208         {
209           protected void execute(IProgressMonitor progressMonitor)
210           {
211             try
212             {
213               // Create a resource set
214
//
215
ResourceSet resourceSet = new ResourceSetImpl();
216               resourceSet.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap());
217
218               // Get the URI of the model file.
219
//
220
URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString());
221
222               // Create a resource for this file.
223
//
224
Resource resource = resourceSet.createResource(fileURI);
225
226               // Add the initial model object to the contents.
227
//
228
EObject rootObject = createInitialModel();
229               if (rootObject != null)
230               {
231                 resource.getContents().add(rootObject);
232               }
233
234               // Save the contents of the resource to the file system.
235
//
236
Map JavaDoc options = new HashMap JavaDoc();
237               options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding());
238               resource.save(options);
239             }
240             catch (Exception JavaDoc exception)
241             {
242               EcoreEditorPlugin.INSTANCE.log(exception);
243             }
244             finally
245             {
246               progressMonitor.done();
247             }
248           }
249         };
250
251       getContainer().run(false, false, operation);
252
253       // Select the new file resource in the current view.
254
//
255
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
256       IWorkbenchPage page = workbenchWindow.getActivePage();
257       final IWorkbenchPart activePart = page.getActivePart();
258       if (activePart instanceof ISetSelectionTarget)
259       {
260         final ISelection targetSelection = new StructuredSelection(modelFile);
261         getShell().getDisplay().asyncExec
262           (new Runnable JavaDoc()
263            {
264              public void run()
265              {
266                ((ISetSelectionTarget)activePart).selectReveal(targetSelection);
267              }
268            });
269       }
270
271       // Open an editor on the new file.
272
//
273
try
274       {
275         page.openEditor
276           (new FileEditorInput(modelFile),
277            workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());
278       }
279       catch (PartInitException exception)
280       {
281         MessageDialog.openError(workbenchWindow.getShell(), EcoreEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
282         return false;
283       }
284
285       return true;
286     }
287     catch (Exception JavaDoc exception)
288     {
289       EcoreEditorPlugin.INSTANCE.log(exception);
290       return false;
291     }
292   }
293
294   /**
295    * This is the one page of the wizard.
296    * <!-- begin-user-doc -->
297    * <!-- end-user-doc -->
298    * @generated
299    */

300   public class EcoreModelWizardNewFileCreationPage extends WizardNewFileCreationPage
301   {
302     /**
303      * Pass in the selection.
304      * <!-- begin-user-doc -->
305      * <!-- end-user-doc -->
306      * @generated
307      */

308     public EcoreModelWizardNewFileCreationPage(String JavaDoc pageId, IStructuredSelection selection)
309     {
310       super(pageId, selection);
311     }
312
313     /**
314      * The framework calls this to see if the file is correct.
315      * <!-- begin-user-doc -->
316      * <!-- end-user-doc -->
317      * @generated
318      */

319     protected boolean validatePage()
320     {
321       if (super.validatePage())
322       {
323         // Make sure the file ends in ".ecore".
324
//
325
String JavaDoc requiredExt = EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreEditorFilenameExtension");
326         String JavaDoc enteredExt = new Path(getFileName()).getFileExtension();
327         if (enteredExt == null || !enteredExt.equals(requiredExt))
328         {
329           setErrorMessage(EcoreEditorPlugin.INSTANCE.getString("_WARN_FilenameExtension", new Object JavaDoc [] { requiredExt }));
330           return false;
331         }
332         else
333         {
334           return true;
335         }
336       }
337       else
338       {
339         return false;
340       }
341     }
342
343     /**
344      * <!-- begin-user-doc -->
345      * <!-- end-user-doc -->
346      * @generated
347      */

348     public IFile getModelFile()
349     {
350       return ResourcesPlugin.getWorkspace().getRoot().getFile(getContainerFullPath().append(getFileName()));
351     }
352   }
353
354   /**
355    * This is the page where the type of object to create is selected.
356    * <!-- begin-user-doc -->
357    * <!-- end-user-doc -->
358    * @generated
359    */

360   public class EcoreModelWizardInitialObjectCreationPage extends WizardPage
361   {
362     /**
363      * <!-- begin-user-doc -->
364      * <!-- end-user-doc -->
365      * @generated
366      */

367     protected Combo initialObjectField;
368
369     /**
370      * @generated
371      * <!-- begin-user-doc -->
372      * <!-- end-user-doc -->
373      */

374     protected List JavaDoc encodings;
375
376     /**
377      * <!-- begin-user-doc -->
378      * <!-- end-user-doc -->
379      * @generated
380      */

381     protected Combo encodingField;
382
383     /**
384      * Pass in the selection.
385      * <!-- begin-user-doc -->
386      * <!-- end-user-doc -->
387      * @generated
388      */

389     public EcoreModelWizardInitialObjectCreationPage(String JavaDoc pageId)
390     {
391       super(pageId);
392     }
393
394     /**
395      * <!-- begin-user-doc -->
396      * <!-- end-user-doc -->
397      * @generated
398      */

399     public void createControl(Composite parent)
400     {
401       Composite composite = new Composite(parent, SWT.NONE);
402       {
403         GridLayout layout = new GridLayout();
404         layout.numColumns = 1;
405         layout.verticalSpacing = 12;
406         composite.setLayout(layout);
407
408         GridData data = new GridData();
409         data.verticalAlignment = GridData.FILL;
410         data.grabExcessVerticalSpace = true;
411         data.horizontalAlignment = GridData.FILL;
412         composite.setLayoutData(data);
413       }
414
415       Label containerLabel = new Label(composite, SWT.LEFT);
416       {
417         containerLabel.setText(EcoreEditorPlugin.INSTANCE.getString("_UI_ModelObject"));
418
419         GridData data = new GridData();
420         data.horizontalAlignment = GridData.FILL;
421         containerLabel.setLayoutData(data);
422       }
423
424       initialObjectField = new Combo(composite, SWT.BORDER);
425       {
426         GridData data = new GridData();
427         data.horizontalAlignment = GridData.FILL;
428         data.grabExcessHorizontalSpace = true;
429         initialObjectField.setLayoutData(data);
430       }
431
432       for (Iterator JavaDoc i = getInitialObjectNames().iterator(); i.hasNext(); )
433       {
434         initialObjectField.add(getLabel((String JavaDoc)i.next()));
435       }
436
437       if (initialObjectField.getItemCount() == 1)
438       {
439         initialObjectField.select(0);
440       }
441       initialObjectField.addModifyListener(validator);
442
443       Label encodingLabel = new Label(composite, SWT.LEFT);
444       {
445         encodingLabel.setText(EcoreEditorPlugin.INSTANCE.getString("_UI_XMLEncoding"));
446
447         GridData data = new GridData();
448         data.horizontalAlignment = GridData.FILL;
449         encodingLabel.setLayoutData(data);
450       }
451       encodingField = new Combo(composite, SWT.BORDER);
452       {
453         GridData data = new GridData();
454         data.horizontalAlignment = GridData.FILL;
455         data.grabExcessHorizontalSpace = true;
456         encodingField.setLayoutData(data);
457       }
458
459       for (Iterator JavaDoc i = getEncodings().iterator(); i.hasNext(); )
460       {
461         encodingField.add((String JavaDoc)i.next());
462       }
463
464       encodingField.select(0);
465       encodingField.addModifyListener(validator);
466
467       setPageComplete(validatePage());
468       setControl(composite);
469     }
470
471     /**
472      * <!-- begin-user-doc -->
473      * <!-- end-user-doc -->
474      * @generated
475      */

476     protected ModifyListener validator =
477       new ModifyListener()
478       {
479         public void modifyText(ModifyEvent e)
480         {
481           setPageComplete(validatePage());
482         }
483       };
484
485     /**
486      * <!-- begin-user-doc -->
487      * <!-- end-user-doc -->
488      * @generated
489      */

490     protected boolean validatePage()
491     {
492       return getInitialObjectName() != null && getEncodings().contains(encodingField.getText());
493     }
494
495     /**
496      * <!-- begin-user-doc -->
497      * <!-- end-user-doc -->
498      * @generated
499      */

500     public void setVisible(boolean visible)
501     {
502       super.setVisible(visible);
503       if (visible)
504       {
505         if (initialObjectField.getItemCount() == 1)
506         {
507           initialObjectField.clearSelection();
508           encodingField.setFocus();
509         }
510         else
511         {
512           encodingField.clearSelection();
513           initialObjectField.setFocus();
514         }
515       }
516     }
517
518     /**
519      * <!-- begin-user-doc -->
520      * <!-- end-user-doc -->
521      * @generated
522      */

523     public String JavaDoc getInitialObjectName()
524     {
525       String JavaDoc label = initialObjectField.getText();
526
527       for (Iterator JavaDoc i = getInitialObjectNames().iterator(); i.hasNext(); )
528       {
529         String JavaDoc name = (String JavaDoc)i.next();
530         if (getLabel(name).equals(label))
531         {
532           return name;
533         }
534       }
535       return null;
536     }
537
538     /**
539      * <!-- begin-user-doc -->
540      * <!-- end-user-doc -->
541      * @generated
542      */

543     public String JavaDoc getEncoding()
544     {
545       return encodingField.getText();
546     }
547
548     /**
549      * Returns the label for the specified type name.
550      * <!-- begin-user-doc -->
551      * <!-- end-user-doc -->
552      * @generated
553      */

554     protected String JavaDoc getLabel(String JavaDoc typeName)
555     {
556       try
557       {
558         return EcoreEditPlugin.INSTANCE.getString("_UI_" + typeName + "_type");
559       }
560       catch(MissingResourceException JavaDoc mre)
561       {
562         EcoreEditorPlugin.INSTANCE.log(mre);
563       }
564       return typeName;
565     }
566
567     /**
568      * <!-- begin-user-doc -->
569      * <!-- end-user-doc -->
570      * @generated
571      */

572     protected Collection JavaDoc getEncodings()
573     {
574       if (encodings == null)
575       {
576         encodings = new ArrayList JavaDoc();
577         for (StringTokenizer JavaDoc stringTokenizer = new StringTokenizer JavaDoc(EcoreEditorPlugin.INSTANCE.getString("_UI_XMLEncodingChoices")); stringTokenizer.hasMoreTokens(); )
578         {
579           encodings.add(stringTokenizer.nextToken());
580         }
581       }
582       return encodings;
583     }
584   }
585
586   /**
587    * The framework calls this to create the contents of the wizard.
588    * <!-- begin-user-doc -->
589    * <!-- end-user-doc -->
590    * @generated
591    */

592   public void addPages()
593   {
594     // Create a page, set the title, and the initial model file name.
595
//
596
newFileCreationPage = new EcoreModelWizardNewFileCreationPage("Whatever", selection);
597     newFileCreationPage.setTitle(EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreModelWizard_label"));
598     newFileCreationPage.setDescription(EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreModelWizard_description"));
599     newFileCreationPage.setFileName(EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreEditorFilenameDefaultBase") + "." + EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreEditorFilenameExtension"));
600     addPage(newFileCreationPage);
601
602     // Try and get the resource selection to determine a current directory for the file dialog.
603
//
604
if (selection != null && !selection.isEmpty())
605     {
606       // Get the resource...
607
//
608
Object JavaDoc selectedElement = selection.iterator().next();
609       if (selectedElement instanceof IResource)
610       {
611         // Get the resource parent, if its a file.
612
//
613
IResource selectedResource = (IResource)selectedElement;
614         if (selectedResource.getType() == IResource.FILE)
615         {
616           selectedResource = selectedResource.getParent();
617         }
618
619         // This gives us a directory...
620
//
621
if (selectedResource instanceof IFolder || selectedResource instanceof IProject)
622         {
623           // Set this for the container.
624
//
625
newFileCreationPage.setContainerFullPath(selectedResource.getFullPath());
626
627           // Make up a unique new name here.
628
//
629
String JavaDoc defaultModelBaseFilename = EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreEditorFilenameDefaultBase");
630           String JavaDoc defaultModelFilenameExtension = EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreEditorFilenameExtension");
631           String JavaDoc modelFilename = defaultModelBaseFilename + "." + defaultModelFilenameExtension;
632           for (int i = 1; ((IContainer)selectedResource).findMember(modelFilename) != null; ++i)
633           {
634             modelFilename = defaultModelBaseFilename + i + "." + defaultModelFilenameExtension;
635           }
636           newFileCreationPage.setFileName(modelFilename);
637         }
638       }
639     }
640     initialObjectCreationPage = new EcoreModelWizardInitialObjectCreationPage("Whatever2");
641     initialObjectCreationPage.setTitle(EcoreEditorPlugin.INSTANCE.getString("_UI_EcoreModelWizard_label"));
642     initialObjectCreationPage.setDescription(EcoreEditorPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description"));
643     addPage(initialObjectCreationPage);
644   }
645
646   /**
647    * Get the file from the page.
648    * <!-- begin-user-doc -->
649    * <!-- end-user-doc -->
650    * @generated
651    */

652   public IFile getModelFile()
653   {
654     return newFileCreationPage.getModelFile();
655   }
656
657 }
658
Popular Tags