KickJava   Java API By Example, From Geeks To Geeks.

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


1 /**
2  * <copyright>
3  *
4  * Copyright (c) 2002-2004 IBM Corporation and others.
5  * All rights reserved. This program and the accompanying materials
6  * are made available under the terms of the Eclipse Public License v1.0
7  * which accompanies this distribution, and is available at
8  * http://www.eclipse.org/legal/epl-v10.html
9  *
10  * Contributors:
11  * IBM - Initial API and implementation
12  *
13  * </copyright>
14  *
15  * $Id: EcoreEditor.java,v 1.19 2005/06/10 21:02:54 emerks Exp $
16  */

17 package org.eclipse.emf.ecore.presentation;
18
19
20 import java.io.IOException JavaDoc;
21 import java.util.ArrayList JavaDoc;
22 import java.util.Collection JavaDoc;
23 import java.util.Collections JavaDoc;
24 import java.util.EventObject JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28
29 import org.eclipse.core.resources.IFile;
30 import org.eclipse.core.resources.IMarker;
31 import org.eclipse.core.resources.IResource;
32 import org.eclipse.core.resources.IResourceChangeEvent;
33 import org.eclipse.core.resources.IResourceChangeListener;
34 import org.eclipse.core.resources.IResourceDelta;
35 import org.eclipse.core.resources.IResourceDeltaVisitor;
36 import org.eclipse.core.resources.ResourcesPlugin;
37 import org.eclipse.core.runtime.CoreException;
38 import org.eclipse.core.runtime.IPath;
39 import org.eclipse.core.runtime.IProgressMonitor;
40 import org.eclipse.core.runtime.NullProgressMonitor;
41 import org.eclipse.jface.action.IMenuListener;
42 import org.eclipse.jface.action.IMenuManager;
43 import org.eclipse.jface.action.IStatusLineManager;
44 import org.eclipse.jface.action.IToolBarManager;
45 import org.eclipse.jface.action.MenuManager;
46 import org.eclipse.jface.action.Separator;
47 import org.eclipse.jface.dialogs.MessageDialog;
48 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
49 //import org.eclipse.jface.viewers.ColumnWeightData;
50
import org.eclipse.jface.viewers.ISelection;
51 import org.eclipse.jface.viewers.ISelectionChangedListener;
52 import org.eclipse.jface.viewers.ISelectionProvider;
53 import org.eclipse.jface.viewers.IStructuredSelection;
54 import org.eclipse.jface.viewers.ListViewer;
55 import org.eclipse.jface.viewers.SelectionChangedEvent;
56 import org.eclipse.jface.viewers.StructuredSelection;
57 import org.eclipse.jface.viewers.StructuredViewer;
58 //import org.eclipse.jface.viewers.TableLayout;
59
import org.eclipse.jface.viewers.TableViewer;
60 import org.eclipse.jface.viewers.TreeViewer;
61 import org.eclipse.jface.viewers.Viewer;
62 import org.eclipse.swt.SWT;
63 import org.eclipse.swt.custom.CTabFolder;
64 import org.eclipse.swt.dnd.DND;
65 import org.eclipse.swt.dnd.Transfer;
66 import org.eclipse.swt.events.ControlAdapter;
67 import org.eclipse.swt.events.ControlEvent;
68 import org.eclipse.swt.graphics.Point;
69 //import org.eclipse.swt.layout.FillLayout;
70

71 import org.eclipse.swt.widgets.Composite;
72 import org.eclipse.swt.widgets.Control;
73 import org.eclipse.swt.widgets.Menu;
74 //import org.eclipse.swt.widgets.Table;
75
//import org.eclipse.swt.widgets.TableColumn;
76
import org.eclipse.swt.widgets.Tree;
77 //import org.eclipse.swt.widgets.TreeColumn;
78

79 import org.eclipse.ui.IActionBars;
80 import org.eclipse.ui.IEditorInput;
81 import org.eclipse.ui.IEditorPart;
82 import org.eclipse.ui.IEditorSite;
83 import org.eclipse.ui.IFileEditorInput;
84 import org.eclipse.ui.IPartListener;
85 import org.eclipse.ui.IWorkbenchPart;
86 import org.eclipse.ui.PartInitException;
87 import org.eclipse.ui.actions.WorkspaceModifyOperation;
88 import org.eclipse.ui.dialogs.SaveAsDialog;
89 import org.eclipse.ui.ide.IGotoMarker;
90 import org.eclipse.ui.part.FileEditorInput;
91 import org.eclipse.ui.part.MultiPageEditorPart;
92 import org.eclipse.ui.views.contentoutline.ContentOutline;
93 import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
94 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
95 import org.eclipse.ui.views.properties.IPropertySheetPage;
96 import org.eclipse.ui.views.properties.PropertySheet;
97 import org.eclipse.ui.views.properties.PropertySheetPage;
98
99 import org.eclipse.emf.common.CommonPlugin;
100 import org.eclipse.emf.common.command.BasicCommandStack;
101 import org.eclipse.emf.common.command.Command;
102 import org.eclipse.emf.common.command.CommandStack;
103 import org.eclipse.emf.common.command.CommandStackListener;
104 import org.eclipse.emf.common.notify.AdapterFactory;
105 import org.eclipse.emf.common.ui.ViewerPane;
106 import org.eclipse.emf.common.ui.viewer.IViewerProvider;
107 import org.eclipse.emf.common.util.URI;
108 import org.eclipse.emf.ecore.EObject;
109 import org.eclipse.emf.ecore.EValidator;
110 import org.eclipse.emf.ecore.plugin.EcorePlugin;
111 import org.eclipse.emf.ecore.provider.EcoreItemProviderAdapterFactory;
112 import org.eclipse.emf.ecore.resource.Resource;
113 import org.eclipse.emf.ecore.resource.ResourceSet;
114 import org.eclipse.emf.ecore.xmi.impl.GenericXMLResourceFactoryImpl;
115 import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
116 import org.eclipse.emf.edit.domain.EditingDomain;
117 import org.eclipse.emf.edit.domain.IEditingDomainProvider;
118 import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
119 import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
120 import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
121 import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
122 import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
123 import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor;
124 import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter;
125 import org.eclipse.emf.edit.ui.dnd.LocalTransfer;
126 import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter;
127 import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
128 import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
129
130
131 /**
132  * This is an example of a Ecore model editor.
133  * <!-- begin-user-doc -->
134  * <!-- end-user-doc -->
135  * @generated
136  */

