Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 58cb5db23adbf87d32ee385d4db4b6b20caa5ae2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
/*****************************************************************************
 * Copyright (c) 2008, 2016 LIFL, CEA LIST, Christian W. Damus, and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Cedric Dumoulin  Cedric.dumoulin@lifl.fr - Initial API and implementation
 *  Christian W. Damus (CEA) - manage models by URI, not IFile (CDO)
 *  Christian W. Damus (CEA) - bug 410346
 *  Christian W. Damus (CEA) - bug 431953 (pre-requisite refactoring of ModelSet service start-up)
 *  Christian W. Damus (CEA) - bug 437217
 *  Christian W. Damus - bugs 469464, 469188, 485220, 496299
 *
 *****************************************************************************/

package org.eclipse.papyrus.infra.ui.editor;

import static org.eclipse.papyrus.infra.core.Activator.log;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.core.commands.operations.IUndoContext;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.osgi.util.NLS;
import org.eclipse.papyrus.infra.core.editor.BackboneException;
import org.eclipse.papyrus.infra.core.language.ILanguageChangeListener;
import org.eclipse.papyrus.infra.core.language.ILanguageService;
import org.eclipse.papyrus.infra.core.language.LanguageChangeEvent;
import org.eclipse.papyrus.infra.core.resource.ModelMultiException;
import org.eclipse.papyrus.infra.core.resource.ModelSet;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.IContentChangedListener;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.ISashWindowsContentProvider;
import org.eclipse.papyrus.infra.core.sasheditor.di.contentprovider.DiSashModelManager;
import org.eclipse.papyrus.infra.core.sasheditor.editor.AbstractMultiPageSashEditor;
import org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer;
import org.eclipse.papyrus.infra.core.sashwindows.di.service.IPageManager;
import org.eclipse.papyrus.infra.core.services.ExtensionServicesRegistry;
import org.eclipse.papyrus.infra.core.services.ServiceException;
import org.eclipse.papyrus.infra.core.services.ServiceMultiException;
import org.eclipse.papyrus.infra.core.services.ServiceStartKind;
import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
import org.eclipse.papyrus.infra.core.utils.ServiceUtils;
import org.eclipse.papyrus.infra.emf.resource.ICrossReferenceIndex;
import org.eclipse.papyrus.infra.emf.resource.ShardResourceLocator;
import org.eclipse.papyrus.infra.ui.Activator;
import org.eclipse.papyrus.infra.ui.contentoutline.ContentOutlineRegistry;
import org.eclipse.papyrus.infra.ui.editor.IReloadableEditor.DirtyPolicy;
import org.eclipse.papyrus.infra.ui.editor.reload.EditorReloadEvent;
import org.eclipse.papyrus.infra.ui.editor.reload.IEditorReloadListener;
import org.eclipse.papyrus.infra.ui.lifecycleevents.DoSaveEvent;
import org.eclipse.papyrus.infra.ui.lifecycleevents.IEditorInputChangedListener;
import org.eclipse.papyrus.infra.ui.lifecycleevents.ISaveAndDirtyService;
import org.eclipse.papyrus.infra.ui.multidiagram.actionbarcontributor.ActionBarContributorRegistry;
import org.eclipse.papyrus.infra.ui.multidiagram.actionbarcontributor.CoreComposedActionBarContributor;
import org.eclipse.papyrus.infra.ui.services.EditorLifecycleManager;
import org.eclipse.papyrus.infra.ui.services.internal.EditorLifecycleManagerImpl;
import org.eclipse.papyrus.infra.ui.services.internal.InternalEditorLifecycleManager;
import org.eclipse.papyrus.infra.ui.util.EditorUtils;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.progress.UIJob;
import org.eclipse.ui.statushandlers.StatusManager;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

/**
 * Multi diagram editor allowing to plug various kind of editors. Editors are
 * registered with the help of the Eclipse extension mechanism. This
 * implementation allows to register editors and context separately. An editor
 * should specify which context it need to run. This multi diagram editor allows
 * to show editor side by side in one or more sash windows.
 *
 * The real implementation for the generic type T of SashMultiPageEditorPart is
 * actually di2.Diagram
 *
 * @author cedric dumoulin
 * @author <a href="mailto:jerome.benois@obeo.fr">Jerome Benois</a>
 * @author <a href="mailto:thomas.szadel@atosorigin.com">Thomas Szadel</a>
 *         Refactoring.
 *
 * @since 1.2
 */
public class CoreMultiDiagramEditor extends AbstractMultiPageSashEditor implements IMultiDiagramEditor, ITabbedPropertySheetPageContributor, IGotoMarker, IEditingDomainProvider {

	/** ContentOutline registry */
	private ContentOutlineRegistry contentOutlineRegistry;

	/** Services registry. Used to get registered services */
	private ServicesRegistry servicesRegistry;

