Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f62485ecdc41365b5128dcc453e589fc3543fc78 (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
/*****************************************************************************
 * Copyright (c) 2010, 2014 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:
 *  Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation
 *  Christian W. Damus (CEA) - post refreshes for transaction commit asynchronously (CDO)
 *  Christian W. Damus (CEA) - bug 429826
 *  Christian W. Damus (CEA) - bug 434635
 *  Christian W. Damus (CEA) - bug 437217
 *  Christian W. Damus (CEA) - bug 441857
 *  Christian W. Damus - bug 450235
 *  Christian W. Damus - bug 451683
 *
 *****************************************************************************/
package org.eclipse.papyrus.views.modelexplorer;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.eclipse.core.commands.operations.IUndoContext;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.transaction.ResourceSetChangeEvent;
import org.eclipse.emf.transaction.ResourceSetListener;
import org.eclipse.emf.transaction.ResourceSetListenerImpl;
import org.eclipse.emf.transaction.Transaction;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerColumn;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.papyrus.infra.core.editor.IMultiDiagramEditor;
import org.eclipse.papyrus.infra.core.editor.IReloadableEditor;
import org.eclipse.papyrus.infra.core.editor.reload.EditorReloadAdapter;
import org.eclipse.papyrus.infra.core.editor.reload.EditorReloadEvent;
import org.eclipse.papyrus.infra.core.editor.reload.TreeViewerContext;
import org.eclipse.papyrus.infra.core.lifecycleevents.IEditorInputChangedListener;
import org.eclipse.papyrus.infra.core.lifecycleevents.ISaveAndDirtyService;
import org.eclipse.papyrus.infra.core.resource.IReadOnlyHandler2;
import org.eclipse.papyrus.infra.core.resource.IReadOnlyListener;
import org.eclipse.papyrus.infra.core.resource.ModelSet;
import org.eclipse.papyrus.infra.core.resource.ReadOnlyEvent;
import org.eclipse.papyrus.infra.core.resource.additional.AdditionalResourcesModel;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.IPageManager;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IPage;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IPageLifeCycleEventsListener;
import org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer;
import org.eclipse.papyrus.infra.core.services.ServiceException;
import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
import org.eclipse.papyrus.infra.core.utils.AdapterUtils;
import org.eclipse.papyrus.infra.core.utils.ServiceUtils;
import org.eclipse.papyrus.infra.emf.providers.SemanticFromModelExplorer;
import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
import org.eclipse.papyrus.infra.services.labelprovider.service.LabelProviderService;
import org.eclipse.papyrus.infra.services.navigation.service.NavigableElement;
import org.eclipse.papyrus.infra.services.navigation.service.NavigationMenu;
import org.eclipse.papyrus.infra.services.navigation.service.NavigationService;
import org.eclipse.papyrus.infra.widgets.util.IRevealSemanticElement;
import org.eclipse.papyrus.views.modelexplorer.SharedModelExplorerState.StateChangedEvent;
import org.eclipse.papyrus.views.modelexplorer.listener.DoubleClickListener;
import org.eclipse.papyrus.views.modelexplorer.matching.IMatchingItem;
import org.eclipse.papyrus.views.modelexplorer.matching.LinkItemMatchingItem;
import org.eclipse.papyrus.views.modelexplorer.matching.ModelElementItemMatchingItem;
import org.eclipse.papyrus.views.modelexplorer.matching.ReferencableMatchingItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.ISaveablePart;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.CommonViewerSorter;
import org.eclipse.ui.navigator.IExtensionActivationListener;
import org.eclipse.ui.navigator.ILinkHelper;
import org.eclipse.ui.navigator.INavigatorContentService;
import org.eclipse.ui.navigator.LinkHelperService;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

/**
 * Papyrus Model Explorer associated to one {@link IMultiDiagramEditor}.
 * This ModelExplorer is linked to one single {@link IMultiDiagramEditor}. It doesn't change its
 * source when the current Editor change. To allow to explore different Model, use a {@link ModelExplorerPageBookView}.
 *
 */
public class ModelExplorerView extends CommonNavigator implements IRevealSemanticElement, IEditingDomainProvider, IPageLifeCycleEventsListener {

	private SharedModelExplorerState sharedState;

	private SharedModelExplorerState.StateChangedListener sharedStateListener;

	/**
	 * The context of the LabelProviderService used by this view
	 *
	 * @see {@link LabelProviderService}
	 */
	public static final String LABEL_PROVIDER_SERVICE_CONTEXT = "org.eclipse.papyrus.views.modelexplorer.labelProvider.context";

	/**
	 * The {@link ServicesRegistry} associated to the Editor. This view is associated to the
	 * ServicesRegistry rather than to the EditorPart.
	 */
	private ServicesRegistry serviceRegistry;

	/** The save aservice associated to the editor. */
	private ISaveAndDirtyService saveAndDirtyService;

	/** {@link IUndoContext} used to tag command in the commandStack. */
	private IUndoContext undoContext;

	/** editing domain used to read/write the model */
	private TransactionalEditingDomain editingDomain;

	/** Flag to avoid reentrant call to refresh. */
	private AtomicBoolean isRefreshing = new AtomicBoolean(false);

	/** Currently selected tree item */
	private TreeItem currentItem;

	/** Navigation menu for selected tree item */
	private NavigationMenu navigationMenu;

	/**
	 * A listener on page (all editors) selection change. This listener is set
	 * in {@link ModelExplorerView#init(IViewSite)}. It should be dispose to remove
	 * hook to the Eclipse page.
	 */
	private ISelectionListener pageSelectionListener = new ISelectionListener() {

		public void selectionChanged(IWorkbenchPart part, ISelection selection) {
			handleSelectionChangedFromDiagramEditor(part, selection);
		}
	};

	/**
	 * Listener on {@link ISaveAndDirtyService#addInputChangedListener(IEditorInputChangedListener)}
	 */
	protected IEditorInputChangedListener editorInputChangedListener = new IEditorInputChangedListener() {

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

		/**
		 * The isDirty flag has changed, reflect its new value
		 *
		 * @see org.eclipse.papyrus.infra.core.lifecycleevents.IEditorInputChangedListener#isDirtyChanged()
		 *
		 */
		public void isDirtyChanged() {
			firePropertyChange(IEditorPart.PROP_DIRTY);
		}
	};

	/** The {@link IPropertySheetPage} this model explorer will use. */
	private final List<IPropertySheetPage> propertySheetPages = new LinkedList<IPropertySheetPage>();

	/**
	 *
	 * Constructor.
	 *
	 * @param part
	 *            The part associated to this ModelExplorer
	 */
	public ModelExplorerView(IMultiDiagramEditor part) {

		if (part == null) {
			throw new IllegalArgumentException("A part should be provided.");
		}

		init(part);

		IReloadableEditor.Adapter.getAdapter(part).addEditorReloadListener(new EditorReloadAdapter() {

			@Override
			public void editorAboutToReload(EditorReloadEvent event) {
				// Stash expansion and selection state of the common viewer
				event.putContext(new ModelExplorerTreeViewerContext(getCommonViewer()));

				deactivate();
			}

			@Override
			public void editorReloaded(EditorReloadEvent event) {
				init(event.getEditor());

				activate();

				initCommonViewer(getCommonViewer());

				// Restore expansion and selection state of the common viewer
				((TreeViewerContext<?>) event.getContext()).restore(getCommonViewer());
			}
		});
	}

	private void init(IMultiDiagramEditor editor) {
		// Try to get the ServicesRegistry
		serviceRegistry = editor.getServicesRegistry();
		if (serviceRegistry == null) {
			throw new IllegalArgumentException("The editor should have a ServiceRegistry.");
		}

		// Get required services from ServicesRegistry
		try {
			saveAndDirtyService = serviceRegistry.getService(ISaveAndDirtyService.class);
			undoContext = serviceRegistry.getService(IUndoContext.class);
		} catch (ServiceException e) {
			Activator.log.error(e);
		}
	}

	/**
	 * Handle a selection change in the editor.
	 *
	 * @param part
	 * @param selection
	 */
	private void handleSelectionChangedFromDiagramEditor(IWorkbenchPart part, ISelection selection) {
		// Handle selection from diagram editor
		if (isLinkingEnabled()) {
			if (part instanceof IEditorPart) {
				if (selection instanceof IStructuredSelection) {
					Iterator<?> selectionIterator = ((IStructuredSelection) selection).iterator();
					ArrayList<Object> semanticElementList = new ArrayList<Object>();
					while (selectionIterator.hasNext()) {
						Object currentSelection = selectionIterator.next();
						Object semanticElement = EMFHelper.getEObject(currentSelection);
						if (semanticElement != null) {
							semanticElementList.add(semanticElement);
						}

					}
					revealSemanticElement(semanticElementList);

				}

			}

			// Selections from the Model Explorer result in a part from the ModelExplorerPageBookView instance which is not an IEditorPart
			if (part instanceof ModelExplorerPageBookView && !selection.isEmpty()) {
				if (selection instanceof IStructuredSelection) {
					// Extracted from org.eclipse.ui.internal.navigator.actions.LinkEditorAction activateEditorJob
					// the problem was that multi-element selections were disabled as only selections of 1 could clear the condition size()==1
					IStructuredSelection sSelection = (IStructuredSelection) selection;
					LinkHelperService linkService = getLinkHelperService();
					ILinkHelper[] helpers = linkService.getLinkHelpersFor(sSelection.getFirstElement()); // LinkHelper in org.eclipse.papyrus.views.modelexplorer
					if (helpers.length > 0) {
						helpers[0].activateEditor(part.getSite().getPage(), sSelection);
					}
				}
			}
		}
	}

	/**
	 * look for the path the list of element (comes from the content provider) to go the eObject
	 *
	 * @param eobject
	 *            that we look for.
	 * @param objects
	 *            a list of elements where eobject can be wrapped.
	 * @return the list of modelElementItem ( from the root to the element that wrap the eobject)
	 */
	protected List<Object> searchPath(EObject eobject, List<Object> objects) {
		SemanticFromModelExplorer semanticGetter = new SemanticFromModelExplorer();
		List<Object> path = new ArrayList<Object>();
		ITreeContentProvider contentProvider = (ITreeContentProvider) getCommonViewer().getContentProvider();
		// IPageMngr iPageMngr = EditorUtils.getIPageMngr();
		IPageManager iPageMngr;
		try {
			iPageMngr = ServiceUtils.getInstance().getIPageManager(serviceRegistry);
		} catch (ServiceException e) {
			// This shouldn't happen.
			return Collections.emptyList();
		}
		Object[] result = iPageMngr.allPages().toArray();
		List<Object> editors = Arrays.asList(result);


		for (Object o : objects) {
			// Search matches in this level
			if (!editors.contains(o)) {
				if (eobject.equals(EMFHelper.getEObject(o))) {
					path.add(o);
					return path;
				}
			}

			// Find childs only for feature container
			for (int i = 0; i < contentProvider.getChildren(o).length; i++) {
				Object treeItem = contentProvider.getChildren(o)[i];

				List<Object> tmppath = new ArrayList<Object>();
				Object element = semanticGetter.getSemanticElement(treeItem);
				if (element != null) {
					if (element instanceof EReference) {
						if (((EReference) element).isContainment() && (!((EReference) element).isDerived())) {
							List<Object> childs = new ArrayList<Object>();
							childs.add(treeItem);
							tmppath = searchPath(eobject, childs);
						}
					}

					else {
						if (element instanceof EObject) {
							List<Object> childs = new ArrayList<Object>();
							childs.add(treeItem);
							tmppath = searchPath(eobject, childs);
						}
					}
				}

				// if tmppath contains the wrapped eobject we have find the good path
				if (tmppath.size() > 0) {
					if (eobject.equals((EMFHelper.getEObject((tmppath.get(tmppath.size() - 1)))))) {
						path.add(o);
						path.addAll(tmppath);
						return path;
					}
				}
			}
		}

		return new ArrayList<Object>();
	}


	/**
	 * {@inheritDoc}
	 */
	// FIXME Use of internal class (NavigatorContentService) - in the hope that the bug gets fixed soon.
	@Override
	protected CommonViewer createCommonViewerObject(Composite aParent) {
		CommonViewer viewer = new CustomCommonViewer(getViewSite().getId(), aParent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);

		initCommonViewer(viewer);

		viewer.getNavigatorContentService().getActivationService().addExtensionActivationListener(new IExtensionActivationListener() {

			public void onExtensionActivation(String aViewerId, String[] theNavigatorExtensionIds, boolean isActive) {
				sharedState.updateNavigatorContentExtensions(theNavigatorExtensionIds, isActive);
			}
		});

		ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE);

		return viewer;
	}

	private void installEMFFacetTreePainter(Tree tree) {
		// Install the EMFFacet Custom Tree Painter
		// org.eclipse.papyrus.infra.emf.Activator.getDefault().getCustomizationManager().installCustomPainter(tree);

		// The EMF Facet MeasureItem Listener is incompatible with the NavigatorDecoratingLabelProvider. Remove it.
		// Symptoms: ModelElementItems with an EMF Facet Overlay have a small selection size
		// Removal also fixes bug 400012: no scrollbar although tree is larger than visible area
		Collection<Listener> listenersToRemove = new LinkedList<Listener>();
		for (Listener listener : tree.getListeners(SWT.MeasureItem)) {
			if (listener.getClass().getName().contains("org.eclipse.papyrus.emf.facet.infra.browser.uicore.internal.CustomTreePainter")) {
				listenersToRemove.add(listener);
			}
		}

		for (Listener listener : listenersToRemove) {
			tree.removeListener(SWT.MeasureItem, listener);
		}
	}

	private void initCommonViewer(CommonViewer viewer) {
		// enable tool-tips
		// workaround for bug 311827: the Common Viewer always uses NavigatorDecoratingLabelProvider
		// as a wrapper for the LabelProvider provided by the application. The NavigatorDecoratingLabelProvider
		// does not delegate tooltip related functions but defines them as empty.

		Object input = getInitialInput();
		ILabelProvider labelProvider = null;

		if (input instanceof ServicesRegistry) {
			ServicesRegistry registry = (ServicesRegistry) input;
			try {
				labelProvider = registry.getService(LabelProviderService.class).getLabelProvider(LABEL_PROVIDER_SERVICE_CONTEXT);
			} catch (ServiceException ex) {
				Activator.log.error(ex);
			}

			labelProvider = new DecoratingLabelProviderWTooltips(labelProvider, (ServicesRegistry) input);
		}

		if (labelProvider == null) {
			labelProvider = new LabelProvider();
		}

		viewer.setLabelProvider(labelProvider); // add for decorator and tooltip support
	}

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

		getCommonViewer().setSorter(null);
		((CustomCommonViewer) getCommonViewer()).getDropAdapter().setFeedbackEnabled(true);
		getCommonViewer().addDoubleClickListener(new DoubleClickListener(new Supplier<ServicesRegistry>() {
			public ServicesRegistry get() {
				return serviceRegistry;
			}
		}));

		try {
			navigationMenu = serviceRegistry.getService(NavigationService.class).createNavigationList();
			if (navigationMenu != null) {
				navigationMenu.setServicesRegistry(serviceRegistry);
				navigationMenu.setParentShell(this.getControl().getShell());
			}
		} catch (ServiceException e) {
			Activator.log.error(e);
		}

		Tree tree = getCommonViewer().getTree();

		tree.addKeyListener(new KeyListener() {

			public void keyReleased(KeyEvent e) {
				if (navigationMenu != null) {
					if (e.keyCode == SWT.ALT) {
						navigationMenu.exitItem();
					}
				}
			}

			public void keyPressed(KeyEvent e) {
				if (e.keyCode != SWT.ALT) {
					return;
				}

				if (navigationMenu != null) {
					Tree tree = getCommonViewer().getTree();

					// Generate a basic mouse event
					Event event = new Event();
					event.widget = tree;
					event.stateMask = SWT.ALT;

					Point absoluteTreeLocation = tree.toDisplay(new Point(0, 0));

					event.x = tree.getDisplay().getCursorLocation().x - absoluteTreeLocation.x;
					event.y = tree.getDisplay().getCursorLocation().y - absoluteTreeLocation.y;

					MouseEvent mouseEvent = new MouseEvent(event);
					navigationMenu.handleRequest(mouseEvent, getTreeItem(mouseEvent));
				}
			}
		});

		tree.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseUp(MouseEvent e) {
				if ((e.stateMask & SWT.ALT) == 0) {
					return;
				}

				TreeItem currentItem = getTreeItem(e);
				if (currentItem != null) {
					Object data = currentItem.getData();
					try {
						NavigationService service = serviceRegistry.getService(NavigationService.class);
						List<NavigableElement> navigableElements = service.getNavigableElements(data);

						// TODO: Implement a priority on NavigableElements and navigate the element with the highest priority
						for (NavigableElement navigableElement : navigableElements) {
							if (navigableElement.isEnabled()) {
								service.navigate(navigableElement);
							}
						}
					} catch (ServiceException ex) {
						Activator.log.error(ex);
					}
				}
			}
		});

		tree.addMouseMoveListener(new MouseMoveListener() {

			public void mouseMove(MouseEvent e) {
				if (navigationMenu != null) {
					navigationMenu.handleRequest(e, getTreeItem(e));
				}
			}

		});

		installEMFFacetTreePainter(tree);
		try {
			ISashWindowsContainer sashWindowsContainer = serviceRegistry.getService(ISashWindowsContainer.class);
			sashWindowsContainer.addPageLifeCycleListener(this);
		} catch (ServiceException ex) {
			// Ignore
		}

		if (sharedState != null) {
			initSharedState(sharedState);
		}
	}

	@Override
	protected CommonViewer createCommonViewer(Composite aParent) {
		CommonViewer viewer = super.createCommonViewer(aParent);
		ViewerColumn column = (ViewerColumn) viewer.getTree().getData(Policy.JFACE + ".columnViewer");
		column.setEditingSupport(new DirectEditorEditingSupport(viewer));
		return viewer;
	}

	private TreeItem getTreeItem(MouseEvent e) {
		return ((Tree) e.widget).getItem(new Point(e.x, e.y));
	}


	/**
	 * Return the control used to render this View
	 *
	 * @see org.eclipse.papyrus.views.modelexplorer.core.ui.pagebookview.IPageBookNestableViewPart#getControl()
	 *
	 * @return the main control of the navigator viewer
	 */
	public Control getControl() {
		return getCommonViewer().getControl();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void init(IViewSite site, IMemento aMemento) throws PartInitException {
		super.init(site, aMemento);

		activate();

		// Self-listen for property changes
		addPropertyListener(new IPropertyListener() {

			public void propertyChanged(Object source, int propId) {
				switch (propId) {
				case IS_LINKING_ENABLED_PROPERTY:
					// Propagate to other instances
					sharedState.setLinkingEnabled(isLinkingEnabled());
					break;
				}
			}
		});
	}

	/**
	 * {@link ResourceSetListener} to listen and react to changes in the
	 * resource set.
	 */
	private final ResourceSetListener resourceSetListener = new ResourceSetListenerImpl() {

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void resourceSetChanged(ResourceSetChangeEvent event) {
			super.resourceSetChanged(event);
			handleResourceSetChanged(event);
		}
	};

	/** cache variable with last transaction which triggered a refresh */
	private Transaction lastTrans = null;

	/**
	 * Run in a UI thread to avoid non UI thread exception.
	 *
	 * @param event
	 */
	private void handleResourceSetChanged(ResourceSetChangeEvent event) {
		// avoid refreshing N times for the same transaction (called for each object in resource)
		Transaction curTrans = event.getTransaction();
		if (lastTrans != null && lastTrans.equals(curTrans)) {
			return;
		}
		lastTrans = curTrans;

		scheduleRefresh();
	}

	private Runnable refreshRunnable;

	/**
	 * Thread-safe
	 * Schedule a runnable which will refresh the view if necessary
	 */
	protected void scheduleRefresh() {
		final Runnable schedule;

		synchronized (this) {
			if (refreshRunnable == null) {
				// No refresh is yet pending. Schedule one
				schedule = createRefreshRunnable();
				refreshRunnable = schedule;
			} else {
				schedule = null;
			}
		}

		if (schedule != null) {
			Control control = getControl();
			Display display = ((control == null) || control.isDisposed()) ? null : control.getDisplay();

			if (display != null) {
				// Don't need to schedule a refresh if we have no control or it's disposed
				display.asyncExec(schedule);
			}
		}
	}

	private Runnable createRefreshRunnable() {
		return new Runnable() {

			public void run() {
				// Only run if I'm still pending
				synchronized (ModelExplorerView.this) {
					if (refreshRunnable != this) {
						return;
					}

					refreshRunnable = null;
				}

				refreshInUIThread();
			}
		};
	}

	/**
	 * Thread-safe method to hurry up a pending refresh of the Model Explorer view (if any), synchronously.
	 * When this method returns, then either the explorer has been refreshed or it doesn't need to be.
	 */
	protected void syncRefresh() {
		final Runnable pending;

		synchronized (this) {
			pending = refreshRunnable;
		}

		if (pending != null) {
			Control control = getControl();
			Display display = ((control == null) || control.isDisposed()) ? null : control.getDisplay();

			if (display != null) {
				// Don't need to execute a refresh if we have no control or it's disposed
				display.syncExec(pending);
			}
		}
	}

	/**
	 * refresh the view.
	 */
	protected void refreshInUIThread() {
		// Need to refresh, even if (temporarily) invisible
		// (Better alternative?: store refresh event and execute once visible again)
		if (getControl().isDisposed()) {
			return;
		}

		// avoid reentrant call
		// Refresh only of we are not already refreshing.
		if (isRefreshing.compareAndSet(false, true)) {
			if (!getCommonViewer().isBusy()) {
				getCommonViewer().refresh();
			}

			isRefreshing.set(false);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected Object getInitialInput() {

		if (serviceRegistry != null) {
			return serviceRegistry;
		} else {
			return super.getInitialInput();
		}

	}

	/**
	 * Activate specified Part.
	 */
	private void activate() {
		try {
			this.editingDomain = ServiceUtils.getInstance().getTransactionalEditingDomain(serviceRegistry);

			// Set Viewer input if it already exist
			if (getCommonViewer() != null) {
				getCommonViewer().setInput(serviceRegistry);
			}
			editingDomain.addResourceSetListener(resourceSetListener);
			IReadOnlyHandler2 readOnlyHandler = AdapterUtils.adapt(editingDomain, IReadOnlyHandler2.class, null);
			if (readOnlyHandler != null) {
				readOnlyHandler.addReadOnlyListener(createReadOnlyListener());
			}
		} catch (ServiceException e) {
			// Can't get EditingDomain, skip
		}

		// listen to change events
		getSite().getPage().addSelectionListener(pageSelectionListener);

		// Listen to isDirty flag
		saveAndDirtyService.addInputChangedListener(editorInputChangedListener);

		if (this.getCommonViewer() != null) {
			// Force a refresh
			Display display = getControl().getDisplay();
			if (display == Display.getCurrent()) {
				refreshInUIThread();
			} else {
				// Hmm. We should be on the UI thread
				Activator.log.warn("Model Explorer activated on a non-UI thread."); //$NON-NLS-1$
				scheduleRefresh();
			}
		}
	}

	/**
	 * Deactivate the Model Explorer.
	 */
	private void deactivate() {
		// deactivate global handler
		if (Activator.log.isDebugEnabled()) {
			Activator.log.debug("deactivate ModelExplorerView"); //$NON-NLS-1$
		}

		try {
			ISashWindowsContainer sashWindowsContainer = serviceRegistry.getService(ISashWindowsContainer.class);
			if (sashWindowsContainer != null) {
				sashWindowsContainer.removePageLifeCycleListener(this);
			}
		} catch (ServiceException ex) {
			// Ignore
		}

		// Stop listening on change events
		getSite().getPage().removeSelectionListener(pageSelectionListener);
		// Stop Listening to isDirty flag
		saveAndDirtyService.removeInputChangedListener(editorInputChangedListener);

		if (editingDomain != null) {
			editingDomain.removeResourceSetListener(resourceSetListener);
			editingDomain = null;
		}

		saveAndDirtyService = null;
		undoContext = null;
		editingDomain = null;
		editingDomain = null;
		lastTrans = null;
	}

	/**
	 * Invoked internally to clear the common viewer's associate listener in order to promote garbage collection.
	 */
	void aboutToDispose() {
		final CommonViewer viewer = getCommonViewer();
		if ((viewer.getTree() != null) && !viewer.getTree().isDisposed()) {
			viewer.setInput(null);

			// Kick the NavigatorContentService to clear the cache in its StructuredViewerManager that leaks all of our tree elements
			INavigatorContentService contentService = getNavigatorContentService();
			if (contentService instanceof IExtensionActivationListener) {
				((IExtensionActivationListener) getNavigatorContentService()).onExtensionActivation(contentService.getViewerId(), new String[0], false);
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void dispose() {

		// Stop if we are already disposed
		if (isDisposed()) {
			return;
		}

		if ((sharedStateListener != null) && (sharedState != null)) {
			sharedState.removeListener(sharedStateListener);
		}

		if (getSite() != null) {
			getSite().getPage().removeSelectionListener(pageSelectionListener);
		}

		deactivate();

		for (IPropertySheetPage propertySheetPage : this.propertySheetPages) {
			propertySheetPage.dispose();
		}

		propertySheetPages.clear();

		pageSelectionListener = null;

		super.dispose();

		// Clean up properties to help GC

	}

	/**
	 * Return true if the component is already disposed.
	 *
	 * @return
	 */
	public boolean isDisposed() {
		// use editorPart as flag
		return saveAndDirtyService == null;
	}

	/**
	 * Retrieves the {@link IPropertySheetPage} that his Model Explorer uses.
	 *
	 * @return
	 */
	private IPropertySheetPage getPropertySheetPage() {
		try {
			final IMultiDiagramEditor multiDiagramEditor = ServiceUtils.getInstance().getService(IMultiDiagramEditor.class, serviceRegistry);

			if (multiDiagramEditor != null) {
				if (multiDiagramEditor instanceof ITabbedPropertySheetPageContributor) {
					ITabbedPropertySheetPageContributor contributor = (ITabbedPropertySheetPageContributor) multiDiagramEditor;
					IPropertySheetPage propertySheetPage = new TabbedPropertySheetPage(contributor);
					this.propertySheetPages.add(propertySheetPage);
					return propertySheetPage;
				}
			}
		} catch (ServiceException ex) {
			Activator.log.error(ex);
		}
		return null;
	}

	/**
	 * in order to see element if the property view
	 */
	@Override
	@SuppressWarnings("rawtypes")
	public Object getAdapter(Class adapter) {
		if (IPropertySheetPage.class.equals(adapter)) {
			return getPropertySheetPage();
		}

		if (IUndoContext.class == adapter) {
			// Return the IUndoContext of associated model.
			return undoContext;
		}

		if (ISaveablePart.class.equals(adapter)) {
			try {
				return serviceRegistry.getService(IMultiDiagramEditor.class);
			} catch (ServiceException ex) {
				Activator.log.error(ex);
			}
			return saveAndDirtyService;
		}

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

		return super.getAdapter(adapter);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @return the EditingDomain used by the properties view
	 */
	public EditingDomain getEditingDomain() {
		return editingDomain;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void selectReveal(ISelection selection) {
		syncRefresh();
		if (getCommonViewer() != null) {
			getCommonViewer().setSelection(selection, true);
		}
	}

	public void revealSemanticElement(List<?> elementList) {
		// Ensure that the ModelExplorer is refreshed before
		// trying to display an element. Useful if the element has just been created,
		// and the model explorer has not yet been refreshed
		syncRefresh();
		reveal(elementList, getCommonViewer());
	}

	/**
	 * Expands the given CommonViewer to reveal the given elements
	 *
	 * @param elementList
	 *            The elements to reveal
	 * @param commonViewer
	 *            The CommonViewer they are to be revealed in
	 */
	public static void reveal(Iterable<?> elementList, final CommonViewer commonViewer) {
		ArrayList<IMatchingItem> matchingItemsToSelect = new ArrayList<IMatchingItem>();
		// filter out non EMF objects
		Iterable<EObject> list = Iterables.filter(elementList, EObject.class);

		for (EObject currentEObject : list) {
			matchingItemsToSelect.add(new ModelElementItemMatchingItem(currentEObject));

			// the content provider exist?
			if (commonViewer.getContentProvider() != null) {
				// retrieve the ancestors to reveal them
				// and allow the selection of the object
				ArrayList<EObject> parents = new ArrayList<EObject>();
				EObject tmp = currentEObject.eContainer();
				while (tmp != null) {
					parents.add(tmp);
					tmp = tmp.eContainer();
				}

				Iterable<EObject> reverseParents = Lists.reverse(parents);

				// reveal the resource if necessary
				Resource r = null;
				if (!parents.isEmpty()) {
					r = parents.get(parents.size() - 1).eResource();
				} else {
					r = currentEObject.eResource();
				}

				if (r != null) {
					final ResourceSet rs = r.getResourceSet();
					final Resource resource = r;
					if (rs instanceof ModelSet && AdditionalResourcesModel.isAdditionalResource((ModelSet) rs, r.getURI())) {
						commonViewer.getControl().getDisplay().syncExec(new Runnable() {

							public void run() {
								commonViewer.expandToLevel(new ReferencableMatchingItem(rs), 1);
								commonViewer.expandToLevel(new ReferencableMatchingItem(resource), 1);
							}
						});

					}
				}

				/*
				 * reveal the ancestors tree using expandToLevel on each of them
				 * in the good order. This is a lot faster than going through the whole tree
				 * using getChildren of the ContentProvider since our Viewer uses a Hashtable
				 * to keep track of the revealed elements.
				 *
				 * However we need to use a dedicated MatchingItem to do the matching,
				 * and a specific comparer in our viewer so than the equals of MatchingItem is
				 * used in priority.
				 *
				 * Please refer to MatchingItem for more infos.
				 */
				EObject previousParent = null;
				for (EObject parent : reverseParents) {
					if (parent.eContainingFeature() != null && previousParent != null) {
						commonViewer.expandToLevel(new LinkItemMatchingItem(previousParent, parent.eContainmentFeature()), 1);
					}

					final IMatchingItem itemToExpand = new ModelElementItemMatchingItem(parent);

					commonViewer.getControl().getDisplay().syncExec(new Runnable() {

						public void run() {
							commonViewer.expandToLevel(itemToExpand, 1);
						}
					});

					previousParent = parent;
				}

				final IMatchingItem itemToExpand = new LinkItemMatchingItem(currentEObject.eContainer(), currentEObject.eContainmentFeature());

				commonViewer.getControl().getDisplay().syncExec(new Runnable() {

					public void run() {
						commonViewer.expandToLevel(itemToExpand, 1);
					}
				});
			}
		}

		selectReveal(new StructuredSelection(matchingItemsToSelect), commonViewer);
	}

	/**
	 * Selects the given ISelection in the given CommonViwer
	 *
	 * @param structuredSelection
	 *            The ISelection to select
	 * @param commonViewer
	 *            The ComonViewer to select it in
	 */
	public static void selectReveal(final ISelection structuredSelection, final Viewer commonViewer) {
		Display.getDefault().syncExec(new Runnable() {

			public void run() {
				commonViewer.setSelection(structuredSelection, true);
			}
		});
	}

	/**
	 * Selects and, if possible, reveals the given ISelection in the given CommonViwer
	 *
	 * @param selection
	 *            The ISelection to select
	 * @param viewer
	 *            The ComonViewer to select it in
	 */
	public static void reveal(final ISelection selection, final CommonViewer viewer) {
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection structured = (IStructuredSelection) selection;
			reveal(Lists.newArrayList(structured.iterator()), viewer);
		} else {
			viewer.getControl().getDisplay().syncExec(new Runnable() {

				public void run() {
					viewer.setSelection(selection);
				}
			});
		}
	}

	public void pageOpened(IPage page) {
		refreshTree();
	}

	public void pageClosed(IPage page) {
		refreshTree();
	}

	private void refreshTree() {
		Display.getDefault().asyncExec(new Runnable() {

			public void run() {
				if (getCommonViewer().getControl() == null || getCommonViewer().getControl().isDisposed()) {
					return;
				}
				getCommonViewer().refresh(true);
				// Force redraw to refresh facet overlay
				getCommonViewer().getTree().redraw();
			}
		});
	}

	public void pageChanged(IPage newPage) {
		// Nothing
	}

	public void pageActivated(IPage page) {
		// Nothing
	}

	public void pageDeactivated(IPage page) {
		// Nothing
	}

	public void pageAboutToBeOpened(IPage page) {
		// Nothing
	}

	public void pageAboutToBeClosed(IPage page) {
		// Nothing
	}

	private IReadOnlyListener createReadOnlyListener() {
		return new IReadOnlyListener() {

			public void readOnlyStateChanged(ReadOnlyEvent event) {
				switch (event.getEventType()) {
				case ReadOnlyEvent.RESOURCE_READ_ONLY_STATE_CHANGED:
					scheduleRefresh();
					break;
				case ReadOnlyEvent.OBJECT_READ_ONLY_STATE_CHANGED:
					CommonViewer viewer = getCommonViewer();
					if ((viewer != null) && (viewer.getControl() != null) && !viewer.getControl().isDisposed()) {
						viewer.refresh(event.getObject());
					}
					break;
				default:
					Activator.log.warn("Unsupported read-only event type: " + event.getEventType());
					break;
				}
			}
		};
	}

	void setSharedState(SharedModelExplorerState state) {
		if (this.sharedState != null) {
			this.sharedState.removeListener(getSharedStateListener());
		}

		this.sharedState = state;

		if (state != null) {
			state.addListener(getSharedStateListener());
			initSharedState(state);
		}
	}

	void initSharedState(SharedModelExplorerState state) {
		setLinkingEnabled(state.isLinkingEnabled());
		setAlphaSorted(state.isAlphaSorted());
	}

	void setAlphaSorted(boolean sorted) {
		CommonViewer viewer = getCommonViewer();
		if ((viewer != null) && (viewer.getControl() != null) && !viewer.getControl().isDisposed()) {
			if (sorted) {
				viewer.setSorter(new CommonViewerSorter());
				if (viewer instanceof CustomCommonViewer) {
					((CustomCommonViewer) viewer).getDropAdapter().setFeedbackEnabled(false);
				}
			} else {
				viewer.setSorter(null);
				if (viewer instanceof CustomCommonViewer) {
					((CustomCommonViewer) viewer).getDropAdapter().setFeedbackEnabled(true);
				}
			}
		}
	}

	SharedModelExplorerState.StateChangedListener getSharedStateListener() {
		if (sharedStateListener == null) {
			sharedStateListener = new SharedModelExplorerState.StateChangedListener() {

				private volatile Runnable contentUpdate;

				public void sharedStateChanged(StateChangedEvent event) {
					switch (event.getEventType()) {
					case StateChangedEvent.LINKING_ENABLED:
						setLinkingEnabled(event.getSource().isLinkingEnabled());
						break;
					case StateChangedEvent.ALPHA_SORTED:
						setAlphaSorted(event.getSource().isAlphaSorted());
						break;
					case StateChangedEvent.CONTENT_EXTENSIONS:
						if (contentUpdate == null) {
							getCommonViewer().getControl().getDisplay().asyncExec(getContentUpdate());
						}
						break;
					}
				}

				private Runnable getContentUpdate() {
					if (contentUpdate == null) {
						contentUpdate = new Runnable() {

							public void run() {
								CommonViewer viewer = getCommonViewer();
								if ((viewer != null) && (viewer.getControl() != null) && !viewer.getControl().isDisposed()) {
									viewer.getNavigatorContentService().getActivationService().activateExtensions(sharedState.getNavigatorContentExtensions(), true);
								}

								// I am no longer pending
								contentUpdate = null;
							}
						};
					}
					return contentUpdate;
				}
			};
		}

		return sharedStateListener;
	}
}

Back to the top