137 public class EcoreEditor
138   extends MultiPageEditorPart
139   implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider, IGotoMarker
140 {
141   public static class XML extends EcoreEditor
142   {
143     public XML()
144     {
145       try
146       {
147         editingDomain.getResourceSet().getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new GenericXMLResourceFactoryImpl());
148
149         Class JavaDoc theItemProviderClass = CommonPlugin.loadClass("org.eclipse.xsd.edit", "org.eclipse.xsd.provider.XSDItemProviderAdapterFactory");
150         AdapterFactory xsdItemProviderAdapterFactory = (AdapterFactory)theItemProviderClass.newInstance();
151         adapterFactory.insertAdapterFactory(xsdItemProviderAdapterFactory);
152       }
153       catch (Exception JavaDoc exception)
154       {
155         EcoreEditorPlugin.INSTANCE.log(exception);
156       }
157     }
158     public void createModel()
159     {
160       super.createModel();
161       
162       // Load the schema and packages that were used to load the instance into this resource set.
163
//
164
ResourceSet resourceSet = editingDomain.getResourceSet();
165       Resource resource = (Resource)resourceSet.getResources().get(0);
166       EObject rootObject = (EObject)resource.getContents().get(0);
167       Resource metaDataResource = rootObject.eClass().eResource();
168       if (metaDataResource != null && metaDataResource.getResourceSet() != null)
169       {
170         resourceSet.getResources().addAll(metaDataResource.getResourceSet().getResources());
171       }
172     }
173   }
174
175   /**
176    * This keeps track of the editing domain that is used to track all changes to the model.
177    * <!-- begin-user-doc -->
178    * <!-- end-user-doc -->
179    * @generated
180    */

181   protected AdapterFactoryEditingDomain editingDomain;
182
183   /**
184    * This is the one adapter factory used for providing views of the model.
185    * <!-- begin-user-doc -->
186    * <!-- end-user-doc -->
187    * @generated
188    */

189   protected ComposedAdapterFactory adapterFactory;
190
191   /**
192    * This is the content outline page.
193    * <!-- begin-user-doc -->
194    * <!-- end-user-doc -->
195    * @generated
196    */

197   protected IContentOutlinePage contentOutlinePage;
198
199   /**
200    * This is a kludge...
201    * <!-- begin-user-doc -->
202    * <!-- end-user-doc -->
203    * @generated
204    */

205   protected IStatusLineManager contentOutlineStatusLineManager;
206
207   /**
208    * This is the content outline page's viewer.
209    * <!-- begin-user-doc -->
210    * <!-- end-user-doc -->
211    * @generated
212    */

213   protected TreeViewer contentOutlineViewer;
214
215   /**
216    * This is the property sheet page.
217    * <!-- begin-user-doc -->
218    * <!-- end-user-doc -->
219    * @generated
220    */

221   protected PropertySheetPage propertySheetPage;
222
223   /**
224    * This is the viewer that shadows the selection in the content outline.
225    * The parent relation must be correctly defined for this to work.
226    * <!-- begin-user-doc -->
227    * <!-- end-user-doc -->
228    * @generated
229    */

230   protected TreeViewer selectionViewer;
231
232   /**
233    * This inverts the roll of parent and child in the content provider and show parents as a tree.
234    * <!-- begin-user-doc -->
235    * <!-- end-user-doc -->
236    * @generated
237    */

238   protected TreeViewer parentViewer;
239
240   /**
241    * This shows how a tree view works.
242    * <!-- begin-user-doc -->
243    * <!-- end-user-doc -->
244    * @generated
245    */

246   protected TreeViewer treeViewer;
247
248   /**
249    * This shows how a list view works.
250    * A list viewer doesn't support icons.
251    * <!-- begin-user-doc -->
252    * <!-- end-user-doc -->
253    * @generated
254    */

255   protected ListViewer listViewer;
256
257   /**
258    * This shows how a table view works.
259    * A table can be used as a list with icons.
260    * <!-- begin-user-doc -->
261    * <!-- end-user-doc -->
262    * @generated
263    */

264   protected TableViewer tableViewer;
265
266   /**
267    * This shows how a tree view with columns works.
268    * <!-- begin-user-doc -->
269    * <!-- end-user-doc -->
270    * @generated
271    */

272   protected TreeViewer treeViewerWithColumns;
273
274   /**
275    * This keeps track of the active viewer pane, in the book.
276    * <!-- begin-user-doc -->
277    * <!-- end-user-doc -->
278    * @generated
279    */

280   protected ViewerPane currentViewerPane;
281
282   /**
283    * This keeps track of the active content viewer, which may be either one of the viewers in the pages or the content outline viewer.
284    * <!-- begin-user-doc -->
285    * <!-- end-user-doc -->
286    * @generated
287    */

288   protected Viewer currentViewer;
289
290   /**
291    * This listens to which ever viewer is active.
292    * <!-- begin-user-doc -->
293    * <!-- end-user-doc -->
294    * @generated
295    */

296   protected ISelectionChangedListener selectionChangedListener;
297
298   /**
299    * This keeps track of all the {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are listening to this editor.
300    * <!-- begin-user-doc -->
301    * <!-- end-user-doc -->
302    * @generated
303    */