	/**
	 * ActionBarContributor Registry. Allows to get an ActionBar by its Id. The
	 * registry is initialized from the Eclipse extension mechanism.
	 */
	private ActionBarContributorRegistry actionBarContributorRegistry;

	/** SashModelMngr to add pages */
	protected DiSashModelManager sashModelMngr;

	/**
	 * Service used to maintain the dirty state and to perform save and saveAs.
	 */
	protected ISaveAndDirtyService saveAndDirtyService;

	private final List<IPropertySheetPage> propertiesPages = new LinkedList<>();

	private final List<Runnable> closeActions = new ArrayList<>();

	/**
	 * Listener on {@link ISaveAndDirtyService#addInputChangedListener(IEditorInputChangedListener)}
	 */
	private static class EditorInputChangedListener implements IEditorInputChangedListener {

		private CoreMultiDiagramEditor editor;

		public EditorInputChangedListener(CoreMultiDiagramEditor editor) {
			this.editor = editor;
		}

		/**
		 * This method is called when the editor input is changed from the
		 * ISaveAndDirtyService.
		 *
		 * @see org.eclipse.papyrus.infra.ui.lifecycleevents.IEditorInputChangedListener#editorInputChanged(org.eclipse.ui.part.FileEditorInput)
		 *
		 * @param fileEditorInput
		 */
		@Override
		public void editorInputChanged(FileEditorInput fileEditorInput) {
			// Change the editor input.
			editor.setInputWithNotify(fileEditorInput);
			editor.setPartName(fileEditorInput.getName());
		}

		/**
		 * The isDirty flag has changed, reflect its new value
		 *
		 * @see org.eclipse.papyrus.infra.ui.lifecycleevents.IEditorInputChangedListener#isDirtyChanged()
		 *
		 */
		@Override
		public void isDirtyChanged() {

			// Run it in async way.
			editor.getSite().getShell().getDisplay().asyncExec(new Runnable() {

				@Override
				public void run() {
					// editor can be null if this object has been finalized, but
					// still queued in the asyncExec queue.
					// This can happen if the editor is disposed, but some run still in
					// the exec queue.
					// When the method is executed asynchronously, the object is already finalized, and so
					// editor is null.
					if (editor == null) {
						return;
					}
					editor.firePropertyChange(IEditorPart.PROP_DIRTY);
				}
			});
		}

		public void dispose() {
			this.editor = null;
		}
	}

	protected EditorInputChangedListener editorInputChangedListener;

	private TransactionalEditingDomain transactionalEditingDomain;

	/**
	 * Object managing models lifeCycle.
	 */
	protected ModelSet resourceSet;

	/**
	 * Cached event that can be reused.
	 */
	protected DoSaveEvent lifeCycleEvent;

	private class ContentChangedListener implements IContentChangedListener {

		/**
		 * Called when the content is changed. RefreshTabs.
		 */
		@Override
		public void contentChanged(ContentEvent event) {
			scheduleRefresh();
		}
	}

	/**
	 * A listener on model change events.
	 */
	private ContentChangedListener contentChangedListener;

	/**
	 * Undo context used to have the same undo context in all Papyrus related
	 * views and editors. TODO : move away, use a version independent of GMF,
	 * add a listener that will add the context to all commands modifying
	 * attached Resources (==> linked to ModelSet ?)
	 */
	private IUndoContext undoContext;

	/**
	 * Editor reload listeners.
	 */
	private CopyOnWriteArrayList<IEditorReloadListener> reloadListeners = new CopyOnWriteArrayList<>();

	/**
	 * A pending reload operation (awaiting next activation of the editor).
	 */
	private final AtomicReference<DeferredReload> pendingReload = new AtomicReference<>();

	public CoreMultiDiagramEditor() {
		super();

		addSelfReloadListener();
	}

	/**
	 * Get the contentOutlineRegistry. Create it if needed.
	 *
	 * @return the contentOutlineRegistry
	 */
	protected ContentOutlineRegistry getContentOutlineRegistry() {
		if (contentOutlineRegistry == null) {
			createContentOutlineRegistry();
		}

		return contentOutlineRegistry;
	}

	/**
	 * Create the contentOutlineRegistry.
	 */
	private void createContentOutlineRegistry() {
		contentOutlineRegistry = new ContentOutlineRegistry(this, Activator.PLUGIN_ID);
	}

	/**
	 * Returns the service registry associated to the editor.
	 *
	 * @return the servicesRegistry The registry.
	 */
	@Override
	public ServicesRegistry getServicesRegistry() {
		if (servicesRegistry == null) {
			servicesRegistry = createServicesRegistry();
		}
		return servicesRegistry;
	}

