Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 932b51085eed4dd31e8c4f71106f45cd8001f829 (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
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
/*****************************************************************************
 * Copyright (c) 2014, 2018 CEA, 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:
 *   Christian W. Damus (CEA) - Initial API and implementation
 *   Christian W. Damus - bugs 433206, 465416, 434983, 483721, 469188, 485220, 491542, 497865, 533673, 533682
 *   Thanh Liem PHAN (ALL4TEC) thanhliem.phan@all4tec.net - Bug 521550
 *****************************************************************************/
package org.eclipse.papyrus.junit.utils.rules;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.core.commands.operations.IOperationHistory;
import org.eclipse.core.commands.operations.IOperationHistoryListener;
import org.eclipse.core.commands.operations.IUndoContext;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.commands.operations.OperationHistoryEvent;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.e4.ui.model.application.ui.MUIElement;
import org.eclipse.e4.ui.model.application.ui.advanced.MPlaceholder;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.model.application.ui.basic.MPartSashContainerElement;
import org.eclipse.e4.ui.model.application.ui.basic.MPartStack;
import org.eclipse.e4.ui.model.application.ui.basic.MStackElement;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.IWorkspaceCommandStack;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.RootEditPart;
import org.eclipse.gef.ui.palette.PaletteViewer;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.commands.SetBoundsCommand;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IDiagramPreferenceSupport;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditorWithFlyOutPalette;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequestFactory;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.Shape;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.papyrus.editor.PapyrusMultiDiagramEditor;
import org.eclipse.papyrus.infra.core.resource.ModelSet;
import org.eclipse.papyrus.infra.core.resource.sasheditor.DiModel;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IComponentPage;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IEditorPage;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IPageVisitor;
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.ServiceException;
import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
import org.eclipse.papyrus.infra.core.utils.ServiceUtils;
import org.eclipse.papyrus.infra.gmfdiag.common.model.NotationModel;
import org.eclipse.papyrus.infra.nattable.common.editor.AbstractEMFNattableEditor;
import org.eclipse.papyrus.infra.nattable.common.modelresource.PapyrusNattableModel;
import org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager;
import org.eclipse.papyrus.infra.nattable.model.nattable.Table;
import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
import org.eclipse.papyrus.infra.tools.util.PlatformHelper;
import org.eclipse.papyrus.infra.tools.util.TypeUtils;
import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
import org.eclipse.papyrus.junit.utils.EditorUtils;
import org.eclipse.papyrus.junit.utils.JUnitUtils;
import org.eclipse.papyrus.junit.utils.tests.AbstractEditorTest;
import org.eclipse.papyrus.uml.tools.model.UmlModel;
import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPage;
import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPageBookView;
import org.eclipse.papyrus.views.modelexplorer.ModelExplorerView;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.ISaveablePart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.IPage;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.UMLPackage;
import org.junit.runner.Description;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;


/**
 * A fixture that presents editors on a model specified via an annotation as for {@link ProjectFixture}. The editor is closed automatically upon
 * completion of the test.
 */
public class PapyrusEditorFixture extends AbstractModelFixture<TransactionalEditingDomain> {

	private final Collection<IEditorPart> editorsToClose = Lists.newArrayList();

	private final List<String> excludedTypeView = Arrays.asList(new String[] { "Note" });

	private final boolean ensureOperationHistoryIntegrity;

	@SuppressWarnings("restriction")
	private org.eclipse.papyrus.infra.ui.internal.preferences.YesNo initialEditorLayoutStorageMigrationPreference;

	private IMultiDiagramEditor editor;

	private DiagramEditorWithFlyOutPalette activeDiagramEditor;

	private AbstractEMFNattableEditor activeTableEditor;

	private ModelExplorerView modelExplorer;

	private Class<?> testClass;

	private Description testDescription;

	private Collection<IViewPart> viewsToClose;

	private ListMultimap<Description, IFile> modelFiles;

	private IOperationHistoryListener operationHistoryIntegrityListener;
	private IOperationHistory operationHistory;

	/**
	 * Initializes me with the assurance of undo/redo correspondence in the
	 * diagram and EMF views of the command history.
	 */
	public PapyrusEditorFixture() {
		this(true);
	}

	/**
	 * Initializes me with the option to ensure integrity of the operation history
	 * by listening for command execution in the diagram context and, if an operation
	 * executed in the diagram does not have the editing-domain context, adds that
	 * context. This ensures that the diagram editor and the model explorer, for
	 * example, see the same undo/redo history (which they would not if some
	 * diagram-only commands were only in the diagram's history). Some tests do
	 * need to suppress this convenience in order to accurately represent the
	 * normal Papyrus run-time environment.
	 *
	 * @param ensureOperationHistoryIntegrity
	 * 
	 * @since 2.0
	 */
	public PapyrusEditorFixture(boolean ensureOperationHistoryIntegrity) {
		super();

		this.ensureOperationHistoryIntegrity = ensureOperationHistoryIntegrity;
	}

	/**
	 * @since 2.0
	 */
	public IMultiDiagramEditor getEditor() {
		return editor;
	}

	/**
	 * @since 2.0
	 */
	public IMultiDiagramEditor getEditor(String path) {
		IMultiDiagramEditor result = null;

		final String fileName = new Path(path).lastSegment();
		for (IEditorReference next : getWorkbenchPage().getEditorReferences()) {
			if (PapyrusMultiDiagramEditor.EDITOR_ID.equals(next.getId()) && fileName.equals(next.getName())) {
				result = (IMultiDiagramEditor) next.getEditor(true);
			}
		}

		return result;
	}

	@SuppressWarnings("restriction")
	@Override
	protected void starting(Description description) {
		testClass = description.getTestClass();
		testDescription = description;

		// Ensure that we won't see a dialog prompting the user to migrate page layout
		// storage from the DI file to the workspace-private sash file
		initialEditorLayoutStorageMigrationPreference = org.eclipse.papyrus.infra.ui.internal.preferences.EditorPreferences.getInstance().getConvertSharedPageLayoutToPrivate();
		org.eclipse.papyrus.infra.ui.internal.preferences.EditorPreferences.getInstance().setConvertSharedPageLayoutToPrivate(org.eclipse.papyrus.infra.ui.internal.preferences.YesNo.NO);

		if (hasRequiredViews()) {
			openRequiredViews();
		}

		modelFiles = ArrayListMultimap.create();
		openAll(description);

		ActiveDiagram activeDiagram = JUnitUtils.getAnnotation(description, ActiveDiagram.class);
		if (activeDiagram != null) {
			String name = activeDiagram.value();
			activateDiagram(name);
			if ((activeDiagramEditor == null) || !name.equals(getActiveDiagramEditor().getDiagram().getName())) {
				// OK, we need to open it, then
				openDiagram(name);
			}
		} else {
			ActiveTable activeTable = JUnitUtils.getAnnotation(description, ActiveTable.class);
			if (activeTable != null) {
				String name = activeTable.value();
				activateTable(name);
				if ((activeTableEditor == null) || !name.equals(getActiveTableEditor().getTable().getName())) {
					openTable(name);
				}
			}
		}

		super.starting(description);

		if (ensureOperationHistoryIntegrity) {
			// Ensure consistency of undo/redo with EMF operations
			final IWorkspaceCommandStack stack = (IWorkspaceCommandStack) getEditingDomain().getCommandStack();
			final IUndoContext emfContext = stack.getDefaultUndoContext();
			operationHistory = stack.getOperationHistory();
			operationHistoryIntegrityListener = new IOperationHistoryListener() {
				@Override
				public void historyNotification(OperationHistoryEvent event) {
					if ((event.getEventType() == OperationHistoryEvent.DONE) && (activeDiagramEditor != null)) {
						IUndoContext diagramContext = activeDiagramEditor.getDiagramEditDomain().getDiagramCommandStack().getUndoContext();
						if (diagramContext != null) {
							IUndoableOperation undo = event.getOperation();
							if ((undo != null) && !undo.hasContext(emfContext)) {
								undo.addContext(emfContext);
							}
						}
					}
					// nothing to do for table
				}
			};
			operationHistory.addOperationHistoryListener(operationHistoryIntegrityListener);
		}
	}

	@SuppressWarnings("restriction")
	@Override
	protected void finished(Description description) {
		try {
			modelFiles = null;

			Exception exception = null;

			for (IEditorPart editor : ImmutableList.copyOf(editorsToClose)) {
				try {
					close(editor);
				} catch (Exception e) {
					if (exception == null) {
						exception = e;
					}
				}
			}

			if (exception != null) {
				exception.printStackTrace();
				fail("Failed to close an editor: " + exception.getLocalizedMessage());
			}
		} finally {
			try {
				if (operationHistoryIntegrityListener != null) {
					operationHistory.removeOperationHistoryListener(operationHistoryIntegrityListener);
					operationHistoryIntegrityListener = null;
					operationHistory = null;
				}

			} finally {
				editorsToClose.clear();
				editor = null;
				activeDiagramEditor = null;

				org.eclipse.papyrus.infra.ui.internal.preferences.EditorPreferences.getInstance().setConvertSharedPageLayoutToPrivate(initialEditorLayoutStorageMigrationPreference);

				try {
					if (hasRequiredViews()) {
						closeRequiredViews();
					}
				} finally {
					super.finished(description);
				}
			}
		}
	}

	@Override
	public TransactionalEditingDomain getEditingDomain() {
		TransactionalEditingDomain result = null;

		if (editor != null) {
			result = getEditingDomain(editor);
		}

		return result;
	}

	/**
	 * @since 2.0
	 */
	public TransactionalEditingDomain getEditingDomain(IMultiDiagramEditor editor) {
		TransactionalEditingDomain result = null;

		try {
			result = getServiceRegistry(editor).getService(TransactionalEditingDomain.class);
		} catch (ServiceException e) {
			e.printStackTrace();
			fail("Failed to get editing domain from Papyrus editor: " + e.getLocalizedMessage());
		}

		return result;
	}

	@Override
	protected TransactionalEditingDomain createEditingDomain() {
		// We don't create the domain; the editor does
		return null;
	}

	/**
	 * @since 2.0
	 */
	protected IMultiDiagramEditor open(final IFile modelFile) {
		final boolean firstEditor = editorsToClose.isEmpty();

		Display.getDefault().syncExec(new Runnable() {

			@Override
			public void run() {
				try {
					editor = EditorUtils.openPapyrusEditor(modelFile);
					editorsToClose.add(editor);
				} catch (Exception e) {
					e.printStackTrace();
					fail("Failed to open Papyrus editor: " + e.getLocalizedMessage());
				}
			}
		});

		if (firstEditor && !editorsToClose.isEmpty()) {
			final IWorkbenchPage page = editor.getSite().getPage();
			page.addPartListener(new IPartListener() {

				@Override
				public void partClosed(IWorkbenchPart part) {
					editorsToClose.remove(part);

					if (part == editor) {
						editor = null;
					}

					if (editorsToClose.isEmpty()) {
						page.removePartListener(this);
					}
				}

				@Override
				public void partOpened(IWorkbenchPart part) {
					// Pass
				}

				@Override
				public void partDeactivated(IWorkbenchPart part) {
					// Pass
				}

				@Override
				public void partBroughtToTop(IWorkbenchPart part) {
					// Pass
				}

				@Override
				public void partActivated(IWorkbenchPart part) {
					// Pass
				}
			});
		}

		flushDisplayEvents();

		return editor;
	}

	/**
	 * @since 2.0
	 */
	protected IMultiDiagramEditor openOne(Description description) {
		IFile papyrusModel = getProject().getFile(Iterables.getOnlyElement(initModelResources(description)).getURI().trimFileExtension().appendFileExtension(DiModel.DI_FILE_EXTENSION));
		modelFiles.put(description, papyrusModel);
		return open(papyrusModel);
	}

	protected Iterable<IMultiDiagramEditor> openAll(Description description) {
		List<IMultiDiagramEditor> result = Lists.newArrayList();

		for (Resource resource : initModelResources(description)) {
			if (resource.getURI().fileExtension().equals(UmlModel.UML_FILE_EXTENSION)) {
				IFile papyrusModel = getProject().getFile(resource.getURI().trimFileExtension().appendFileExtension(DiModel.DI_FILE_EXTENSION));
				modelFiles.put(description, papyrusModel);
				result.add(open(papyrusModel));
			}
		}

		return result;
	}

	/**
	 * @since 2.0
	 */
	protected IMultiDiagramEditor reopenOne(Description description) {
		IFile papyrusModel = modelFiles.get(description).get(0);
		return open(papyrusModel);
	}

	/**
	 * @since 2.0
	 */
	public IMultiDiagramEditor open() {
		return openOne(testDescription);
	}

	/**
	 * @since 2.0
	 */
	public IMultiDiagramEditor open(String resourcePath) {
		return open(new Path(resourcePath).removeFileExtension().lastSegment(), ResourceKind.BUNDLE, resourcePath);
	}

	/**
	 * @since 2.0
	 */
	public IMultiDiagramEditor open(String targetPath, String resourcePath) {
		return open(targetPath, ResourceKind.BUNDLE, resourcePath);
	}

	/**
	 * @since 2.0
	 */
	public IMultiDiagramEditor open(String targetPath, ResourceKind resourceKind, String resourcePath) {
		final IFile papyrusModel = getProject().getFile(initModelResource(targetPath, resourceKind, resourcePath).getURI().trimFileExtension().appendFileExtension(DiModel.DI_FILE_EXTENSION));
		return open(papyrusModel);
	}

	/**
	 * Reopens the same test model that was previously {@link #open() opened} and the
	 * subsequently {@link #close() closed}. This is an important disction, as simply
	 * {@link #open() opening} the test model again would actually re-initialize it from
	 * the deployed test resources, potentially replacing any changes in the model files
	 * that may be significant to the test.
	 * 
	 * @return the re-opened editor
	 * @since 2.0
	 */
	public IMultiDiagramEditor reopen() {
		return reopenOne(testDescription);
	}

	public void activate() {
		if (editor != null) {
			activate(editor);
		}
	}

	public void activate(IWorkbenchPart part) {
		IWorkbenchPage page = part.getSite().getPage();

		if (page.getActivePart() != part) {
			page.activate(part);
			flushDisplayEvents();
		}
	}

	public void close() {
		if (editor != null) {
			close(editor);
			editor = null;
		}
	}

	public void close(IEditorPart editor) {
		editor.getSite().getPage().closeEditor(editor, false);
		flushDisplayEvents();
	}

	public ModelExplorerView getModelExplorerView() {

		Display.getDefault().syncExec(new Runnable() {

			@Override
			public void run() {
				ModelExplorerPageBookView view;
				try {
					view = (ModelExplorerPageBookView) getWorkbenchPage().showView(AbstractEditorTest.MODELEXPLORER_VIEW_ID);
				} catch (PartInitException e) {
					e.printStackTrace();
					return;
				}

				IPage currentPage = view.getCurrentPage();
				ModelExplorerPage page = (ModelExplorerPage) currentPage;
				IViewPart viewer = page.getViewer();
				modelExplorer = (ModelExplorerView) viewer;
			}
		});

		return modelExplorer;
	}

	protected final IWorkbenchPage getWorkbenchPage() {
		IWorkbench bench = PlatformUI.getWorkbench();
		IWorkbenchWindow window = bench.getActiveWorkbenchWindow();
		if (window == null) {
			window = bench.getWorkbenchWindows()[0];
		}
		return window.getActivePage();
	}

	public ServicesRegistry getServiceRegistry() {
		return getServiceRegistry(editor);
	}

	/**
	 * @since 2.0
	 */
	public ServicesRegistry getServiceRegistry(IMultiDiagramEditor editor) {
		return editor.getServicesRegistry();
	}

	public ModelSet getModelSet() {
		return getModelSet(editor);
	}

	/**
	 * @since 2.0
	 */
	public ModelSet getModelSet(IMultiDiagramEditor editor) {
		try {
			return getServiceRegistry(editor).getService(ModelSet.class);
		} catch (ServiceException e) {
			e.printStackTrace();
			fail("Failed to get model set from Papyrus editor: " + e.getLocalizedMessage());
			return null; // Unreachable
		}
	}

	@Override
	public Package getModel() {
		return getModel(editor);
	}

	/**
	 * @since 2.0
	 */
	public Package getModel(IMultiDiagramEditor editor) {
		Package result = null;

		ModelSet modelSet = getModelSet(editor);
		UmlModel uml = (UmlModel) modelSet.getModel(UmlModel.MODEL_ID);
		assertThat("No UML model present in resource set", uml.getResource(), notNullValue());

		result = (Package) EcoreUtil.getObjectByType(uml.getResource().getContents(), UMLPackage.Literals.PACKAGE);
		assertThat("Model resource contains no UML Package", result, notNullValue());

		return result;
	}

	/**
	 * @since 2.0
	 */
	public IPageManager getPageManager() {
		return getPageManager(editor);
	}

	/**
	 * @since 2.0
	 */
	public IPageManager getPageManager(IMultiDiagramEditor editor) {
		try {
			return getServiceRegistry(editor).getService(IPageManager.class);
		} catch (ServiceException e) {
			e.printStackTrace();
			fail("Failed to get page manager from Papyrus editor: " + e.getLocalizedMessage());
			return null; // Unreachable
		}
	}

	public PapyrusEditorFixture activateDiagram(String name) {
		return activateDiagram(editor, name);
	}

	public PapyrusEditorFixture activateTable(String name) {
		return activateTable(editor, name);
	}

	/**
	 * @since 2.0
	 */
	public PapyrusEditorFixture activateDiagram(IMultiDiagramEditor editor, final String name) {
		activate(editor);

		final ISashWindowsContainer sashContainer = PlatformHelper.getAdapter(editor, ISashWindowsContainer.class);
		final org.eclipse.papyrus.infra.core.sasheditor.editor.IPage[] select = { null };

		sashContainer.visit(new IPageVisitor() {

			@Override
			public void accept(IEditorPage page) {
				if (name.equals(page.getPageTitle()) && (page.getIEditorPart() instanceof DiagramEditorWithFlyOutPalette)) {
					select[0] = page;
					setActiveDiagramEditor((DiagramEditorWithFlyOutPalette) page.getIEditorPart());
				}
			}

			@Override
			public void accept(IComponentPage page) {
				// Pass
			}
		});

		if (select[0] != null) {
			sashContainer.selectPage(select[0]);
			flushDisplayEvents();
		}

		return this;
	}

	/**
	 * @since 2.0
	 */
	public PapyrusEditorFixture activateTable(IMultiDiagramEditor editor, final String name) {
		activate(editor);

		final ISashWindowsContainer sashContainer = PlatformHelper.getAdapter(editor, ISashWindowsContainer.class);
		final org.eclipse.papyrus.infra.core.sasheditor.editor.IPage[] select = { null };

		sashContainer.visit(new IPageVisitor() {

			@Override
			public void accept(IEditorPage page) {
				if (name.equals(page.getPageTitle()) && (page.getIEditorPart() instanceof AbstractEMFNattableEditor)) {
					select[0] = page;
					setActiveTableEditor((AbstractEMFNattableEditor) page.getIEditorPart());
				}
			}

			@Override
			public void accept(IComponentPage page) {
				// Pass
			}
		});

		if (select[0] != null) {
			sashContainer.selectPage(select[0]);
			flushDisplayEvents();
		}

		return this;
	}

	private void setActiveDiagramEditor(DiagramEditorWithFlyOutPalette editor) {
		activeDiagramEditor = editor;
		activeTableEditor = null;
	}

	private void setActiveTableEditor(AbstractEMFNattableEditor editor) {
		activeTableEditor = editor;
		activeDiagramEditor = null;
	}

	public PapyrusEditorFixture activateDiagram(DiagramEditPart diagram) {
		return activateDiagram(editor, diagram);
	}

	/**
	 * @since 2.0
	 */
	public PapyrusEditorFixture activateDiagram(IMultiDiagramEditor editor, final DiagramEditPart diagram) {
		activate(editor);

		final ISashWindowsContainer sashContainer = PlatformHelper.getAdapter(editor, ISashWindowsContainer.class);
		final org.eclipse.papyrus.infra.core.sasheditor.editor.IPage[] select = { null };

		sashContainer.visit(new IPageVisitor() {

			@Override
			public void accept(IEditorPage page) {
				DiagramEditorWithFlyOutPalette nested = TypeUtils.as(page.getIEditorPart(), DiagramEditorWithFlyOutPalette.class);
				if ((nested != null) && (nested.getDiagramEditPart() == diagram)) {
					select[0] = page;
					setActiveDiagramEditor(nested);
				}
			}

			@Override
			public void accept(IComponentPage page) {
				// Pass
			}
		});

		if (select[0] != null) {
			sashContainer.selectPage(select[0]);
			flushDisplayEvents();
		}

		return this;
	}

	public PapyrusEditorFixture openDiagram(String name) {
		return openDiagram(editor, name);
	}

	public PapyrusEditorFixture openTable(String name) {
		return openTable(editor, name);
	}

	/**
	 * @since 2.0
	 */
	public PapyrusEditorFixture openDiagram(IMultiDiagramEditor editor, final String name) {
		activate(editor);

		try {
			ModelSet modelSet = ServiceUtils.getInstance().getModelSet(editor.getServicesRegistry());
			NotationModel notation = (NotationModel) modelSet.getModel(NotationModel.MODEL_ID);
			Diagram diagram = notation.getDiagram(name);
			ServiceUtils.getInstance().getService(IPageManager.class, editor.getServicesRegistry()).openPage(diagram);
			flushDisplayEvents();

			activateDiagram(editor, name);
		} catch (Exception e) {
			throw new IllegalStateException("Cannot initialize test", e);
		}

		return this;
	}

	/**
	 * @since 2.0
	 */
	public PapyrusEditorFixture openTable(IMultiDiagramEditor editor, final String name) {
		activate(editor);

		try {
			ModelSet modelSet = ServiceUtils.getInstance().getModelSet(editor.getServicesRegistry());
			PapyrusNattableModel notation = (PapyrusNattableModel) modelSet.getModel(PapyrusNattableModel.MODEL_ID);
			Table table = notation.getTable(name);
			ServiceUtils.getInstance().getService(IPageManager.class, editor.getServicesRegistry()).openPage(table);
			flushDisplayEvents();

			activateTable(editor, name);
		} catch (Exception e) {
			throw new IllegalStateException("Cannot initialize test", e); // NON-NLS-1
		}

		return this;
	}

	public String closeDiagram() {
		String result = getActiveDiagramEditor().getDiagram().getName();
		closeDiagram(editor, result);
		return result;
	}

	public PapyrusEditorFixture closeDiagram(String name) {
		return closeDiagram(editor, name);
	}

	/**
	 * @since 2.0
	 */
	public PapyrusEditorFixture closeDiagram(IMultiDiagramEditor editor, final String name) {
		try {
			ModelSet modelSet = ServiceUtils.getInstance().getModelSet(editor.getServicesRegistry());
			NotationModel notation = (NotationModel) modelSet.getModel(NotationModel.MODEL_ID);
			Diagram diagram = notation.getDiagram(name);

			// If the diagram was deleted, then so too was its page
			if (diagram != null) {
				ServiceUtils.getInstance().getService(IPageManager.class, editor.getServicesRegistry()).closePage(diagram);
				flushDisplayEvents();
			}
		} catch (Exception e) {
			throw new IllegalStateException("Cannot close diagram", e);
		}

		return this;
	}

	public DiagramEditorWithFlyOutPalette getActiveDiagramEditor() {
		DiagramEditorWithFlyOutPalette result = activeDiagramEditor;

		if (result == null) {
			IEditorPart activeEditor = getWorkbenchPage().getActiveEditor();
			if (activeEditor instanceof IMultiDiagramEditor) {
				activeEditor = ((IMultiDiagramEditor) activeEditor).getActiveEditor();
				if (activeEditor instanceof DiagramEditorWithFlyOutPalette) {
					result = (DiagramEditorWithFlyOutPalette) activeEditor;
					setActiveDiagramEditor(result);
				}
			}
		}

		assertThat("No diagram active", result, notNullValue());

		return result;
	}

	public AbstractEMFNattableEditor getActiveTableEditor() {
		AbstractEMFNattableEditor result = activeTableEditor;

		if (result == null) {
			IEditorPart activeEditor = getWorkbenchPage().getActiveEditor();
			if (activeEditor instanceof IMultiDiagramEditor) {
				activeEditor = ((IMultiDiagramEditor) activeEditor).getActiveEditor();
				if (activeEditor instanceof AbstractEMFNattableEditor) {
					result = (AbstractEMFNattableEditor) activeEditor;
					setActiveTableEditor(result);
				}
			}
		}

		assertThat("No table active", result, notNullValue());

		return result;
	}

	public DiagramEditPart getActiveDiagram() {
		return getActiveDiagramEditor().getDiagramEditPart();
	}

	public INattableModelManager getActiveTableManager() {
		return (INattableModelManager) getActiveTableEditor().getAdapter(INattableModelManager.class);
	}

	public DiagramEditPart getDiagram(String name) {
		return getDiagram(editor, name);
	}

	/**
	 * @since 2.0
	 */
	public DiagramEditPart getDiagram(IMultiDiagramEditor editor, final String name) {
		final ISashWindowsContainer sashContainer = PlatformHelper.getAdapter(editor, ISashWindowsContainer.class);
		final org.eclipse.papyrus.infra.core.sasheditor.editor.IPage[] matchedPage = { null };

		sashContainer.visit(new IPageVisitor() {

			@Override
			public void accept(IEditorPage page) {
				if (name.equals(page.getPageTitle()) && (page.getIEditorPart() instanceof DiagramEditorWithFlyOutPalette)) {
					matchedPage[0] = page;
				}
			}

			@Override
			public void accept(IComponentPage page) {
				// Pass
			}
		});

		IEditorPage editorPage = TypeUtils.as(matchedPage[0], IEditorPage.class);
		IDiagramWorkbenchPart diagramPart = (editorPage == null) ? null : TypeUtils.as(editorPage.getIEditorPart(), IDiagramWorkbenchPart.class);

		// The lazy initialization, used in the patch for bug 519107, does not initialize the diagram edit part of UmlGmfDiagramEditor
		// So we call the setFocus method here to initialize it manually (see patch for bug 521353)
		if (null != diagramPart) {
			if (null == diagramPart.getDiagramEditPart()) {
				diagramPart.setFocus();
			}
			return diagramPart.getDiagramEditPart();
		}
		return null;
	}

	public EditPart findEditPart(EObject modelElement) {
		return findEditPart(getActiveDiagramEditor(), modelElement);
	}

	/**
	 * @since 2.0
	 */
	public EditPart findEditPart(IMultiDiagramEditor editor, EObject modelElement) {
		IEditorPart activeEditor = editor.getActiveEditor();
		assertThat("No diagram active", activeEditor, instanceOf(DiagramEditor.class));
		return findEditPart((DiagramEditor) activeEditor, modelElement);
	}

	public EditPart findEditPart(IDiagramWorkbenchPart editor, EObject modelElement) {
		DiagramEditPart diagram = editor.getDiagramEditPart();
		return findEditPart(diagram, modelElement);
	}

	/**
	 * Get the shape compartment of an edit-part. Fails if the edit-part has no
	 * shape compartment.
	 * 
	 * @param shapeEditPart
	 *            a shape edit part
	 * @return its shape compartment
	 * 
	 * @since 2.2
	 */
	public EditPart getShapeCompartment(EditPart shapeEditPart) {
		return stream(shapeEditPart.getChildren(), EditPart.class)
				.filter(ShapeCompartmentEditPart.class::isInstance)
				.findFirst().orElseGet(failOnAbsence("No shape compartment"));
	}

	/**
	 * Obtain a typed stream over a raw-typed collection from a legacy pre-generics API
	 * such as GEF.
	 * 
	 * @param rawCollection
	 *            a raw-typed collection
	 * @param type
	 *            the expected element type of the collection
	 * @return the typed stream
	 */
	private static <T> Stream<T> stream(@SuppressWarnings("rawtypes") Collection rawCollection, Class<T> type) {
		return ((Collection<?>) rawCollection).stream()
				.filter(type::isInstance).map(type::cast);
	}

	/**
	 * Obtain a fake supplier that just fails the test with the given {@code message}
	 * instead of supplying a result.
	 * 
	 * @param message
	 *            the failure message
	 * @return the fake supplier
	 */
	private static <T> Supplier<T> failOnAbsence(String message) {
		return () -> {
			fail(message);
			return null;
		};
	}

	/**
	 * Find orphan edit part with a type.
	 *
	 * @param type
	 *            the type
	 * @return the edits the part
	 */
	public EditPart findOrphanEditPart(String type) {
		IDiagramWorkbenchPart activeEditor = (IDiagramWorkbenchPart) editor.getActiveEditor();
		EditPart result = null;
		for (Iterator<View> views = Iterators.filter(activeEditor.getDiagram().eAllContents(), View.class); views.hasNext();) {
			View next = views.next();
			EObject element = next.getElement();
			if (element == null && type.equals(next.getType())) {
				result = (EditPart) activeEditor.getDiagramGraphicalViewer().getEditPartRegistry().get(next);
				break;
			}
		}

		return result;

	}

	/**
	 * Find orphan edit part.
	 *
	 * @return the edits the part
	 */
	public EditPart findOrphanEditPart() {
		IDiagramWorkbenchPart activeEditor = (IDiagramWorkbenchPart) editor.getActiveEditor();
		EditPart result = null;
		for (Iterator<View> views = Iterators.filter(activeEditor.getDiagram().eAllContents(), View.class); views.hasNext();) {
			View next = views.next();

			String type = next.getType();
			EObject element = next.getElement();

			if (element == null && !excludedTypeView.contains(type)) {
				result = (EditPart) activeEditor.getDiagramGraphicalViewer().getEditPartRegistry().get(next);
				break;
			}
		}

		return result;

	}

	/**
	 * Find an edit-part for a model element in a particular {@code scope}.
	 * 
	 * @param scope
	 *            an edit part in which to search (its children) for an edit-part
	 * @param modelElement
	 *            the model element visualized by the edit-part to search for
	 * 
	 * @return the matching edit-part, or {@code null} if none is found in the {@code scope}
	 */
	public EditPart findEditPart(EditPart scope, EObject modelElement) {
		EditPart result = null;

		View view = PlatformHelper.getAdapter(scope, View.class);
		if ((view != null) && (view.getElement() == modelElement)) {
			result = scope;
		}

		if (result == null) {
			// Search children
			for (Iterator<?> iter = scope.getChildren().iterator(); (result == null) && iter.hasNext();) {
				result = findEditPart((EditPart) iter.next(), modelElement);
			}
		}

		if ((result == null) && (scope instanceof GraphicalEditPart)) {
			// Search edges
			for (Iterator<?> iter = ((GraphicalEditPart) scope).getSourceConnections().iterator(); (result == null) && iter.hasNext();) {
				result = findEditPart((EditPart) iter.next(), modelElement);
			}
			if (result == null) {
				for (Iterator<?> iter = ((GraphicalEditPart) scope).getTargetConnections().iterator(); (result == null) && iter.hasNext();) {
					result = findEditPart((EditPart) iter.next(), modelElement);
				}
			}
		}

		return result;
	}

	/**
	 * Require an edit-part for a model element in a particular {@code scope}.
	 * 
	 * @param scope
	 *            an edit part in which to search (its children) for an edit-part
	 * @param modelElement
	 *            the model element visualized by the edit-part to search for
	 * 
	 * @return the matching edit-part
	 * 
	 * @throws AssertionError
	 *             if the required edit-part is found in the {@code scope}
	 */
	public EditPart requireEditPart(EditPart scope, EObject modelElement) {
		EditPart result = findEditPart(scope, modelElement);
		if (result == null) {
			String label = getLabel(modelElement);
			fail(String.format("No edit-part found for \"%s\" in %s", label, scope));
		}
		return result;
	}

	public String getLabel(EObject object) {
		String result = null;

		try {
			EditingDomain domain = ServiceUtils.getInstance().getTransactionalEditingDomain(editor.getServicesRegistry());
			if (domain instanceof AdapterFactoryEditingDomain) {
				IItemLabelProvider labels = (IItemLabelProvider) ((AdapterFactoryEditingDomain) domain).getAdapterFactory().adapt(object, IItemLabelProvider.class);
				if (labels != null) {
					result = labels.getText(object);
				}
			}
		} catch (ServiceException e) {
			// Doesn't matter
		}

		if (result == null) {
			result = String.valueOf(object);
		}

		return result;
	}

	public EditPart findEditPart(String name, Class<? extends NamedElement> type) {
		return findEditPart(getActiveDiagramEditor(), name, type);
	}

	/**
	 * @since 2.0
	 */
	public EditPart findEditPart(IMultiDiagramEditor editor, String name, Class<? extends NamedElement> type) {
		IEditorPart activeEditor = editor.getActiveEditor();
		assertThat("No diagram active", activeEditor, instanceOf(DiagramEditor.class));
		return findEditPart((DiagramEditor) activeEditor, name, type);
	}

	public EditPart findEditPart(IDiagramWorkbenchPart editor, String name, Class<? extends NamedElement> type) {
		EditPart result = null;

		for (Iterator<View> views = Iterators.filter(editor.getDiagram().eAllContents(), View.class); views.hasNext();) {
			View next = views.next();
			EObject element = next.getElement();
			if (type.isInstance(element) && name.equals(type.cast(element).getName())) {
				result = (EditPart) editor.getDiagramGraphicalViewer().getEditPartRegistry().get(next);
				break;
			}
		}

		return result;
	}

	public void select(EditPart editPart) {
		editPart.getViewer().getSelectionManager().appendSelection(editPart);
	}

	public void deselect(EditPart editPart) {
		editPart.getViewer().getSelectionManager().deselect(editPart);
	}

	public void move(EditPart editPart, Point newLocation) {
		execute(new ICommandProxy(new SetBoundsCommand(getEditingDomain(), "Move Node", editPart, newLocation)));
	}

	public void resize(EditPart editPart, Dimension newSize) {
		execute(new ICommandProxy(new SetBoundsCommand(getEditingDomain(), "Resize Node", editPart, newSize)));
	}

	public void execute(org.eclipse.gef.commands.Command command) {
		assertThat("No command", command, notNullValue());
		assertThat("Command not executable", command.canExecute(), is(true));
		getActiveDiagramEditor().getDiagramEditDomain().getDiagramCommandStack().execute(command);
		flushDisplayEvents();
	}

	@Override
	public void execute(Command command) {
		super.execute(command);
		flushDisplayEvents();
	}

	@Override
	public IStatus execute(IUndoableOperation operation, IProgressMonitor monitor, IAdaptable info) {
		IStatus result = super.execute(operation, monitor, info);
		flushDisplayEvents();
		return result;
	}

	@Override
	public void undo() {
		super.undo();
		flushDisplayEvents();
	}

	@Override
	public void redo() {
		super.redo();
		flushDisplayEvents();
	}

	public PaletteViewer getPalette() {
		return getPalette(getActiveDiagramEditor());
	}

	/**
	 * @since 2.0
	 */
	public PaletteViewer getPalette(IMultiDiagramEditor editor) {
		IEditorPart activeEditor = editor.getActiveEditor();
		assertThat("No diagram active", activeEditor, instanceOf(DiagramEditor.class));
		return getPalette((DiagramEditor) activeEditor);
	}

	public PaletteViewer getPalette(IDiagramWorkbenchPart editor) {
		return editor.getDiagramEditPart().getViewer().getEditDomain().getPaletteViewer();
	}

	public void flushDisplayEvents() {
		for (;;) {
			try {
				if (Display.getCurrent() != null && !Display.getCurrent().readAndDispatch()) {
					break;
				}
			} catch (Exception e) {
				Bundle testBundle = FrameworkUtil.getBundle((testClass == null) ? PapyrusEditorFixture.class : testClass);
				Platform.getLog(testBundle).log(new Status(IStatus.ERROR, testBundle.getSymbolicName(), "Uncaught exception in display runnable.", e));
			}
		}
	}

	public IViewPart getView(String id, boolean open) {
		IViewPart result = null;

		IWorkbenchPage wbPage = getWorkbenchPage();

		try {
			result = wbPage.findView(id);
			if ((result == null) && open) {
				result = wbPage.showView(id);
			}

			if (result != null) {
				result.getSite().getPage().activate(result);
				flushDisplayEvents();
			}
		} catch (PartInitException e) {
			e.printStackTrace();
			fail("Failed to show a view: " + id);
		} finally {
			flushDisplayEvents();
		}

		return result;
	}

	public void save() {
		save(getEditor());
	}

	public void save(ISaveablePart part) {
		if (part.isDirty()) {
			try {
				part.doSave(new NullProgressMonitor());
			} catch (Exception e) {
				e.printStackTrace();
				fail("Failed to save editor/view: " + e.getLocalizedMessage());
			} finally {
				// Must flush display events because some steps (e.g. dependent editor reload)
				// are done asynchronously in a UI job
				flushDisplayEvents();
			}
		}
	}

	public void saveAll() {
		try {
			IWorkbenchPage page = editor.getSite().getPage();
			page.saveAllEditors(false);
		} finally {
			// Must flush display events because some steps (e.g. dependent editor reload)
			// are done asynchronously in a UI job
			flushDisplayEvents();
		}
	}

	public void splitEditorArea(IEditorPart editorToMove, boolean splitHorizontally) {
		MPart editorPart = editorToMove.getSite().getService(MPart.class);
		EModelService modelService = editorPart.getContext().get(EModelService.class);
		MPartStack oldStack = (MPartStack) modelService.getContainer(editorPart);
		MPartStack newStack = modelService.createModelElement(MPartStack.class);
		modelService.insert(newStack, oldStack, splitHorizontally ? EModelService.RIGHT_OF : EModelService.BELOW, 0.5f);
		newStack.getChildren().add(editorPart);

		activate(editorToMove);
	}

	public List<IWorkbenchPart> getPartStack(IWorkbenchPart part) {
		List<IWorkbenchPart> result;

		MPart mpart = part.getSite().getService(MPart.class);
		EModelService modelService = mpart.getContext().get(EModelService.class);
		MPartStack stack = (MPartStack) modelService.getContainer(mpart);

		result = Lists.newArrayListWithCapacity(stack.getChildren().size());
		for (MPart next : Iterables.filter(stack.getChildren(), MPart.class)) {
			IWorkbenchPart wbPart = next.getContext().get(IWorkbenchPart.class);
			if (wbPart != null) {
				result.add(wbPart);
			}
		}

		return result;
	}

	protected final boolean hasRequiredViews() {
		return getRequiredViews() != null;
	}

	protected final ShowView getRequiredViews() {
		ShowView result = testDescription.getAnnotation(ShowView.class);

		if (result == null) {
			for (Class<?> clazz = testClass; (result == null) && (clazz != null) && (clazz != Object.class); clazz = clazz.getSuperclass()) {
				result = clazz.getAnnotation(ShowView.class);
			}
		}

		return result;
	}

	protected void openRequiredViews() {
		IWorkbenchPage page = getWorkbenchPage();

		for (ShowViewDescriptor next : ShowViewDescriptor.getDescriptors(getRequiredViews())) {
			IViewPart part = page.findView(next.viewID());
			if (part == null) {
				// Must open it
				try {
					part = page.showView(next.viewID());
					movePartRelativeTo(part, next.relativeTo(), next.location());

					if (viewsToClose == null) {
						viewsToClose = Lists.newArrayListWithExpectedSize(1);
					}
					viewsToClose.add(part);
				} catch (PartInitException e) {
					e.printStackTrace();
					fail("Failed to open required view: " + e.getLocalizedMessage());
				}
			}
		}

		flushDisplayEvents();
	}

	private void movePartRelativeTo(IWorkbenchPart part, String relativeTo, int where) {
		MPart mPart = part.getSite().getService(MPart.class);
		EModelService modelService = mPart.getContext().get(EModelService.class);
		MUIElement relativePart = modelService.find(relativeTo, modelService.getTopLevelWindowFor(mPart));
		if (relativePart instanceof MPartSashContainerElement) {
			MStackElement toMove = mPart;
			MPlaceholder placeHolder = mPart.getCurSharedRef();
			if (placeHolder != null) {
				toMove = placeHolder;
			}

			if (where < 0) {
				// Add it to the relative part's containing stack
				if (relativePart instanceof MPart) {
					MPart relativeMPart = (MPart) relativePart;
					if (relativeMPart.getCurSharedRef() != null) {
						// This is where the part is stacked
						relativePart = relativeMPart.getCurSharedRef();
					}
				}
				relativePart.getParent().getChildren().add(toMove);
			} else {
				// Insert it next to the relative part
				MPartStack newStack = modelService.createModelElement(MPartStack.class);
				newStack.getChildren().add(toMove);
				modelService.insert(newStack, (MPartSashContainerElement) relativePart, where, 0.3f);
			}
		}
	}

	protected void closeRequiredViews() {
		// Only close the Palette view if we opened it
		if (viewsToClose != null) {
			for (IViewPart closeMe : viewsToClose) {
				closeMe.getSite().getPage().hideView(closeMe);
			}
			viewsToClose = null;
			flushDisplayEvents();
		}
	}

	private static final class ShowViewDescriptor {

		private static final String DEFAULT_RELATIVE_TO = "org.eclipse.ui.editorss"; //$NON-NLS-1$

		private static final ShowView.Location DEFAULT_LOCATION_EDITORS = ShowView.Location.RIGHT;

		private static final ShowView.Location DEFAULT_LOCATION_VIEW = ShowView.Location.STACKED;

		private final String viewID;

		private final String relativeTo;

		private final ShowView.Location location;

		private ShowViewDescriptor(ShowView annotation, int index) {
			this.viewID = annotation.value()[index];

			String[] relativeTo = annotation.relativeTo();
			this.relativeTo = (relativeTo.length == 0) ? null : (relativeTo.length == 1) ? relativeTo[0] : relativeTo[index];

			ShowView.Location[] location = annotation.location();
			this.location = (location.length == 0) ? null : (location.length == 1) ? location[0] : location[index];
		}

		static Iterable<ShowViewDescriptor> getDescriptors(final ShowView annotation) {
			ImmutableList.Builder<ShowViewDescriptor> result = ImmutableList.builder();

			String[] ids = annotation.value();
			for (int i = 0; i < ids.length; i++) {
				result.add(new ShowViewDescriptor(annotation, i));
			}

			return result.build();
		}

		String viewID() {
			return viewID;
		}

		String relativeTo() {
			return (relativeTo != null) ? relativeTo : DEFAULT_RELATIVE_TO;
		}

		int location() {
			return ((location != null) ? location : (relativeTo == null) ? DEFAULT_LOCATION_EDITORS : DEFAULT_LOCATION_VIEW).toModelServiceLocation();
		}
	}

	public PreferencesHint getPreferencesHint() {
		PreferencesHint result = PreferencesHint.USE_DEFAULTS;

		if (activeDiagramEditor != null) {
			RootEditPart rootEditPart = activeDiagramEditor.getDiagramGraphicalViewer().getRootEditPart();
			if (rootEditPart instanceof IDiagramPreferenceSupport) {
				result = ((IDiagramPreferenceSupport) rootEditPart).getPreferencesHint();
			}
		}

		return result;
	}

	/**
	 * @since 2.0
	 */
	public void ensurePapyrusPerspective() {
		Display.getDefault().syncExec(new Runnable() {

			@Override
			public void run() {
				final String papyrus = "org.eclipse.papyrus.infra.core.perspective"; //$NON-NLS-1$
				final IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				IPerspectiveDescriptor perspective = activePage.getPerspective();
				if (!papyrus.equals(perspective.getId())) {
					perspective = PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(papyrus);
					if (perspective != null) {
						activePage.setPerspective(perspective);
						flushDisplayEvents();
					}
				}
			}
		});
	}

	/**
	 * Create a new shape in the {@code parent}. Fails if the shape cannot be created or
	 * cannot be found in the diagram after creation.
	 * 
	 * @param parent
	 *            the parent edit-part in which to create a shape
	 * @param type
	 *            the type of shape to create
	 * @param location
	 *            the location (mouse pointer) at which to create the shape
	 * @param size
	 *            the size of the shape to create
	 * @return the newly created shape edit-part
	 * 
	 * @since 2.2
	 */
	public EditPart createShape(EditPart parent, IElementType type, Point location, Dimension size) {
		CreateViewRequest request = CreateViewRequestFactory.getCreateShapeRequest(type, ((IGraphicalEditPart) parent).getDiagramPreferencesHint());

		// Collect existing children
		Set<EditPart> initialChildren = stream(parent.getChildren(), EditPart.class).collect(Collectors.toSet());
		request.setLocation(location);
		request.setSize(size);
		org.eclipse.gef.commands.Command command = parent.getCommand(request);
		execute(command);

		// Find the new edit-part
		Set<EditPart> children = stream(parent.getChildren(), EditPart.class).collect(Collectors.toSet());
		return Sets.difference(children, initialChildren).stream()
				.filter(ep -> ep.getModel() instanceof Shape)
				.findAny().orElseGet(failOnAbsence("Could not find new shape edit-part"));
	}

	/**
	 * Create a point location (useful as a static import for test readability).
	 * 
	 * @param x
	 *            the x coördinate
	 * @param y
	 *            the y coördinate
	 * @return the point
	 * 
	 * @since 2.2
	 */
	public static Point at(int x, int y) {
		return new Point(x, y);
	}

	/**
	 * Create a size dimension (useful as a static import for test readability).
	 * 
	 * @param width
	 *            the size width
	 * @param height
	 *            the the size height
	 * @return the size
	 * 
	 * @since 2.2
	 */
	public static Dimension sized(int width, int height) {
		return new Dimension(width, height);
	}

	/**
	 * Delete an edit-part from the diagram.
	 * 
	 * @param editPart
	 *            the edit-part to delete
	 * 
	 * @since 2.2
	 */
	public void delete(EditPart editPart) {
		EObject toDestroy = editPart.getAdapter(EObject.class);
		EObject container = toDestroy.eContainer();
		DestroyElementRequest request = new DestroyElementRequest(toDestroy, false);
		IElementEditService edit = ElementEditServiceUtils.getCommandProvider(container);
		ICommand delete = edit.getEditCommand(request);

		assertThat("No delete command obtained", delete, notNullValue());
		execute(delete);
	}
}

Back to the top