304   protected Collection JavaDoc selectionChangedListeners = new ArrayList JavaDoc();
305
306   /**
307    * This keeps track of the selection of the editor as a whole.
308    * <!-- begin-user-doc -->
309    * <!-- end-user-doc -->
310    * @generated
311    */

312   protected ISelection editorSelection= StructuredSelection.EMPTY;
313
314   /**
315    * This listens for when the outline becomes active
316    * <!-- begin-user-doc -->
317    * <!-- end-user-doc -->
318    * @generated
319    */

320   protected IPartListener partListener =
321     new IPartListener()
322     {
323       public void partActivated(IWorkbenchPart p)
324       {
325         if (p instanceof ContentOutline)
326         {
327           if (((ContentOutline)p).getCurrentPage() == contentOutlinePage)
328           {
329             getActionBarContributor().setActiveEditor(EcoreEditor.this);
330
331             setCurrentViewer(contentOutlineViewer);
332           }
333         }
334         else if (p instanceof PropertySheet)
335         {
336           if (((PropertySheet)p).getCurrentPage() == propertySheetPage)
337           {
338             getActionBarContributor().setActiveEditor(EcoreEditor.this);
339             handleActivate();
340           }
341         }
342         else if (p == EcoreEditor.this)
343         {
344           handleActivate();
345         }
346       }
347       public void partBroughtToTop(IWorkbenchPart p)
348       {
349       }
350       public void partClosed(IWorkbenchPart p)
351       {
352       }
353       public void partDeactivated(IWorkbenchPart p)
354       {
355       }
356       public void partOpened(IWorkbenchPart p)
357       {
358       }
359     };
360
361   /**
362    * Resources that have been removed since last activation.
363    * @generated
364    */

365   Collection JavaDoc removedResources = new ArrayList JavaDoc();
366
367   /**
368    * Resources that have been changed since last activation.
369    * @generated
370    */

371   Collection JavaDoc changedResources = new ArrayList JavaDoc();
372  
373   /**
374    * Resources that have been saved.
375    * @generated
376    */

377   Collection JavaDoc savedResources = new ArrayList JavaDoc();
378
379   /**
380    * This listens for workspace changes.
381    * <!-- begin-user-doc -->
382    * <!-- end-user-doc -->
383    * @generated
384    */

385   protected IResourceChangeListener resourceChangeListener =
386     new IResourceChangeListener()
387     {
388       public void resourceChanged(IResourceChangeEvent event)
389       {
390         // Only listening to these.
391
// if (event.getType() == IResourceDelta.POST_CHANGE)
392
{
393           IResourceDelta delta = event.getDelta();
394           try
395           {
396             class ResourceDeltaVisitor implements IResourceDeltaVisitor
397             {
398               protected ResourceSet resourceSet = editingDomain.getResourceSet();
399               protected Collection JavaDoc changedResources = new ArrayList JavaDoc();
400               protected Collection JavaDoc removedResources = new ArrayList JavaDoc();
401
402               public boolean visit(IResourceDelta delta)
403               {
404                 if (delta.getFlags() != IResourceDelta.MARKERS &&
405                       delta.getResource().getType() == IResource.FILE)
406                 {
407                   if ((delta.getKind() & (IResourceDelta.CHANGED | IResourceDelta.REMOVED)) != 0)
408                   {
409                     Resource resource = resourceSet.getResource(URI.createURI(delta.getFullPath().toString()), false);
410                     if (resource != null)
411                     {
412                       if ((delta.getKind() & IResourceDelta.REMOVED) != 0)
413                       {
414                         removedResources.add(resource);
415                       }
416                       else
417                       {
418                         changedResources.add(resource);
419                       }
420                     }
421                   }
422                 }
423
424                 return true;
425               }
426
427               public Collection JavaDoc getChangedResources()
428               {
429                 return changedResources;
430               }
431
432               public Collection JavaDoc getRemovedResources()
433               {
434                 return removedResources;
435               }
436             }
437
438             ResourceDeltaVisitor visitor = new ResourceDeltaVisitor();
439             delta.accept(visitor);
440
441             if (!visitor.getRemovedResources().isEmpty())
442             {
443               removedResources.addAll(visitor.getRemovedResources());
444               if (!isDirty())
445               {
446                 getSite().getShell().getDisplay().asyncExec
447                   (new Runnable JavaDoc()
448                    {
449                      public void run()
450                      {
451                        getSite().getPage().closeEditor(EcoreEditor.this, false);
452                        EcoreEditor.this.dispose();
453                      }
454                    });
455               }
456             }
457
458             if (!visitor.getChangedResources().isEmpty())
459             {
460               changedResources.addAll(visitor.getChangedResources());
461             }
462           }
463           catch (CoreException exception)
464           {
465             EcoreEditorPlugin.INSTANCE.log(exception);
466           }
467         }
468       }
469     };
470
471   /**
472    * Handles activation of the editor or it's associated views.
473    * @generated
474    */

475   protected void handleActivate()
476   {
477     // Recompute the read only state.
478
//
479
if (editingDomain.getResourceToReadOnlyMap() != null)
480     {
481       editingDomain.getResourceToReadOnlyMap().clear();
482
483       // Refresh any actions that may become enabled or disabled.
484
//
485
setSelection(getSelection());
486     }
487
488     if (!removedResources.isEmpty())
489     {
490       if (handleDirtyConflict())
491       {
492         getSite().getPage().closeEditor(EcoreEditor.this, false);
493         EcoreEditor.this.dispose();
494       }
495       else
496       {
497         removedResources.clear();
498         changedResources.clear();
499         savedResources.clear();
500       }
501     }
502     else if (!changedResources.isEmpty())
503     {
504       changedResources.removeAll(savedResources);
505       handleChangedResources();
506       changedResources.clear();
507       savedResources.clear();
508     }
509   }
510
511
512   /**
513    * Handles what to do with changed resources on activation.
514    * @generated
515    */