	/**
	 * Create the ServicesRegistry.
	 *
	 * @return
	 */
	private ServicesRegistry createServicesRegistry() {
		// Create Services Registry
		try {
			ServicesRegistry servicesRegistry = new ExtensionServicesRegistry(org.eclipse.papyrus.infra.core.Activator.PLUGIN_ID);
			// servicesRegistry.startRegistry();
			return servicesRegistry;
		} catch (ServiceException e) {
			// Show log and error
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * Do nothing as we create the provider before any calls to this method.
	 * Should not be called by subclasses.
	 *
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.AbstractMultiPageSashEditor#createPageProvider()
	 */
	@Override
	protected ISashWindowsContentProvider createPageProvider() {
		throw new UnsupportedOperationException("Not implemented. Should not be called as the ContentProvider is already initialized.");
	}

	/**
	 * Create the pageContentProvider.
	 *
	 * Removed since 0.10.0
	 *
	 * @param pageFactory
	 * @param diResource
	 *            Resource used to load/save the SashModel.
	 *
	 *
	 */
	// protected ISashWindowsContentProvider createPageProvider(IPageModelFactory pageFactory, Resource diResource, TransactionalEditingDomain editingDomain) {
	//
	// sashModelMngr = new TransactionalDiSashModelMngr(pageFactory, diResource, editingDomain);
	//
	// ISashWindowsContentProvider pageProvider = sashModelMngr.getISashWindowsContentProvider();
	//
	// return pageProvider;
	// }

	/**
	 * Get The {@link IPageMngr} used to add, open, remove or close a diagram in
	 * the SashWindow. This method is available as soon as the {@link CoreMultiDiagramEditor#init(IEditorSite, IEditorInput)} method is
	 * called.
	 *
	 * @return
	 */
	protected IPageManager getIPageManager() throws IllegalStateException {
		try {
			return sashModelMngr.getIPageManager();
		} catch (Exception e) {
			throw new IllegalStateException("Method should be called after CoreMultiDiagramEditor#init(IEditorSite, IEditorInput) is called");
		}
	}

	/**
	 * Get the ActionBarContributorRegistry. Creates it if necessary.
	 *
	 * @return
	 */
	protected ActionBarContributorRegistry getActionBarContributorRegistry() {
		if (actionBarContributorRegistry == null) {

			// Try to got it from CoreComposedActionBarContributor
			// Get it from the contributor.
			IEditorActionBarContributor contributor = getEditorSite().getActionBarContributor();
			if (contributor instanceof CoreComposedActionBarContributor) {
				log.debug(getClass().getSimpleName() + " - ActionBarContributorRegistry loaded from CoreComposedActionBarContributor.");
				actionBarContributorRegistry = ((CoreComposedActionBarContributor) contributor).getActionBarContributorRegistry();

			} else {
				// Create a registry.
				log.debug(getClass().getSimpleName() + " - create an ActionBarContributorRegistry.");
				actionBarContributorRegistry = createActionBarContributorRegistry();
			}
		}

		return actionBarContributorRegistry;
	}

	/**
	 * Create the ActionBarContributorRegistry.
	 *
	 * @return
	 */
	private ActionBarContributorRegistry createActionBarContributorRegistry() {
		return new ActionBarContributorRegistry(Activator.PLUGIN_ID);
	}

	/**
	 *
	 *
	 * @param adapter
	 *
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Object getAdapter(Class adapter) {

		if (ServicesRegistry.class == adapter) {
			return getServicesRegistry();
		}

		if (IPageManager.class == adapter) {
			return getIPageManager();
		}

		if (IPropertySheetPage.class == adapter) {
			// Do not test if tabbedPropertySheetPage is null before calling new
			// this is managed by Eclipse which only call current method when
			// necessary
			return getPropertySheetPage();
		}

		// Add a viewer
		if (IContentOutlinePage.class == adapter) {
			try {
				ContentOutlineRegistry outlineRegistry = getContentOutlineRegistry();
				if (outlineRegistry == null) {
					return null;
				}
				IContentOutlinePage contentOutline = outlineRegistry.getContentOutline();
				if (contentOutline != null) {
					return contentOutline;
				}
			} catch (BackboneException e) {
				// Ignore: There is not registered outline.
			}
		}

		if (EditingDomain.class == adapter || TransactionalEditingDomain.class == adapter) {
			return transactionalEditingDomain;
		}

		/*
		 * Return context used for undo/redo. All papyrus views should use this
		 * context. The prefer way to get this is to use undoContext =
		 * servicesRegistry.getService(IUndoContext.class);
		 */
		if (IUndoContext.class == adapter) {
			return undoContext;
		}

		// EMF requirements
		if (IEditingDomainProvider.class == adapter) {
			return this;
		}

		if (adapter == ISelection.class) {
			return getSite().getSelectionProvider().getSelection();
		}

		if (adapter == IReloadableEditor.class) {
			return createReloadAdapter();
		}

		return super.getAdapter(adapter);
	}

	/**
	 * Init the editor.
	 */
	@Override
	public void init(IEditorSite site, IEditorInput input) throws PartInitException {
		// Init super
		super.init(site, input);

		// Set editor name
		setPartName(input.getName());

		initContents();
	}

	@Override
	public void createPartControl(Composite parent) {
		super.createPartControl(parent);

		// Fire the PreDisplay event synchronously, so that listeners can continue
		// setting up the UI before the contents are actually rendered fully
		getLifecycleManager().firePreDisplay(this);

		// Fire the PostDisplay event asynchronously, to leave time to the Eclipse
		// framework to actually display the contents of the editor
		Display.getDefault().asyncExec(new Runnable() {

			@Override
			public void run() {
				// Because we are asynchronous, the editor may already have been disposed
				// (Especially in the case of tests running in the UI Thread)
				if (servicesRegistry == null) {
					return;
				}
				getLifecycleManager().firePostDisplay(CoreMultiDiagramEditor.this);
			}
		});

	}

	protected void loadModelAndServices() throws PartInitException {
		// Create ServicesRegistry and register services
		servicesRegistry = createServicesRegistry();

		// Add itself as a service
		servicesRegistry.add(IMultiDiagramEditor.class, 1, this);

		// Create lifeCycle event provider and the event that is used when the editor fire a save event.
		// lifeCycleEventsProvider = new LifeCycleEventsProvider();
		// lifeCycleEvent = new DoSaveEvent(servicesRegistry, this);
		// servicesRegistry.add(ILifeCycleEventsProvider.class, 1, lifeCycleEventsProvider);

		// register services
		servicesRegistry.add(ActionBarContributorRegistry.class, 1, getActionBarContributorRegistry());
		// servicesRegistry.add(TransactionalEditingDomain.class, 1, transactionalEditingDomain);
		// servicesRegistry.add(DiResourceSet.class, 1, resourceSet);

		// Create and initalize editor icons service
		// PageIconsRegistry pageIconsRegistry = new PageIconsRegistry();
		// PluggableEditorFactoryReader editorReader = new PluggableEditorFactoryReader(Activator.PLUGIN_ID);
		// editorReader.populate(pageIconsRegistry);
		// servicesRegistry.add(IPageIconsRegistry.class, 1, pageIconsRegistry);


		// Create PageModelRegistry requested by content provider.
		// Also populate it from extensions.
		// PageModelFactoryRegistry pageModelRegistry = new PageModelFactoryRegistry();
		// editorReader.populate(pageModelRegistry, servicesRegistry);

		// TODO : create appropriate Resource for the contentProvider, and pass it here.
		// This will allow to remove the old sash stuff.
		// setContentProvider(createPageProvider(pageModelRegistry, resourceSet.getDiResource(), transactionalEditingDomain));
		// servicesRegistry.add(ISashWindowsContentProvider.class, 1, getContentProvider());
		// servicesRegistry.add(IPageMngr.class, 1, getIPageMngr());

		// register a basic label provider
		// adapter factory used by EMF objects
		AdapterFactory factory = null;
		try {
			EditingDomain domain = ServiceUtils.getInstance().getTransactionalEditingDomain(servicesRegistry);
			if (domain instanceof AdapterFactoryEditingDomain) {
				// Use the adapter factory already provided by this editing domain
				factory = ((AdapterFactoryEditingDomain) domain).getAdapterFactory();
			}
		} catch (ServiceException e) {
			// OK, there's no editing domain. That's fine
		}

		if (factory == null) {
			// Must create a new adapter factory
			factory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
		}

		/** label provider for EMF objects */
		ILabelProvider labelProvider = new AdapterFactoryLabelProvider(factory) {

			/**
			 * This implements {@link ILabelProvider}.getText by forwarding it
			 * to an object that implements {@link IItemLabelProvider#getText
			 * IItemLabelProvider.getText}
			 */
			@Override
			public String getText(Object object) {
				// Get the adapter from the factory.
				//
				IItemLabelProvider itemLabelProvider = (IItemLabelProvider) adapterFactory.adapt(object, IItemLabelProvider.class);
				if (object instanceof EObject) {
					if (((EObject) object).eIsProxy()) {
						return "Proxy - " + object;
					}
				}
				return itemLabelProvider != null ? itemLabelProvider.getText(object) : object == null ? "" : object.toString();
			}
		};
		servicesRegistry.add(ILabelProvider.class, 1, labelProvider);

		EditorLifecycleManager lifecycleManager = new EditorLifecycleManagerImpl();
		servicesRegistry.add(EditorLifecycleManager.class, 1, lifecycleManager, ServiceStartKind.LAZY);

		// Start servicesRegistry
		URI uri = EditorUtils.getResourceURI(getEditorInput());

		try {
			// Start the ModelSet first, and load if from the specified File.
			// Also start me so that I may be retrieved from the registry by other services
			List<Class<?>> servicesToStart = new ArrayList<>(1);
			servicesToStart.add(ModelSet.class);
			servicesToStart.add(IMultiDiagramEditor.class);

			servicesRegistry.startServicesByClassKeys(servicesToStart);

			resourceSet = servicesRegistry.getService(ModelSet.class);

			// Install shard resource handling
			new ShardResourceLocator(resourceSet);

			// Resolve a possible shard URI
			uri = EditorUtils.resolveShardRoot(
					ICrossReferenceIndex.getInstance(resourceSet), uri);

			// Load it up
			resourceSet.loadModels(uri);

			// start remaining services
			servicesRegistry.startRegistry();

			// In case of a shard
			String name = java.net.URLDecoder.decode(uri.lastSegment(), "UTF-8");
			if (!name.equals(getPartName())) {
				setPartName(name);
			}
		} catch (ModelMultiException e) {
			try {
				// with the ModelMultiException it is still possible to open the
				// editors that's why the service registry is still started
				servicesRegistry.startRegistry();
				warnUser(e);
			} catch (ServiceException e1) {
				log.error(e);
				// throw new PartInitException("could not initialize services", e); //$NON-NLS-1$
			}
		} catch (ServiceException e) {
			log.error(e);
			// throw new PartInitException("could not initialize services", e);
		} catch (UnsupportedEncodingException e) {
			log.error(e);
		}

		// Get required services

		try {
			transactionalEditingDomain = servicesRegistry.getService(TransactionalEditingDomain.class);
			sashModelMngr = servicesRegistry.getService(DiSashModelManager.class);

			saveAndDirtyService = servicesRegistry.getService(ISaveAndDirtyService.class);
			undoContext = servicesRegistry.getService(IUndoContext.class);

			servicesRegistry.getService(ILanguageService.class).addLanguageChangeListener(createLanguageChangeListener());
		} catch (ServiceException e) {
			log.error("A required service is missing.", e);
			// if one of the services above fail to start, the editor can't run
			// => stop
			throw new PartInitException("could not initialize services", e);
		}


		// Listen on input changed from the ISaveAndDirtyService
		editorInputChangedListener = new EditorInputChangedListener(this);
		saveAndDirtyService.addInputChangedListener(editorInputChangedListener);
		getLifecycleManager().firePostInit(this);
	}

	private ILanguageChangeListener createLanguageChangeListener() {
		return new ILanguageChangeListener() {

			@Override
			public void languagesChanged(LanguageChangeEvent event) {
				// Re-load the editor if languages changed, because new ModelSet configurations may be required
				if (event.getType() == LanguageChangeEvent.ADDED) {
					new UIJob(getSite().getShell().getDisplay(), NLS.bind("Reload editor {0}", getTitle())) {

						@Override
						public IStatus runInUIThread(IProgressMonitor monitor) {
							IStatus result = Status.OK_STATUS;
							monitor = SubMonitor.convert(monitor, IProgressMonitor.UNKNOWN);

							try {
								ISashWindowsContainer container = getISashWindowsContainer();
								if ((container != null) && !container.isDisposed()) {
									IReloadableEditor.ReloadReason reason = IReloadableEditor.ReloadReason.RESOURCES_CHANGED;

									DirtyPolicy dirtyPolicy = DirtyPolicy.getDefault();
									try {
										IReloadableEditor.Adapter.getAdapter(CoreMultiDiagramEditor.this).reloadEditor(resourceSet.getResources(), reason, dirtyPolicy);
									} catch (CoreException e) {
										result = e.getStatus();
									}
								}
							} finally {
								monitor.done();
							}

							return result;
						}
					}.schedule();
				}
			}
		};
	}

	private InternalEditorLifecycleManager getLifecycleManager() {
		// I've been disposed
		if (servicesRegistry == null) {
			return null;
		}
		try {
			return (InternalEditorLifecycleManager) servicesRegistry.getService(EditorLifecycleManager.class);
		} catch (ServiceException ex) {
			Activator.log.error(ex);
		}
		return null;
	}

	protected void loadNestedEditors() throws PartInitException {
		ISashWindowsContentProvider contentProvider = null;
		try {
			contentProvider = servicesRegistry.getService(ISashWindowsContentProvider.class);
		} catch (ServiceException ex) {
			log.error("A required service is missing.", ex);
			// if one of the services above fail to start, the editor can't run
			// => stop
			throw new PartInitException("could not initialize services", ex);
		}

		// Set the content provider providing editors.
		setContentProvider(contentProvider);

		// Listen on contentProvider changes
		if (contentChangedListener == null) {
			contentChangedListener = new ContentChangedListener();
		}
		sashModelMngr.getSashModelContentChangedProvider().addListener(contentChangedListener);

		IEditorInput input = getEditorInput();

		if (input instanceof IPapyrusPageInput) {
			IPapyrusPageInput papyrusPageInput = (IPapyrusPageInput) input;
			final IPageManager pageManager = getIPageManager();

			if (papyrusPageInput.closeOtherPages()) {
				pageManager.closeAllOpenedPages();
			}

			for (URI pageIdentifierURI : papyrusPageInput.getPages()) {
				final EObject pageIdentifier = resourceSet.getEObject(pageIdentifierURI, true);
				if (!pageManager.allPages().contains(pageIdentifier)) {
					Activator.log.warn("The object " + pageIdentifier + " does not reference an existing page");
					continue;
				}

				if (pageManager.isOpen(pageIdentifier)) {
					pageManager.selectPage(pageIdentifier);
				} else {
					pageManager.openPage(pageIdentifier);
				}
			}
		}
	}

	protected void warnUser(ModelMultiException e) {
		Activator.log.error(e);
		MessageDialog.openError(getSite().getShell(), "Error", String.format("Your model is corrupted, invalid links have been found :\n" + "%s" + "It is recommended to fix it before editing it", e.getMessage()));
	}

	/**
	 * Activate this editor. Called after the SWT.control is created.
	 */
	@Override
	protected void activate() {
		super.activate();

		initFolderTabMenus();

		try {
			// Register ISashWindowsContainer as service
			// Should be done only once the container is ready.
			getServicesRegistry().add(ISashWindowsContainer.class, 1, getISashWindowsContainer());
			getServicesRegistry().startServicesByClassKeys(ISashWindowsContainer.class);
			// Let the IPageMngr use the ISashWindowsContainer to discover current folder
			// This should be done after SashWindowContainer initialization.
			// DiSashModelManager sashModelManager = getServicesRegistry().getService(DiSashModelManager.class);
			sashModelMngr.setCurrentFolderAndPageMngr(getISashWindowsContainer());

		} catch (ServiceException e) {
			log.error(e);
		}

	}

	/**
	 * Init the contextual menu shown in the folder tabs. This popup menu is
	 * contributed by the help of Eclipse extensions, using the Commands
	 * framework. I.e, to add a menu item, create a menu, a command and an
	 * handler in the extension.
	 */
	protected void initFolderTabMenus() {
		ISashWindowsContainer container = getISashWindowsContainer();

		// TODO : use a constant
		MenuManager menuManager = new MenuManager("tabmenu");
		menuManager.add(new Separator("tabcommands"));
		menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
		container.setFolderTabMenuManager(menuManager);

		// TODO : use a constant
		getSite().registerContextMenu("org.eclipse.papyrus.infra.core.editor.ui.tabmenu", menuManager, getSite().getSelectionProvider());

	}

	/**
	 * Overrides getPropertySheetPage.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor#getPropertySheetPage()
	 */
	public IPropertySheetPage getPropertySheetPage() {
		IPropertySheetPage propertiesPage = new MultiDiagramPropertySheetPage(this);
		propertiesPages.add(propertiesPage);
		return propertiesPage;
	}

	@Override
	public void dispose() {
		for (IPropertySheetPage propertiesPage : this.propertiesPages) {
			propertiesPage.dispose();
		}
		propertiesPages.clear();

		// Forget the outline page(s)
		contentOutlineRegistry = null;

		super.dispose();
	}

	private IReloadableEditor createReloadAdapter() {

		return new IReloadableEditor() {

			@Override
			public void reloadEditor(Collection<? extends Resource> triggeringResources, ReloadReason reason, DirtyPolicy dirtyPolicy) throws CoreException {
				// Attempt to re-load, later
				pendingReload.set(new DeferredReload(triggeringResources, reason, dirtyPolicy));

				// If I am already active, then do it now. Or, if we're not going to ask the user about it, also do it now
				IWorkbenchPage page = getSite().getPage();
				if ((page.getActiveEditor() == CoreMultiDiagramEditor.this) || (dirtyPolicy != DirtyPolicy.PROMPT_TO_SAVE)) {
					pendingReload.get().reload();
				}
			}

			@Override
			public void addEditorReloadListener(IEditorReloadListener listener) {
				reloadListeners.addIfAbsent(listener);
			}

			@Override
			public void removeEditorReloadListener(IEditorReloadListener listener) {
				reloadListeners.remove(listener);
			}
		};
	}

	private void addSelfReloadListener() {
		createReloadAdapter().addEditorReloadListener(new IEditorReloadListener() {

			@Override
			public void editorAboutToReload(EditorReloadEvent event) {
				event.putContext(new MultiDiagramEditorSelectionContext(event.getEditor()));
			}

			@Override
			public void editorReloaded(EditorReloadEvent event) {
				((MultiDiagramEditorSelectionContext) event.getContext()).restore(event.getEditor());
			}
		});
	}

	/**
	 * Register an action to be run when I am closed. Any number of such actions may
	 * be added. note that close actions also run on re-load, which behaves to all
	 * outward appearances like a close and re-open.
	 * 
	 * @param closeAction
	 *            an action to run when I am closed
	 */
	public void onClose(Runnable closeAction) {
		closeActions.add(closeAction);
	}

	@Override
	protected void deactivate() {
		getLifecycleManager().fireBeforeClose(this);
		if (sashModelMngr != null) {
			sashModelMngr.getSashModelContentChangedProvider().removeListener(contentChangedListener);
		}

		super.deactivate();

		// dispose available service
		if (servicesRegistry != null) {
			try {
				servicesRegistry.disposeRegistry();
				servicesRegistry = null;
			} catch (ServiceMultiException e) {
				log.error(e);
			}
		}

		if (contentChangedListener != null) {
			this.contentChangedListener = null;
		}

		if (editorInputChangedListener != null) {
			this.editorInputChangedListener.dispose();
			this.editorInputChangedListener = null;
		}

		for (Runnable next : closeActions) {
			try {
				next.run();
			} catch (Exception e) {
				Activator.log.error("Uncaught exception in close action", e); //$NON-NLS-1$
			}
		}
		closeActions.clear();

		transactionalEditingDomain = null;
		resourceSet = null;
		undoContext = null;
		saveAndDirtyService = null;
		sashModelMngr = null;
	}

	void initContents() throws PartInitException {
		loadModelAndServices();
		loadNestedEditors();
	}

	@Override
	public void setFocus() {
		super.setFocus();

		DeferredReload reload = pendingReload.get();
		if (reload != null) {
			reload.reload();
		}
	}

	private void doReload() throws CoreException {
		final IWorkbenchPage page = getSite().getPage();
		final IWorkbenchPart activePart = page.getActivePart();
		final IEditorPart activeEditor = page.getActiveEditor();

		final Iterable<? extends IEditorReloadListener> listeners = ImmutableList.copyOf(reloadListeners);
		final EditorReloadEvent event = new EditorReloadEvent(CoreMultiDiagramEditor.this);

		try {
			event.dispatchEditorAboutToReload(listeners);

			deactivate();

			initContents();

			activate();

			// My self-listener will be first, to ensure that the pages are all restored before dependents run
			event.dispatchEditorReloaded(listeners);
		} finally {
			event.dispose();

			// Ensure that the editor previously active is active again (if it still exists)
			if ((activeEditor != null) && page.isPartVisible(activeEditor)) {
				page.activate(activeEditor);
			}

			// Ensure that the part previously active is active again (if it still exists and is not the active editor)
			if ((activePart != null) && (activePart != activeEditor) && page.isPartVisible(activePart)) {
				page.activate(activePart);
			}
		}

	}

	/**
	 * Overrides doSave.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public void doSave(IProgressMonitor monitor) {

		saveAndDirtyService.doSave(monitor);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isDirty() {
		// May happen if the editor has not yet been initialized. In this case, the editor cannot be dirty, so we simply return false.
		// Bug 410286: The isDirty() method can also be called /after/ the editor has been disposed. Most likely an Eclipse bug?
		if (saveAndDirtyService == null) {
			return false;
		}
		return saveAndDirtyService.isDirty();
	}

	/**
	 * Overrides doSaveAs.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ui.part.EditorPart#doSaveAs()
	 */
	@Override
	public void doSaveAs() {

		saveAndDirtyService.doSaveAs();
	}

	/**
	 * Overrides isSaveAsAllowed.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
	 */
	@Override
	public boolean isSaveAsAllowed() {
		return true;
	}

	/**
	 * Overrides getContributorId.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor#getContributorId()
	 */
	@Override
	public String getContributorId() {
		// return Activator.PLUGIN_ID;
		return "TreeOutlinePage";

	}

	// implements IDiagramWorkbenchPart to restore GMF standard behavior
	// and delegate to the activeEditor

	/**
	 * Overrides getDiagram.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart#getDiagram()
	 */
	// public org.eclipse.gmf.runtime.notation.Diagram getDiagram() {
	// IEditorPart activeEditor = getActiveEditor();
	// if(activeEditor instanceof DiagramEditor) {
	// return ((DiagramEditor)activeEditor).getDiagram();
	// } else {
	// return null;
	// }
	// }

	/**
	 * This method is called from a GMF diagram. It should only be called from GMF diagram code. Normally, the Diagram under the Mouse is a GMF
	 * Diagram. The active Diagram can be another Diagram, not
	 * under the mouse. This is a GMF issue.
	 */
	// public DiagramEditPart getDiagramEditPart() {
	//
	// // Get the editor under the mouse
	// // IEditorPart activeEditor = rootContainer.getEditorUnderMouse();
	// IEditorPart activeEditor = getActiveEditor();
	// if(activeEditor == null) {
	// return null;
	// }
	// // IEditorPart activeEditor = getActiveEditor();
	// if(activeEditor instanceof DiagramEditor) {
	// return ((DiagramEditor)activeEditor).getDiagramEditPart();
	// } else {
	// // This case should never happen.
	// // Return null, as the GMF runtime now support it (since 093009)
	// return null;
	// }
	// }

	/**
	 * Overrides getDiagramGraphicalViewer.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart#getDiagramGraphicalViewer()
	 */
	// public IDiagramGraphicalViewer getDiagramGraphicalViewer() {
	// IEditorPart activeEditor = getActiveEditor();
	// if(activeEditor instanceof DiagramEditor) {
	// return ((DiagramEditor)activeEditor).getDiagramGraphicalViewer();
	// } else {
	// return null;
	// }
	// }

	/**
	 * Overrides getEditingDomain.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.edit.domain.IEditingDomainProvider#getEditingDomain()
	 */
	@Override
	public EditingDomain getEditingDomain() {
		return transactionalEditingDomain;
	}

	/**
	 * Throws an UnsupportedOperationException.
	 *
	 * @see org.eclipse.papyrus.infra.core.editor.IMultiDiagramEditor#getDiagramEditDomain()
	 */
	// public DiagramEditDomain getDiagramEditDomain() {
	// throw new UnsupportedOperationException("Not implemented. Should not be called.");
	// }


	/**
	 * Change the editor input.<BR>
	 * <U>Note</U>: that method should be called within the UI-Thread.
	 *
	 * @see org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor#setEditorInput(org.eclipse.ui.IEditorInput)
	 *
	 * @param newInput
	 *            The new input
	 * @deprecated Not used anymore
	 */

	@Override
	@Deprecated
	public void setEditorInput(IEditorInput newInput) {
		setInputWithNotify(newInput);
		setPartName(newInput.getName());
	}

	@Override
	@Deprecated
	public void gotoMarker(IMarker marker) {
		IWorkbench wb = PlatformUI.getWorkbench();
		IWorkbenchPage page = wb.getActiveWorkbenchWindow().getActivePage();
		boolean first = true;
		for (IViewReference view : page.getViewReferences()) {
			// no longer restrict to model explorer (see bug 387578)
			IWorkbenchPart part = view.getPart(false);
			if (part instanceof IGotoMarker) {
				// activate first view implementing the IGotoMarker interface
				if (first) {
					page.activate(view.getPart(false));
					first = false;
				}
				((IGotoMarker) part).gotoMarker(marker);
			}
		}
	}

	private boolean needsRefresh;

	protected void scheduleRefresh() {
		needsRefresh = true;
		Display.getDefault().asyncExec(new Runnable() {

			@Override
			public void run() {
				refreshTabs();
			}
		});
	}

	@Override
	protected void refreshTabs() {
		if (!needsRefresh) {
			return;
		}
		needsRefresh = false;
		super.refreshTabs();
	}

	@Override
	public synchronized IEditorPart getActiveEditor() {
		refreshTabs();
		return super.getActiveEditor();
	}

	private final class DeferredReload extends IReloadableEditor.Adapter {

		private final Collection<? extends Resource> triggeringResources;

		private final ReloadReason reason;

		private final DirtyPolicy dirtyPolicy;

		DeferredReload(Collection<? extends Resource> triggeringResources, ReloadReason reason, DirtyPolicy dirtyPolicy) {
			super(CoreMultiDiagramEditor.this);

			this.triggeringResources = ImmutableSet.copyOf(triggeringResources);
			this.reason = reason;
			this.dirtyPolicy = dirtyPolicy;
		}

		void reload() {
			try {
				reloadEditor(triggeringResources, reason, dirtyPolicy);
			} catch (CoreException e) {
				// Failed to properly unload/load in place, so just close
				getSite().getPage().closeEditor(CoreMultiDiagramEditor.this, false);

				StatusManager.getManager().handle(e.getStatus(), StatusManager.LOG | StatusManager.SHOW);
			}
		}

		@Override
		public void reloadEditor(Collection<? extends Resource> triggeringResources, ReloadReason reason, DirtyPolicy dirtyPolicy) throws CoreException {
			if (!pendingReload.compareAndSet(this, null)) {
				return;
			}

			final DirtyPolicy action = dirtyPolicy.resolve(CoreMultiDiagramEditor.this, triggeringResources, reason);

			if ((action == DirtyPolicy.SAVE) && isDirty()) {
				doSave(new NullProgressMonitor());
			}

			switch (action) {
			case SAVE:
			case DO_NOT_SAVE:
				if (reason.shouldReload(triggeringResources)) {
					// Attempt to re-load
					doReload();
				} else {
					// Just close 'er down
					getSite().getPage().closeEditor(CoreMultiDiagramEditor.this, false);
				}
				break;
			case IGNORE:
				// Pass
				break;
			default:
				throw new IllegalArgumentException("Invalid resolution of editor re-load dirty policy: " + action); //$NON-NLS-1$
			}
		}
	}
}

Back to the top