516   protected void handleChangedResources()
517   {
518     if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict()))
519     {
520       editingDomain.getCommandStack().flush();
521
522       for (Iterator JavaDoc i = changedResources.iterator(); i.hasNext(); )
523       {
524         Resource resource = (Resource)i.next();
525         if (resource.isLoaded())
526         {
527           resource.unload();
528           try
529           {
530             resource.load(Collections.EMPTY_MAP);
531           }
532           catch (IOException JavaDoc exception)
533           {
534             EcoreEditorPlugin.INSTANCE.log(exception);
535           }
536         }
537       }
538     }
539   }
540
541   /**
542    * Shows a dialog that asks if conflicting changes should be discarded.
543    * @generated
544    */

545   protected boolean handleDirtyConflict()
546   {
547     return
548       MessageDialog.openQuestion
549         (getSite().getShell(),
550          getString("_UI_FileConflict_label"),
551          getString("_WARN_FileConflict"));
552   }
553
554   /**
555    * This creates a model editor.
556    * <!-- begin-user-doc -->
557    * <!-- end-user-doc -->
558    * @generated
559    */

560   public EcoreEditor()
561   {
562     super();
563
564     // Create an adapter factory that yields item providers.
565
//
566
List JavaDoc factories = new ArrayList JavaDoc();
567     factories.add(new ResourceItemProviderAdapterFactory());
568     factories.add(new EcoreItemProviderAdapterFactory());
569     factories.add(new ReflectiveItemProviderAdapterFactory());
570
571     adapterFactory = new ComposedAdapterFactory(factories);
572
573     // Create the command stack that will notify this editor as commands are executed.
574
//
575
BasicCommandStack commandStack = new BasicCommandStack();
576
577     // Add a listener to set the most recent command's affected objects to be the selection of the viewer with focus.
578
//
579
commandStack.addCommandStackListener
580       (new CommandStackListener()
581        {
582          public void commandStackChanged(final EventObject JavaDoc event)
583          {
584            getContainer().getDisplay().asyncExec
585              (new Runnable JavaDoc()
586               {
587                 public void run()
588                 {
589                   firePropertyChange(IEditorPart.PROP_DIRTY);
590
591                   // Try to select the affected objects.
592
//
593
Command mostRecentCommand = ((CommandStack)event.getSource()).getMostRecentCommand();
594                   if (mostRecentCommand != null)
595                   {
596                     setSelectionToViewer(mostRecentCommand.getAffectedObjects());
597                   }
598                   if (propertySheetPage != null)
599                   {
600                     propertySheetPage.refresh();
601                   }
602                 }
603               });
604          }
605        });
606
607     // Create the editing domain with a special command stack.
608
//
609
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, new HashMap JavaDoc());
610   }
611
612   /**
613    * This is here for the listener to be able to call it.
614    * <!-- begin-user-doc -->
615    * <!-- end-user-doc -->
616    * @generated
617    */

618   protected void firePropertyChange(int action)
619   {
620     super.firePropertyChange(action);
621   }
622
623   /**
624    * This sets the selection into whichever viewer is active.
625    * <!-- begin-user-doc -->
626    * <!-- end-user-doc -->
627    * @generated
628    */

629   public void setSelectionToViewer(Collection JavaDoc collection)
630   {
631     final Collection JavaDoc theSelection = collection;
632     // Make sure it's okay.
633
//
634
if (theSelection != null && !theSelection.isEmpty())
635     {
636       // I don't know if this should be run this deferred
637
// because we might have to give the editor a chance to process the viewer update events
638
// and hence to update the views first.
639
//
640
//
641
Runnable JavaDoc runnable =
642         new Runnable JavaDoc()
643         {
644           public void run()
645           {
646             // Try to select the items in the current content viewer of the editor.
647
//
648
if (currentViewer != null)
649             {
650               currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true);
651             }
652           }
653         };
654       runnable.run();
655     }
656   }
657
658   /**
659    * This returns the editing domain as required by the {@link IEditingDomainProvider} interface.
660    * This is important for implementing the static methods of {@link AdapterFactoryEditingDomain}
661    * and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
662    * <!-- begin-user-doc -->
663    * <!-- end-user-doc -->
664    * @generated
665    */

666   public EditingDomain getEditingDomain()
667   {
668     return editingDomain;
669   }
670
671   /**
672    * <!-- begin-user-doc -->
673    * <!-- end-user-doc -->
674    * @generated
675    */

676   public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider
677   {
678     public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory)
679     {
680       super(adapterFactory);
681     }
682
683     public Object JavaDoc [] getElements(Object JavaDoc object)
684     {
685       Object JavaDoc parent = super.getParent(object);
686       return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
687     }
688
689     public Object JavaDoc [] getChildren(Object JavaDoc object)
690     {
691       Object JavaDoc parent = super.getParent(object);
692       return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
693     }
694
695     public boolean hasChildren(Object JavaDoc object)
696     {
697       Object JavaDoc parent = super.getParent(object);
698       return parent != null;
699     }
700
701     public Object JavaDoc getParent(Object JavaDoc object)
702     {
703       return null;
704     }
705   }
706
707   /**
708    * <!-- begin-user-doc -->
709    * <!-- end-user-doc -->
710    * @generated
711    */

712   public void setCurrentViewerPane(ViewerPane viewerPane)
713   {
714     if (currentViewerPane != viewerPane)
715     {
716       if (currentViewerPane != null)
717       {
718         currentViewerPane.showFocus(false);
719       }
720       currentViewerPane = viewerPane;
721     }
722     setCurrentViewer(currentViewerPane.getViewer());
723   }
724
725   /**
726    * This makes sure that one content viewer, either for the current page or the outline view, if it has focus,
727    * is the current one.
728    * <!-- begin-user-doc -->
729    * <!-- end-user-doc -->
730    * @generated
731    */

732   public void setCurrentViewer(Viewer viewer)
733   {
734     // If it is changing...
735
//
736
if (currentViewer != viewer)
737     {
738       if (selectionChangedListener == null)
739       {
740         // Create the listener on demand.
741
//
742
selectionChangedListener =
743           new ISelectionChangedListener()
744           {
745             // This just notifies those things that are affected by the section.
746
//
747
public void selectionChanged(SelectionChangedEvent selectionChangedEvent)
748             {
749               setSelection(selectionChangedEvent.getSelection());
750             }
751           };
752       }
753
754       // Stop listening to the old one.
755
//
756
if (currentViewer != null)
757       {
758         currentViewer.removeSelectionChangedListener(selectionChangedListener);
759       }
760
761       // Start listening to the new one.
762
//
763
if (viewer != null)
764       {
765         viewer.addSelectionChangedListener(selectionChangedListener);
766       }
767
768       // Remember it.
769
//
770
currentViewer = viewer;
771
772       // Set the editors selection based on the current viewer's selection.
773
//
774
setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection());
775     }
776   }
777
778   /**
779    * This returns the viewer as required by the {@link IViewerProvider} interface.
780    * <!-- begin-user-doc -->
781    * <!-- end-user-doc -->
782    * @generated
783    */

784   public Viewer getViewer()
785   {
786     return currentViewer;
787   }
788
789   /**
790    * This creates a context menu for the viewer and adds a listener as well registering the menu for extension.
791    * <!-- begin-user-doc -->
792    * <!-- end-user-doc -->
793    * @generated
794    */

795   protected void createContextMenuFor(StructuredViewer viewer)
796   {
797     MenuManager contextMenu = new MenuManager("#PopUp");
798     contextMenu.add(new Separator("additions"));
799     contextMenu.setRemoveAllWhenShown(true);
800     contextMenu.addMenuListener(this);
801     Menu menu= contextMenu.createContextMenu(viewer.getControl());
802     viewer.getControl().setMenu(menu);
803     getSite().registerContextMenu(contextMenu, viewer);
804
805     int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
806     Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance() };
807     viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
808     viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer));
809   }
810
811   /**
812    * This is the method called to load a resource into the editing domain's resource set based on the editor's input.
813    * <!-- begin-user-doc -->
814    * <!-- end-user-doc -->
815    * @generated NOT
816    */

817   public void createModel()
818   {
819     // I assume that the input is a file object.
820
//
821
IFileEditorInput modelFile = (IFileEditorInput)getEditorInput();
822     
823     editingDomain.getResourceSet().getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap());
824
825     try
826     {
827       // Load the resource through the editing domain.
828
//
829
editingDomain.loadResource(URI.createPlatformResourceURI(modelFile.getFile().getFullPath().toString()).toString());
830     }
831     catch (Exception JavaDoc exception)
832     {
833       EcoreEditorPlugin.INSTANCE.log(exception);
834     }
835   }
836
837   /**
838    * This is the method used by the framework to install your own controls.
839    * <!-- begin-user-doc -->
840    * <!-- end-user-doc -->
841    * @generated NOT
842    */

843   public void createPages()
844   {
845     createModel();
846     
847     // Create a page for the selection tree view.
848
//
849
{
850       ViewerPane viewerPane =
851         new ViewerPane(getSite().getPage(), EcoreEditor.this)
852         {
853           public Viewer createViewer(Composite composite)
854           {
855             Tree tree = new Tree(composite, SWT.MULTI);
856             TreeViewer newTreeViewer = new TreeViewer(tree);
857             return newTreeViewer;
858           }
859           public void requestActivation()
860           {
861             super.requestActivation();
862             setCurrentViewerPane(this);
863           }
864         };
865       viewerPane.createControl(getContainer());
866
867       selectionViewer = (TreeViewer)viewerPane.getViewer();
868       selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
869
870       selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
871       selectionViewer.setInput(editingDomain.getResourceSet());
872       viewerPane.setTitle(editingDomain.getResourceSet());
873
874       new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory);
875
876       createContextMenuFor(selectionViewer);
877       int pageIndex = addPage(viewerPane.getControl());
878       setPageText(pageIndex, getString("_UI_SelectionPage_label"));
879     }
880     
881     setActivePage(0);
882
883     getContainer().addControlListener
884       (new ControlAdapter()
885        {
886          boolean guard = false;
887          public void controlResized(ControlEvent event)
888          {
889            if (!guard)
890            {
891              guard = true;
892              hideTabs();
893              guard = false;
894            }
895          }
896        });
897   }
898
899   /**
900    * If there is just one page in the multi-page editor part, this hides
901    * the single tab at the bottom.
902    * <!-- begin-user-doc -->
903    * <!-- end-user-doc -->
904    * @generated
905    */

906   protected void hideTabs()
907   {
908     if (getPageCount() <= 1)
909     {
910       setPageText(0, "");
911       if (getContainer() instanceof CTabFolder)
912       {
913         ((CTabFolder)getContainer()).setTabHeight(1);
914         Point point = getContainer().getSize();
915         getContainer().setSize(point.x, point.y + 6);
916       }
917     }
918   }
919
920   /**
921    * This is used to track the active viewer.
922    * <!-- begin-user-doc -->
923    * <!-- end-user-doc -->
924    * @generated
925    */

926   protected void pageChange(int pageIndex)
927   {
928     super.pageChange(pageIndex);
929
930     // This is a temporary workaround... EATM
931
//
932
Control control = getControl(pageIndex);
933     if (control != null)
934     {
935       control.setVisible(true);
936       control.setFocus();
937     }
938
939     if (contentOutlinePage != null)
940     {
941       handleContentOutlineSelection(contentOutlinePage.getSelection());
942     }
943   }
944
945   /**
946    * This is how the framework determines which interfaces we implement.
947    * <!-- begin-user-doc -->
948    * <!-- end-user-doc -->
949    * @generated
950    */

951   public Object JavaDoc getAdapter(Class JavaDoc key)
952   {
953     if (key.equals(IContentOutlinePage.class))
954     {
955       return getContentOutlinePage();
956     }
957     else if (key.equals(IPropertySheetPage.class))
958     {
959       return getPropertySheetPage();
960     }
961     else if (key.equals(IGotoMarker.class))
962     {
963       return this;
964     }
965     else
966     {
967       return super.getAdapter(key);
968     }
969   }
970
971   /**
972    * This accesses a cached version of the content outliner.
973    * <!-- begin-user-doc -->
974    * <!-- end-user-doc -->
975    * @generated
976    */

977   public IContentOutlinePage getContentOutlinePage()
978   {
979     if (contentOutlinePage == null)
980     {
981       // The content outline is just a tree.
982
//
983
class MyContentOutlinePage extends ContentOutlinePage
984       {
985         public void createControl(Composite parent)
986         {
987           super.createControl(parent);
988           contentOutlineViewer = getTreeViewer();
989           contentOutlineViewer.addSelectionChangedListener(this);
990
991           // Set up the tree viewer.
992
//
993
contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
994           contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
995           contentOutlineViewer.setInput(editingDomain.getResourceSet());
996
997           // Make sure our popups work.
998
//
999
createContextMenuFor(contentOutlineViewer);
1000
1001          if (!editingDomain.getResourceSet().getResources().isEmpty())
1002          {
1003            // Select the root object in the view.
1004
//
1005
ArrayList JavaDoc selection = new ArrayList JavaDoc();
1006            selection.add(editingDomain.getResourceSet().getResources().get(0));
1007            contentOutlineViewer.setSelection(new StructuredSelection(selection), true);
1008          }
1009        }
1010
1011        public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager)
1012        {
1013          super.makeContributions(menuManager, toolBarManager, statusLineManager);
1014          contentOutlineStatusLineManager = statusLineManager;
1015        }
1016
1017        public void setActionBars(IActionBars actionBars)
1018        {
1019          super.setActionBars(actionBars);
1020          getActionBarContributor().shareGlobalActions(this, actionBars);
1021        }
1022      }
1023
1024      contentOutlinePage = new MyContentOutlinePage();
1025
1026      // Listen to selection so that we can handle it is a special way.
1027
//
1028
contentOutlinePage.addSelectionChangedListener
1029        (new ISelectionChangedListener()
1030         {
1031           // This ensures that we handle selections correctly.
1032
//
1033
public void selectionChanged(SelectionChangedEvent event)
1034           {
1035             handleContentOutlineSelection(event.getSelection());
1036           }
1037         });
1038    }
1039
1040    return contentOutlinePage;
1041  }
1042
1043  /**
1044   * This accesses a cached version of the property sheet.
1045   * <!-- begin-user-doc -->
1046   * <!-- end-user-doc -->
1047   * @generated
1048   */

1049  public IPropertySheetPage getPropertySheetPage()
1050  {
1051    if (propertySheetPage == null)
1052    {
1053      propertySheetPage =
1054        new PropertySheetPage()
1055        {
1056          public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager)
1057          {
1058            super.makeContributions(menuManager, toolBarManager, statusLineManager);
1059          }
1060
1061          public void setActionBars(IActionBars actionBars)
1062          {
1063            super.setActionBars(actionBars);
1064            getActionBarContributor().shareGlobalActions(this, actionBars);
1065          }
1066        };
1067      propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory));
1068    }
1069
1070    return propertySheetPage;
1071  }
1072
1073  /**
1074   * This deals with how we want selection in the outliner to affect the other views.
1075   * <!-- begin-user-doc -->
1076   * <!-- end-user-doc -->
1077   * @generated
1078   */

1079  public void handleContentOutlineSelection(ISelection selection)
1080  {
1081    if (currentViewerPane != null && !selection.isEmpty() && selection instanceof IStructuredSelection)
1082    {
1083      Iterator JavaDoc selectedElements = ((IStructuredSelection)selection).iterator();
1084      if (selectedElements.hasNext())
1085      {
1086        // Get the first selected element.
1087
//
1088
Object JavaDoc selectedElement = selectedElements.next();
1089
1090        // If it's the selection viewer, then we want it to select the same selection as this selection.
1091
//
1092
if (currentViewerPane.getViewer() == selectionViewer)
1093        {
1094          ArrayList JavaDoc selectionList = new ArrayList JavaDoc();
1095          selectionList.add(selectedElement);
1096          while (selectedElements.hasNext())
1097          {
1098            selectionList.add(selectedElements.next());
1099          }
1100
1101          // Set the selection to the widget.
1102
//
1103
selectionViewer.setSelection(new StructuredSelection(selectionList));
1104        }
1105        else
1106        {
1107          // Set the input to the widget.
1108
//
1109
if (currentViewerPane.getViewer().getInput() != selectedElement)
1110          {
1111            currentViewerPane.getViewer().setInput(selectedElement);
1112            currentViewerPane.setTitle(selectedElement);
1113          }
1114        }
1115      }
1116    }
1117  }
1118
1119  /**
1120   * This is for implementing {@link IEditorPart} and simply tests the command stack.
1121   * <!-- begin-user-doc -->
1122   * <!-- end-user-doc -->
1123   * @generated
1124   */

1125  public boolean isDirty()
1126  {
1127    return ((BasicCommandStack)editingDomain.getCommandStack()).isSaveNeeded();
1128  }
1129
1130  /**
1131   * This is for implementing {@link IEditorPart} and simply saves the model file.
1132   * <!-- begin-user-doc -->
1133   * <!-- end-user-doc -->
1134   * @generated
1135   */

1136  public void doSave(IProgressMonitor progressMonitor)
1137  {
1138    // Do the work within an operation because this is a long running activity that modifies the workbench.
1139
//
1140
WorkspaceModifyOperation operation =
1141      new WorkspaceModifyOperation()
1142      {
1143        // This is the method that gets invoked when the operation runs.
1144
//
1145
public void execute(IProgressMonitor monitor)
1146        {
1147          try
1148          {
1149            // Save the resource to the file system.
1150
//
1151
Resource savedResource = (Resource)editingDomain.getResourceSet().getResources().get(0);
1152            savedResources.add(savedResource);
1153            savedResource.save(Collections.EMPTY_MAP);
1154          }
1155          catch (Exception JavaDoc exception)
1156          {
1157            EcoreEditorPlugin.INSTANCE.log(exception);
1158          }
1159        }
1160      };
1161
1162    try
1163    {
1164      // This runs the options, and shows progress.
1165
//
1166
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
1167
1168      // Refresh the necessary state.
1169
//
1170
((BasicCommandStack)editingDomain.getCommandStack()).saveIsDone();
1171      firePropertyChange(IEditorPart.PROP_DIRTY);
1172    }
1173    catch (Exception JavaDoc exception)
1174    {
1175      // Something went wrong that shouldn't.
1176
//
1177
EcoreEditorPlugin.INSTANCE.log(exception);
1178    }
1179  }
1180
1181  /**
1182   * This always returns true because it is not currently supported.
1183   * <!-- begin-user-doc -->
1184   * <!-- end-user-doc -->
1185   * @generated
1186   */

1187  public boolean isSaveAsAllowed()
1188  {
1189    return true;
1190  }
1191
1192  public static final String JavaDoc ECORE_FILE_EXTENSION = "ecore";
1193  public static final String JavaDoc EMOF_FILE_EXTENSION = "emof";
1194
1195  /**
1196   * This also changes the editor's input.
1197   * <!-- begin-user-doc -->
1198   * <!-- end-user-doc -->
1199   * @generated NOT
1200   */

1201  public void doSaveAs()
1202  {
1203    SaveAsDialog saveAsDialog= new SaveAsDialog(getSite().getShell());
1204    saveAsDialog.open();
1205    IPath path= saveAsDialog.getResult();
1206    if (path != null)
1207    {
1208      IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
1209      if (file != null)
1210      {
1211        ResourceSet resourceSet = editingDomain.getResourceSet();
1212        Resource currentResource = (Resource)resourceSet.getResources().get(0);
1213        String JavaDoc currentExtension = currentResource.getURI().fileExtension();
1214
1215        URI newURI = URI.createPlatformResourceURI(file.getFullPath().toString());
1216        String JavaDoc newExtension = newURI.fileExtension();
1217        
1218        if (currentExtension.equals(ECORE_FILE_EXTENSION) && newExtension.equals(EMOF_FILE_EXTENSION) ||
1219            currentExtension.equals(EMOF_FILE_EXTENSION) && newExtension.equals(ECORE_FILE_EXTENSION))
1220        {
1221          Resource newResource = resourceSet.createResource(newURI);
1222          newResource.getContents().addAll(currentResource.getContents());
1223          resourceSet.getResources().remove(0);
1224          resourceSet.getResources().move(0, newResource);
1225        }
1226        else
1227        {
1228          currentResource.setURI(newURI);
1229        }
1230
1231        IFileEditorInput modelFile = new FileEditorInput(file);
1232        setInput(modelFile);
1233        setPartName(file.getName());
1234        doSave(getActionBars().getStatusLineManager().getProgressMonitor());
1235      }
1236    }
1237  }
1238
1239  /**
1240   * <!-- begin-user-doc -->
1241   * <!-- end-user-doc -->
1242   * @generated
1243   */

1244  protected void doSaveAs(URI uri, IEditorInput editorInput)
1245  {
1246    ((Resource)editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
1247    setInput(editorInput);
1248    setPartName(editorInput.getName());
1249    IProgressMonitor progressMonitor =
1250      getActionBars().getStatusLineManager() != null ?
1251        getActionBars().getStatusLineManager().getProgressMonitor() :
1252        new NullProgressMonitor();
1253    doSave(progressMonitor);
1254  }
1255
1256  /**
1257   * <!-- begin-user-doc -->
1258   * <!-- end-user-doc -->
1259   * @generated
1260   */

1261  public void gotoMarker(IMarker marker)
1262  {
1263    try
1264    {
1265      if (marker.getType().equals(EValidator.MARKER))
1266      {
1267        String JavaDoc uriAttribute = marker.getAttribute(EValidator.URI_ATTRIBUTE, null);
1268        if (uriAttribute != null)
1269        {
1270          URI uri = URI.createURI(uriAttribute);
1271          EObject eObject = editingDomain.getResourceSet().getEObject(uri, true);
1272          if (eObject != null)
1273          {
1274            setSelectionToViewer(Collections.singleton(editingDomain.getWrapper(eObject)));
1275          }
1276        }
1277      }
1278    }
1279    catch (CoreException exception)
1280    {
1281      EcoreEditorPlugin.INSTANCE.log(exception);
1282    }
1283  }
1284
1285  /**
1286   * This is called during startup.
1287   * <!-- begin-user-doc -->
1288   * <!-- end-user-doc -->
1289   * @generated
1290   */

1291  public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException, PartInitException
1292  {
1293    setSite(site);
1294    setInput(editorInput);
1295    setPartName(editorInput.getName());
1296    site.setSelectionProvider(this);
1297    site.getPage().addPartListener(partListener);
1298    ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE);
1299  }
1300
1301  /**
1302   * <!-- begin-user-doc -->
1303   * <!-- end-user-doc -->
1304   * @generated
1305   */

1306  public void setFocus()
1307  {
1308    getControl(getActivePage()).setFocus();
1309  }
1310
1311  /**
1312   * This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
1313   * <!-- begin-user-doc -->
1314   * <!-- end-user-doc -->
1315   * @generated
1316   */

1317  public void addSelectionChangedListener(ISelectionChangedListener listener)
1318  {
1319    selectionChangedListeners.add(listener);
1320  }
1321
1322  /**
1323   * This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
1324   * <!-- begin-user-doc -->
1325   * <!-- end-user-doc -->
1326   * @generated
1327   */

1328  public void removeSelectionChangedListener(ISelectionChangedListener listener)
1329  {
1330    selectionChangedListeners.remove(listener);
1331  }
1332
1333  /**
1334   * This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to return this editor's overall selection.
1335   * <!-- begin-user-doc -->
1336   * <!-- end-user-doc -->
1337   * @generated
1338   */

1339  public ISelection getSelection()
1340  {
1341    return editorSelection;
1342  }
1343
1344  /**
1345   * This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to set this editor's overall selection.
1346   * Calling this result will notify the listeners.
1347   * <!-- begin-user-doc -->
1348   * <!-- end-user-doc -->
1349   * @generated
1350   */

1351  public void setSelection(ISelection selection)
1352  {
1353    editorSelection = selection;
1354
1355    for (Iterator JavaDoc listeners = selectionChangedListeners.iterator(); listeners.hasNext(); )
1356    {
1357      ISelectionChangedListener listener = (ISelectionChangedListener)listeners.next();
1358      listener.selectionChanged(new SelectionChangedEvent(this, selection));
1359    }
1360    setStatusLineManager(selection);
1361  }
1362
1363  /**
1364   * <!-- begin-user-doc -->
1365   * <!-- end-user-doc -->
1366   * @generated
1367   */

1368  public void setStatusLineManager(ISelection selection)
1369  {
1370    IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer ?
1371      contentOutlineStatusLineManager : getActionBars().getStatusLineManager();
1372  
1373    if (statusLineManager != null)
1374    {
1375      if (selection instanceof IStructuredSelection)
1376      {
1377        Collection JavaDoc collection = ((IStructuredSelection)selection).toList();
1378        switch (collection.size())
1379        {
1380          case 0:
1381          {
1382            statusLineManager.setMessage(getString("_UI_NoObjectSelected"));
1383            break;
1384          }
1385          case 1:
1386          {
1387            String JavaDoc text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next());
1388            statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text));
1389            break;
1390          }
1391          default:
1392          {
1393            statusLineManager.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size())));
1394            break;
1395          }
1396        }
1397      }
1398      else
1399      {
1400        statusLineManager.setMessage("");
1401      }
1402    }
1403  }
1404
1405  /**
1406   * This looks up a string in the plugin's plugin.properties file.
1407   * <!-- begin-user-doc -->
1408   * <!-- end-user-doc -->
1409   * @generated
1410   */

1411  private static String JavaDoc getString(String JavaDoc key)
1412  {
1413    return EcoreEditorPlugin.INSTANCE.getString(key);
1414  }
1415
1416  /**
1417   * This looks up a string in plugin.properties, making a substitution.
1418   * <!-- begin-user-doc -->
1419   * <!-- end-user-doc -->
1420   * @generated
1421   */

1422  private static String JavaDoc getString(String JavaDoc key, Object JavaDoc s1)
1423  {
1424    return EcoreEditorPlugin.INSTANCE.getString(key, new Object JavaDoc [] { s1 });
1425  }
1426
1427  /**
1428   * This implements {@link org.eclipse.jface.action.IMenuListener} to help fill the context menus with contributions from the Edit menu.
1429   * <!-- begin-user-doc -->
1430   * <!-- end-user-doc -->
1431   * @generated
1432   */

1433  public void menuAboutToShow(IMenuManager menuManager)
1434  {
1435    ((IMenuListener)getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
1436  }
1437
1438  /**
1439   * <!-- begin-user-doc -->
1440   * <!-- end-user-doc -->
1441   * @generated
1442   */

1443  public EditingDomainActionBarContributor getActionBarContributor()
1444  {
1445    return (EditingDomainActionBarContributor)getEditorSite().getActionBarContributor();
1446  }
1447
1448  /**
1449   * <!-- begin-user-doc -->
1450   * <!-- end-user-doc -->
1451   * @generated
1452   */

1453  public IActionBars getActionBars()
1454  {
1455    return getActionBarContributor().getActionBars();
1456  }
1457
1458  /**
1459   * <!-- begin-user-doc -->
1460   * <!-- end-user-doc -->
1461   * @generated
1462   */

1463  public AdapterFactory getAdapterFactory()
1464  {
1465    return adapterFactory;
1466  }
1467
1468  /**
1469   * <!-- begin-user-doc -->
1470   * <!-- end-user-doc -->
1471   * @generated
1472   */

1473  public void dispose()
1474  {
1475    ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener);
1476
1477    getSite().getPage().removePartListener(partListener);
1478
1479    adapterFactory.dispose();
1480
1481    if (getActionBarContributor().getActiveEditor() == this)
1482    {
1483      getActionBarContributor().setActiveEditor(null);
1484    }
1485
1486    if (propertySheetPage != null)
1487    {
1488      propertySheetPage.dispose();
1489    }
1490
1491    if (contentOutlinePage != null)
1492    {
1493      contentOutlinePage.dispose();
1494    }
1495
1496    super.dispose();
1497  }
1498
1499}
1500
Popular Tags