Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 1e71b42040d6e4507f7b20d0543c45b04e3f3d17 (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
/*****************************************************************************
 * Copyright (c) 2010, 2015 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:
 *  Camille Letavernier (CEA LIST) camille.letavernier@cea.fr - Initial API and implementation
 *  Christian W. Damus (CEA) - Factor out workspace storage for pluggable storage providers (CDO)
 *  Christian W. Damus (CEA) - Support implicit enablement of prototypes of unavailable contexts (CDO)
 *  Christian W. Damus - bug 482930
 *  Christian W. Damus - bug 469188
 *  Nicolas FAUVERGUE (CEA LIST) nicolas.fauvergue@cea.fr - Bug 527001
 *****************************************************************************/
package org.eclipse.papyrus.views.properties.runtime;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.osgi.util.NLS;
import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
import org.eclipse.papyrus.infra.properties.contexts.Context;
import org.eclipse.papyrus.infra.properties.contexts.ContextsFactory;
import org.eclipse.papyrus.infra.properties.contexts.DataContextElement;
import org.eclipse.papyrus.infra.properties.contexts.Property;
import org.eclipse.papyrus.infra.properties.contexts.Section;
import org.eclipse.papyrus.infra.properties.contexts.Tab;
import org.eclipse.papyrus.infra.properties.environment.CompositeWidgetType;
import org.eclipse.papyrus.infra.properties.environment.Environment;
import org.eclipse.papyrus.infra.properties.environment.EnvironmentPackage;
import org.eclipse.papyrus.infra.properties.environment.LayoutType;
import org.eclipse.papyrus.infra.properties.environment.Namespace;
import org.eclipse.papyrus.infra.properties.environment.PropertyEditorType;
import org.eclipse.papyrus.infra.properties.environment.StandardWidgetType;
import org.eclipse.papyrus.infra.properties.environment.Type;
import org.eclipse.papyrus.infra.properties.environment.WidgetType;
import org.eclipse.papyrus.infra.properties.internal.ContextExtensionPoint;
import org.eclipse.papyrus.infra.properties.internal.EnvironmentExtensionPoint;
import org.eclipse.papyrus.infra.properties.internal.ui.extensions.ContextBindingsExtensionPoint;
import org.eclipse.papyrus.infra.properties.internal.ui.runtime.ConfigurationConflict;
import org.eclipse.papyrus.infra.properties.internal.ui.runtime.IInternalConfigurationManager;
import org.eclipse.papyrus.infra.properties.ui.runtime.ViewConstraintEngine;
import org.eclipse.papyrus.infra.properties.ui.runtime.ViewConstraintEngineImpl;
import org.eclipse.papyrus.infra.properties.ui.util.PropertiesUtil;
import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder;
import org.eclipse.papyrus.views.properties.Activator;
import org.eclipse.papyrus.views.properties.root.PropertiesRoot;
import org.eclipse.papyrus.views.properties.root.RootFactory;
import org.eclipse.papyrus.views.properties.runtime.preferences.ContextDescriptor;
import org.eclipse.papyrus.views.properties.runtime.preferences.Preferences;
import org.eclipse.papyrus.views.properties.runtime.preferences.PreferencesFactory;
import org.eclipse.papyrus.views.properties.runtime.preferences.PreferencesPackage;
import org.eclipse.papyrus.views.properties.storage.ContextStorageRegistry;
import org.eclipse.papyrus.views.properties.storage.IContextStorageProvider;
import org.eclipse.papyrus.views.properties.storage.IContextStorageProviderListener;
import org.eclipse.swt.widgets.Display;

/**
 * Central class of the Property View framework. It lists the available environments and contexts,
 * and is responsible for Enabling or Disabling contexts programmatically.
 *
 * All {@link Context}s should have unique names.
 *
 * @see ContextExtensionPoint
 * @see EnvironmentExtensionPoint
 * @see Preferences
 * @see ConfigurationManager#instance
 *
 * @author Camille Letavernier
 */
public class ConfigurationManager implements IInternalConfigurationManager {

	/**
	 * The unique identifier of the default preference page, covering the <b>Properties View</b>.
	 */
	private static final String DEFAULT_VIEW_ID = "org.eclipse.papyrus.views.properties.propertyview"; //$NON-NLS-1$

	private final Preferences preferences;

	private final PropertiesRoot root;

	private final ResourceSet resourceSet = new ResourceSetImpl();

	private boolean started = false;

	/**
	 * All contexts (Whether they are applied or not)
	 */
	private final Map<URI, Context> contexts;

	private final Set<Context> enabledContexts;

	private final Map<Context, Boolean> customizableContexts;

	private final ContextStorageRegistry contextStorageRegistry;

	private IContextStorageProviderListener contextStorageProviderListener;

	/** Map of preference page identifier to context unique identifiers. */
	private final Map<String, Set<String>> preferencePageBindings;

	/**
	 * The global constraint engine
	 */
	private ViewConstraintEngine constraintEngine;

	/**
	 * The singleton instance
	 */
	private final static ConfigurationManager instance = new ConfigurationManager();

	public static ConfigurationManager getInstance() {
		synchronized (instance) {
			if (!instance.started) {
				instance.start();
			}
		}
		return instance;
	}

	private ConfigurationManager() {
		constraintEngine = new ViewConstraintEngineImpl(this);
		enabledContexts = new LinkedHashSet<Context>();
		customizableContexts = new HashMap<Context, Boolean>();
		contexts = new LinkedHashMap<URI, Context>();
		contextStorageRegistry = new ContextStorageRegistry(resourceSet);
		preferencePageBindings = new HashMap<>();

		root = RootFactory.eINSTANCE.createPropertiesRoot();

		preferences = loadPreferences();
	}

	private void start() {
		if (started) {
			return;
		}

		started = true;

		new ContextExtensionPoint(this::addContext);
		new EnvironmentExtensionPoint(this::addEnvironment);
		new ContextBindingsExtensionPoint(this::registerPreferencePageBinding);

		loadCustomContexts();

		// now that we have loaded the custom contexts, we can migrate the preferences from a
		// previous version (if required)
		if (new PreferencesMigrator(this).process(preferences)) {
			savePreferences();
		}
	}

	private EObject loadEMFModel(URI sourceURI) throws IOException {
		return EMFHelper.loadEMFModel(resourceSet, sourceURI);
	}

	private Preferences loadPreferences() {
		IPath path = Activator.getDefault().getPreferencesPath();
		String preferencesPath = path.toString() + "/preferences.xmi"; //$NON-NLS-1$
		URI preferencesURI = URI.createFileURI(preferencesPath);

		try {
			EObject model = loadEMFModel(preferencesURI);
			if (model != null && model instanceof Preferences) {
				return (Preferences) model;
			}
		} catch (Exception ex) {
			// File not found : we ignore the exception //TODO : improve the exceptions (FileNotFound is not the only one that can occur)
		}

		// If we're here, then the preferences.xmi doesn't exist or isn't valid : we create it

		return createPreferences(preferencesURI);
	}

	private Preferences createPreferences(URI preferencesURI) {
		Preferences preferencesStore = PreferencesFactory.eINSTANCE.createPreferences();
		preferencesStore.setVersion(Preferences.CURRENT_VERSION);

		Resource resource = resourceSet.createResource(preferencesURI);
		resource.getContents().add(preferencesStore);
		saveModel(preferencesStore);

		return preferencesStore;
	}

	private void loadCustomContexts() {
		for (IContextStorageProvider provider : contextStorageRegistry.getStorageProviders()) {
			// discover initial contexts
			try {
				for (Context context : provider.loadContexts()) {
					addContext(context, findDescriptor(context).isApplied(), true);
				}
			} catch (CoreException ex) {
				// Silent : The file has been removed from the preferences, but the folder still exists
			}

			// listen for changes
			provider.addContextStorageProviderListener(getContextStorageProviderListener());
		}
	}

	private IContextStorageProviderListener getContextStorageProviderListener() {
		if (contextStorageProviderListener == null) {
			contextStorageProviderListener = new IContextStorageProviderListener() {

				@Override
				public void contextsAdded(Collection<? extends Context> contexts) {
					List<Context> appliedContexts = new java.util.ArrayList<Context>(contexts.size());

					for (Context next : contexts) {
						boolean applied = findDescriptor(next).isApplied();

						addContext(next, applied, true);

						if (applied) {
							appliedContexts.add(next);
						}
					}

					if (!appliedContexts.isEmpty()) {
						notifyContextChanges(appliedContexts, ContextEventType.ADDED);
					}
				}

				@Override
				public void contextsChanged(Collection<? extends Context> contexts) {
					List<Context> appliedContexts = new java.util.ArrayList<Context>(contexts.size());

					for (Context next : contexts) {
						boolean applied = findDescriptor(next).isApplied();

						reloadContext(next);

						if (applied) {
							appliedContexts.add(next);
						}
					}

					if (!appliedContexts.isEmpty()) {
						notifyContextChanges(appliedContexts, ContextEventType.CHANGED);
					}
				}

				@Override
				public void contextsRemoved(Collection<? extends Context> contexts) {
					List<Context> appliedContexts = new java.util.ArrayList<Context>(contexts.size());

					for (Context next : contexts) {
						boolean wasApplied = findDescriptor(next).isApplied();

						// don't update the preferences on the expectation that this context
						// is only temporarily unavailable
						deleteContext(next, false);

						if (wasApplied) {
							appliedContexts.add(next);
						}
					}

					if (!appliedContexts.isEmpty()) {
						notifyContextChanges(appliedContexts, ContextEventType.REMOVED);
					}
				}
			};
		}

		return contextStorageProviderListener;
	}

	private void notifyContextChanges(Collection<Context> contexts, IContextStorageProviderListener.ContextEventType eventType) {
		if (contexts.size() == 0) {
			throw new IllegalArgumentException("Empty contexts collection");
		}

		StringBuilder list = new StringBuilder();
		Iterator<Context> iter = contexts.iterator();
		if (contexts.size() > 1) {
			list.append("\n");
		}
		list.append(iter.next().getName());
		while (iter.hasNext()) {
			list.append("\n");
			list.append(iter.next().getName());
		}

		String pattern;
		switch (eventType) {
		case ADDED:
			pattern = "New Properties View configurations have been applied: {0}";
			break;
		case REMOVED:
			pattern = "Properties View configurations are no longer available: {0}";
			break;
		default:
			pattern = "Properties View configurations have changed: {0}";
			break;
		}
		final String message = NLS.bind(pattern, list);

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

			@Override
			public void run() {
				NotificationBuilder.createAsyncPopup(message).setType(org.eclipse.papyrus.infra.widgets.toolbox.notification.Type.INFO).setDelay(5000L).run();
			}
		});

	}

	/**
	 * Refresh the given Context. This method should be called when a model is edited
	 * at runtime, to re-load it from persistent storage.
	 *
	 * @param context
	 *            A Context model to re-load
	 */
	@Override
	public void refresh(Context context) {
		IContextStorageProvider provider = contextStorageRegistry.getStorageProvider(context);
		if (provider != null) {
			try {
				provider.refreshContext(context);
				reloadContext(context);
			} catch (CoreException e) {
				Activator.getDefault().getLog().log(e.getStatus());
			}
		}
	}

	private void reloadContext(Context context) {
		// TODO : get the right URI from the context file :
		// ppe:/context/<plugin>/<path> if it is in the workspace,
		// ppe:/context/<preferences>/<path> if it is registered through
		// preferences

		URI contextURI = EcoreUtil.getURI(context);

		if (contexts.containsKey(contextURI)) {
			// Unloads the previous objects corresponding to this context
			Context previousContext = contexts.get(contextURI);
			enabledContexts.remove(previousContext);
			previousContext.eResource().unload();

			// Adds the new object corresponding to this context
			try {
				addContext(contextURI);
				constraintEngine.refresh();
			} catch (IOException ex) {
				Activator.log.error(ex);
			}
		}
	}

	/**
	 * Tests if a Context is enabled.
	 *
	 * @param context
	 * @return
	 * 		true if the given context is enabled.
	 *
	 * @see Preferences
	 */
	@Override
	public boolean isApplied(Context context) {
		boolean result = !isCustomizable(context) || findDescriptor(context).isApplied();

		if (!result) {
			// see whether perhaps there's an active descriptor for a missing context that
			// is based on this context
			@SuppressWarnings("serial")
			EcoreUtil.CrossReferencer xrefs = new EcoreUtil.CrossReferencer(preferences) {

				{
					crossReference();
					done();
				}

				@Override
				protected boolean crossReference(EObject eObject, EReference eReference, EObject crossReferencedEObject) {
					return eReference == PreferencesPackage.Literals.CONTEXT_DESCRIPTOR__PROTOTYPE;
				}
			};

			// breadth-first search for a copied context that is enabled but missing, where
			// no other traceable copy is enabled and accessible
			Queue<ContextDescriptor> queue = new java.util.LinkedList<ContextDescriptor>();
			Set<ContextDescriptor> cycleDetect = new java.util.HashSet<ContextDescriptor>();
			queue.offer(findDescriptor(context));
			out: while (!queue.isEmpty()) {
				ContextDescriptor desc = queue.remove();
				Collection<EStructuralFeature.Setting> refs = xrefs.get(desc);
				if ((refs != null) && cycleDetect.add(desc)) {
					for (EStructuralFeature.Setting ref : refs) {
						ContextDescriptor copy = (ContextDescriptor) ref.getEObject();
						if (copy.isApplied()) {
							if (getContext(copy.getName()) == null) {
								// it's an applied context that is missing. That's what we're looking for
								result = true;
							} else {
								// it's an applied context that is *not* missing. So, it is in effect
								// and the prototype should not implicitly be enabled
								result = false;
								break out;
							}
						} else {
							// enqueue for searching further copies
							queue.offer(copy);
						}
					}
				}
			}
		}

		return result;
	}

	/**
	 * Retrieves the ContextDescriptor associated to the specified context.
	 * If a matching descriptor cannot be found, a new Descriptor is created
	 * in the preferences.
	 *
	 * @param context
	 * @return
	 */
	private ContextDescriptor findDescriptor(Context context) {
		if (context.getName() == null || context.getName().equals("")) { //$NON-NLS-1$
			return null;
		}

		for (ContextDescriptor descriptor : preferences.getContexts()) {
			if (descriptor.getName().equals(context.getName())) {
				return descriptor;
			}
		}
		// The descriptor hasn't been found : We create it

		ContextDescriptor descriptor = PreferencesFactory.eINSTANCE.createContextDescriptor();
		descriptor.setName(context.getName());
		preferences.getContexts().add(descriptor);
		savePreferences();
		return descriptor;
	}

	/**
	 * Return true if the context has a desciptor.
	 *
	 * @param context
	 * @return
	 */
	private boolean hasDescriptor(Context context) {
		Boolean value = false;

		if ((context.getName() != null && !context.getName().equals(""))) { //$NON-NLS-1$

			Iterator<ContextDescriptor> contextIterator = preferences.getContexts().iterator();
			while (contextIterator.hasNext() && !value) {
				if (contextIterator.next().getName().equals(context.getName())) {
					value = true;
				}
			}
		}
		return value;
	}

	/**
	 * Adds a context via its URI. The URI should represent a valid Context model.
	 * The model is loaded in the ConfigurationManager's resourceSet.
	 *
	 * @param uri
	 *            The context's URI
	 * @param customizable
	 *            if is customizable
	 * @throws IOException
	 *             If the model behind this URI is not a valid Context
	 */
	public void addContext(URI uri, boolean customizable) throws IOException {
		addContext(uri, true, customizable);
	}

	/**
	 * Adds a context via its URI. The URI should represent a valid Context model.
	 * The model is loaded in the ConfigurationManager's resourceSet.
	 *
	 * @param uri
	 *            The context's URI
	 * @param appliedByDefault
	 *            if is applied by default
	 * @param customizable
	 *            if is customizable
	 * @throws IOException
	 *             If the model behind this URI is not a valid Context
	 */
	public void addContext(URI uri, boolean appliedByDefault, boolean customizable) throws IOException {
		EObject firstRootObject = loadEMFModel(uri);

		if (firstRootObject != null) {
			for (EObject rootObject : firstRootObject.eResource().getContents()) {
				if (rootObject instanceof Context) {
					Context context = (Context) rootObject;
					addContext(context, hasDescriptor(context) ? findDescriptor(context).isApplied() : appliedByDefault, customizable);

					findDescriptor(context).setAppliedByDefault(appliedByDefault);
				}
			}
		}
	}

	@Override
	public Boolean isAppliedByDefault(Context context) {
		return findDescriptor(context).isAppliedByDefault();
	}

	/**
	 * Adds a context via its URI. The URI should represent a valid Context model.
	 * The model is loaded in the ConfigurationManager's resourceSet.
	 *
	 * @param uri
	 *            The context's URI
	 * @throws IOException
	 *             If the model behind this URI is not a valid Context
	 */
	@Override
	public void addContext(URI uri) throws IOException {
		addContext(uri, true, true);
	}

	/**
	 * Programmatically register a new context to this ConfigurationManager.
	 * Most of the time, new contexts should be registered through {@link ContextExtensionPoint}.
	 * However, you can still call this method when creating a Context at runtime, programmatically
	 * (Wizards, ...)
	 * All {@link Context} should have unique names
	 *
	 * @param context
	 *            The new context to register
	 * @param apply
	 *            Whether the context should be enabled or not
	 *
	 * @see ConfigurationManager#addContext(URI)
	 */
	@Override
	public void addContext(Context context, boolean apply) {
		addContext(context, apply, true);
	}

	/**
	 * Recalculates the cached preference descriptor prototype of the specified {@code context}.
	 * This ensures that if the {@code context} becomes unavailable, we will still know locally
	 * in this workspace what its prototype is.
	 *
	 * @param context
	 *            a context
	 */
	private void updatePrototype(Context context) {
		Context prototype = context.getPrototype();
		if ((prototype == null) || !prototype.eIsProxy()) {
			// it has no prototype or the prototype is available? Cache in the preferences
			ContextDescriptor desc = findDescriptor(context);
			ContextDescriptor oldPrototype = desc.getPrototype();

			desc.setPrototype((prototype == null) ? null : findDescriptor(prototype));

			if (desc.getPrototype() != oldPrototype) {
				savePreferences();
			}
		}
	}

	/**
	 * Programmatically register a new context to this ConfigurationManager.
	 * Most of the time, new contexts should be registered through {@link ContextExtensionPoint}.
	 * However, you can still call this method when creating a Context at runtime, programmatically
	 * (Wizards, ...)
	 * All {@link Context} should have unique names
	 *
	 * @param context
	 *            The new context to register
	 * @param apply
	 *            Whether the context should be enabled or not
	 *
	 * @see ConfigurationManager#addContext(URI)
	 */
	public void addContext(Context context, boolean apply, boolean isCustomizable) {

		URI contextURI = EcoreUtil.getURI(context);
		if (contexts.containsKey(contextURI)) {
			throw new IllegalArgumentException("This properties view configuration is already deployed");
		}

		customizableContexts.put(context, isCustomizable);
		contexts.put(contextURI, context);

		updatePrototype(context);

		ContextDescriptor desc = findDescriptor(context);
		if (desc.isDeleted()) {
			desc.setDeleted(false); // can't be deleted any longer
			savePreferences();
		}

		// If the context is not customizable, then it must always be applied
		if (apply || !isCustomizable) {
			enableContext(context, true);
		} else {
			disableContext(context, true);
		}

		// as we have added a new context, it may be an applied copy of some
		// other context that was implicitly enabled because of the missing copy
		reconcileEnabledContexts();
	}

	/**
	 * @return the list of <strong>enabled</strong> contexts
	 */
	@Override
	public Collection<Context> getEnabledContexts() {
		return enabledContexts;
	}

	/**
	 * Disable a Context.
	 *
	 * @param context
	 *            The Context to disable
	 * @param update
	 *            If true, the constraint engine will be updated to handle the
	 *            modification
	 *            If false, you should call manually {@link #update()} to refresh
	 *            the constraint engine
	 * @see Preferences
	 * @see #enableContext(Context, boolean)
	 */
	@Override
	public void disableContext(Context context, boolean update) {
		disableContext(context, update, true);
	}

	private void disableContext(Context context, boolean updateEngine, boolean updatePreferences) {
		final boolean missing = isMissing(context);

		if (!missing && !isCustomizable(context)) {
			throw new IllegalStateException("Non-customizable contexts cannot be disabled. Trying to disable " + context.getName());
		}

		// even if it's missing, make sure it's not in the enabledContexts set!
		updateEngine = enabledContexts.remove(context) && updateEngine;

		// Update the preferences if requested
		ContextDescriptor descriptor = findDescriptor(context);
		if (updatePreferences && descriptor.isApplied()) {
			descriptor.setApplied(false);
			savePreferences();
		}

		if (updateEngine) {
			// Update the Engine
			update();
		}
	}

	/**
	 * Enables a Context
	 *
	 * @param context
	 *            The Context to enable
	 * @param update
	 *            If true, the constraint engine will be updated to handle the
	 *            modification
	 *            If false, you should call manually {@link #update()} to refresh
	 *            the constraint engine
	 *
	 * @see #disableContext(Context, boolean)
	 */
	@Override
	public void enableContext(Context context, boolean update) {
		enableContext(context, update, true);
	}

	private void enableContext(Context context, boolean updateEngine, boolean updatePreferences) {
		final boolean missing = isMissing(context);

		if (!missing) {
			enabledContexts.add(context);
		}

		// Update the preferences if requested
		ContextDescriptor descriptor = findDescriptor(context);
		if (updatePreferences && !descriptor.isApplied()) {
			descriptor.setApplied(true);
			savePreferences();
		}

		if (updateEngine && !missing) {
			// Update the Engine
			constraintEngine.addContext(context);
		}
	}

	/**
	 * Queries whether a given context is {@linkplain #getEnabledContexts() enabled}.
	 * 
	 * @param context
	 *            a context
	 * @return whether it is currently enabled
	 * 
	 * @see #getEnabledContexts()
	 */
	@Override
	public boolean isEnabled(Context context) {
		return enabledContexts.contains(context);
	}

	/**
	 * Tests if a Context is a plugin context. plugin contexts
	 * are registered through {@link ContextExtensionPoint} and are
	 * read-only.
	 *
	 * @param context
	 * @return
	 * 		True if the context comes from a plugin, and is thus read-only
	 */
	@Override
	public boolean isPlugin(Context context) {
		// a missing context can't be a plug-in context because plug-ins can't go missing
		boolean result = !isMissing(context) && contextStorageRegistry.getStorageProvider(context) == IContextStorageProvider.NULL;
		return result;
	}

	/**
	 * Queries whether the specified {@code context} is a proxy for a missing context. That is a
	 * context that is expected to exist but is (temporarily) unavailable.
	 *
	 * @param context
	 *            a context
	 * @return whether it represents a missing context
	 */
	@Override
	public boolean isMissing(Context context) {
		return !contexts.containsValue(context) && !findDescriptor(context).isDeleted();
	}

	/**
	 * Loads a Context from the given URI. The model is loaded in the {@link ConfigurationManager}'s resourceSet
	 *
	 * @param uri
	 *            The URI from which the Context is loaded
	 * @return
	 * 		The loaded context
	 * @throws IOException
	 *             If the URI doesn't represent a valid Context model
	 */
	@Override
	public Context getContext(URI uri) throws IOException {
		return (Context) loadEMFModel(uri);
	}

	private void addEnvironment(Environment environment) {
		root.getEnvironments().add(environment);
	}

	/**
	 * Adds a new Environment from the given URI.
	 *
	 * @param uri
	 *            The URI from which the Environment is retrieved.
	 * @throws IOException
	 *             if the URI doesn't represent a valid Environment model
	 */
	public void addEnvironment(URI uri) throws IOException {
		Environment environment = (Environment) loadEMFModel(uri);
		addEnvironment(environment);
	}

	/**
	 * @return
	 * 		The PropertiesRoot for the Property view framework. The PropertiesRoot contains
	 *         all registered Environments and Contexts (Whether they are enabled or disabled)
	 */
	public PropertiesRoot getPropertiesRoot() {
		return root;
	}

	/**
	 * Returns the context from the given context name
	 *
	 * @param contextName
	 *            The name of the context to retrieve
	 * @return
	 * 		The context corresponding to the given name
	 */
	@Override
	public Context getContext(String contextName) {
		for (Context context : getContexts()) {
			if (context.getName().equals(contextName)) {
				return context;
			}
		}
		return null;
	}

	private void savePreferences() {
		saveModel(preferences);
	}

	private void saveModel(EObject eObject) {
		try {
			eObject.eResource().save(Collections.EMPTY_MAP);
		} catch (IOException ex) {
			Activator.log.error(ex);
		}
	}

	/**
	 * Returns all the known contexts, even if they are not applied
	 * To get only applied contexts, see {@link #getEnabledContexts()}
	 *
	 * @return All known contexts
	 *
	 * @see PropertiesRoot#getContexts()
	 */
	@Override
	public Collection<Context> getContexts() {
		return contexts.values();
	}

	/**
	 * Returns all the known customizable contexts.
	 *
	 * @return All known contexts
	 *
	 * @see PropertiesRoot#getContexts()
	 * @see {@link #getEnabledContexts()}
	 */
	@Override
	public Collection<Context> getCustomizableContexts() {
		List<Context> result = new LinkedList<Context>();
		for (Context context : contexts.values()) {
			if (isCustomizable(context)) {
				result.add(context);
			}
		}
		return result;
	}

	/**
	 * Obtains proxies (not the EMF kind) for all contexts that the system knows about
	 * but are currently unavailable.
	 *
	 * @return the current collection of missing contexts
	 */
	@Override
	public Collection<Context> getMissingContexts() {
		List<Context> result = new java.util.ArrayList<Context>();

		for (ContextDescriptor next : preferences.getContexts()) {
			if (!next.isDeleted() && (getContext(next.getName()) == null)) {
				Context missing = ContextsFactory.eINSTANCE.createContext();
				missing.setName(next.getName());
				result.add(missing);
			}
		}

		return result;
	}

	private <T extends WidgetType> T getDefaultWidget(int featureID, Class<T> theClass, String widgetName, String namespacePrefix) {
		EStructuralFeature feature = EnvironmentPackage.Literals.ENVIRONMENT.getEStructuralFeature(featureID);
		for (Environment environment : root.getEnvironments()) {
			@SuppressWarnings("unchecked")
			T widget = findWidgetTypeByClassName((EList<T>) environment.eGet(feature), widgetName, namespacePrefix);
			if (widget != null) {
				return widget;
			}
		}
		return null;
	}


	private <T extends WidgetType> T findWidgetTypeByClassName(Collection<T> types, String className, String namespacePrefix) {
		for (T widgetType : types) {
			if (widgetType.getWidgetClass().equals(className) && PropertiesUtil.namespaceEqualsByName(widgetType.getNamespace(), namespacePrefix)) {
				return widgetType;
			}
		}
		return null;
	}

	/**
	 * @return the default implementation of CompositeWidgetType
	 */
	@Override
	public CompositeWidgetType getDefaultCompositeType() {
		return getDefaultWidget(EnvironmentPackage.ENVIRONMENT__COMPOSITE_WIDGET_TYPES, CompositeWidgetType.class, "Composite", ""); //$NON-NLS-1$ //$NON-NLS-2$
	}

	/**
	 * @return the default implementation of LayoutType
	 */
	@Override
	public LayoutType getDefaultLayoutType() {
		return getDefaultWidget(EnvironmentPackage.ENVIRONMENT__LAYOUT_TYPES, LayoutType.class, "PropertiesLayout", "ppel"); //$NON-NLS-1$ //$NON-NLS-2$
	}

	/**
	 * @return the default implementation of StandardWidgetType
	 */
	@Override
	public StandardWidgetType getDefaultWidgetType() {
		return getDefaultWidget(EnvironmentPackage.ENVIRONMENT__WIDGET_TYPES, StandardWidgetType.class, "Label", ""); //$NON-NLS-1$ //$NON-NLS-2$
	}

	/**
	 * @param propertyType
	 * @param multiple
	 * @return the default implementation of PropertyEditorType for the given property Type
	 *         and multiplicity
	 */
	@Override
	public PropertyEditorType getDefaultEditorType(Type propertyType, boolean multiple) {
		String propertyEditorName = null;
		switch (propertyType) {
		case BOOLEAN:
			propertyEditorName = multiple ? "MultiBoolean" : "BooleanRadio"; //$NON-NLS-1$ //$NON-NLS-2$
			break;
		case ENUMERATION:
			propertyEditorName = multiple ? "MultiReference" : "EnumCombo"; //$NON-NLS-1$ //$NON-NLS-2$
			break;
		case INTEGER:
			propertyEditorName = multiple ? "MultiInteger" : "IntegerEditor"; //$NON-NLS-1$ //$NON-NLS-2$
			break;
		case REFERENCE:
			propertyEditorName = multiple ? "MultiReference" : "ReferenceDialog"; //$NON-NLS-1$ //$NON-NLS-2$
			break;
		case STRING:
			propertyEditorName = multiple ? "MultiString" : "StringEditor"; //$NON-NLS-1$ //$NON-NLS-2$
			break;
		case DOUBLE:
			propertyEditorName = multiple ? "MultiDouble" : "DoubleEditor"; //$NON-NLS-1$ //$NON-NLS-2$
		}


		if (propertyEditorName == null) {
			return null;
		}

		return getDefaultWidget(EnvironmentPackage.ENVIRONMENT__PROPERTY_EDITOR_TYPES, PropertyEditorType.class, propertyEditorName, "ppe"); //$NON-NLS-1$
	}

	/**
	 * Returns the default XWT namespaces
	 *
	 * @return the default XWT namespaces
	 */
	@Override
	public Set<Namespace> getBaseNamespaces() {
		Set<Namespace> result = new HashSet<Namespace>();
		result.add(getNamespaceByName("")); //$NON-NLS-1$
		result.add(getNamespaceByName("x")); //$NON-NLS-1$
		result.add(getNamespaceByName("j")); //$NON-NLS-1$
		return result;
	}

	/**
	 * @param name
	 * @return
	 * 		The namespace corresponding to the given name
	 */
	@Override
	public Namespace getNamespaceByName(String name) {
		for (Environment environment : root.getEnvironments()) {
			for (Namespace namespace : environment.getNamespaces()) {
				if (PropertiesUtil.namespaceEqualsByName(namespace, name)) {
					return namespace;
				}
			}
		}
		Activator.log.warn("Cannot find a registered namespace for '" + name + "'"); //$NON-NLS-1$ //$NON-NLS-2$
		return null;
	}

	/**
	 * @param property
	 * @return
	 * 		the default PropertyEditorType for the given Property
	 */
	@Override
	public PropertyEditorType getDefaultEditorType(Property property) {
		return getDefaultEditorType(property.getType(), property.getMultiplicity() != 1);
	}

	/**
	 * Disable, then unregisters a Context. The Context won't be available anymore in the framework
	 * (not even in the Preferences page). This method <strong>won't</strong> delete the context's files
	 * on the file system.
	 *
	 * @param context
	 *            The context to delete
	 */
	@Override
	public void deleteContext(Context context) {
		deleteContext(context, true);
	}

	/**
	 * Disable, then unregisters a Context. The Context won't be available anymore in the framework
	 * (not even in the Preferences page). This method <strong>won't</strong> delete the context's files
	 * on the file system.
	 *
	 * @param context
	 *            The context to delete
	 * @param updateEngine
	 *            If set to true, the ConstraintEngine will be updated.
	 *            If set to false, you will need to call {@link #update()} manually
	 */
	public void deleteContext(Context context, boolean updateEngine) {
		findDescriptor(context).setDeleted(true); // explicitly deleted (not missing)
		deleteContext(context, updateEngine, true);
	}

	private void deleteContext(Context context, boolean updateEngine, boolean updatePreferences) {
		if (!isCustomizable(context)) {
			throw new IllegalStateException("Non-customizable contexts cannot be deleted. Trying to delete " + context.getName());
		}

		Resource resource = context.eResource();
		contexts.remove(EcoreUtil.getURI(context));
		disableContext(context, updateEngine, updatePreferences);
		root.getContexts().remove(context);

		resource.unload();
		resourceSet.getResources().remove(resource);

		// as we have deleted this context, it may have been a copy of
		// some other context that now should be implicitly enabled
		reconcileEnabledContexts();
	}

	private boolean reconcileEnabledContexts() {
		boolean result = false;

		for (Context next : contexts.values()) {
			if (!next.eIsProxy()) {
				boolean isApplied = isApplied(next);
				if (isApplied != enabledContexts.contains(next)) {
					// it is implicitly enabled?
					if (isApplied) {
						result = enabledContexts.add(next) || result;
					} else {
						result = enabledContexts.remove(next) || result;
					}
				}
			}
		}

		if (result) {
			update(); // update the engine
		}

		return result;
	}

	/**
	 * Retrieves the Property object associated to the propertyPath in the given context
	 *
	 * @param propertyPath
	 * @param context
	 * @return
	 * 		The property associated to the given propertyPath
	 */
	@Override
	public Property getProperty(String propertyPath, Context context) {
		String elementName = propertyPath.substring(0, propertyPath.lastIndexOf(":")); //$NON-NLS-1$
		String propertyName = propertyPath.substring(propertyPath.lastIndexOf(":") + 1, propertyPath.length()); //$NON-NLS-1$
		Set<DataContextElement> elements = new HashSet<DataContextElement>();

		Collection<Context> allContexts;

		if (context == null) {
			allContexts = getContexts();
		} else {
			allContexts = PropertiesUtil.getDependencies(context);
		}

		for (Context ctx : allContexts) {
			elements.addAll(ctx.getDataContexts());
		}

		DataContextElement element = PropertiesUtil.getContextElementByQualifiedName(elementName, elements);
		if (element != null) {
			for (Property property : element.getProperties()) {
				if (property.getName().equals(propertyName)) {
					return property;
				}
			}
		}

		return null;
	}

	/**
	 * Updates the constraint engine to handle changes in the contexts
	 * activation
	 */
	@Override
	public void update() {
		constraintEngine.refresh();
	}

	/**
	 * Checks the conflicts between all applied {@linkplain #getEnabledContexts() enabled}) configurations
	 * A Conflict may occur when two sections have the same ID : they can't
	 * be displayed at the same time
	 *
	 * @return
	 * 		The list of conflicts
	 */
	@Override
	public Collection<ConfigurationConflict> checkConflicts() {
		return checkConflicts(getEnabledContexts());
	}

	/**
	 * Checks the conflicts between those of the specified configurations that are enabled.
	 * A Conflict may occur when two sections have the same ID : they can't
	 * be displayed at the same time.
	 *
	 * @param contexts
	 *            a set of configurations to check for conflicts (amongst the subset of these
	 *            that are actually {@linkplain #isEnabled(Context) enabled}
	 * 
	 * @return
	 * 		The list of conflicts
	 * 
	 * @see #isEnabled(Context)
	 */
	@Override
	public Collection<ConfigurationConflict> checkConflicts(Collection<? extends Context> contexts) {
		Map<String, List<Context>> sections = new HashMap<String, List<Context>>();
		Map<String, ConfigurationConflict> conflicts = new HashMap<String, ConfigurationConflict>();

		for (Context context : getEnabledContexts()) {
			for (Tab tab : context.getTabs()) {
				for (Section section : tab.getSections()) {
					String sectionID = section.getName();
					List<Context> sectionContexts = sections.get(sectionID);
					if (sectionContexts == null) {
						sectionContexts = new LinkedList<Context>();
						sections.put(sectionID, sectionContexts);
					} else {
						ConfigurationConflict conflict = conflicts.get(sectionID);
						if (conflict == null) {
							conflict = new ConfigurationConflict(sectionID);
							conflicts.put(sectionID, conflict);

							conflict.addContext(sectionContexts.get(0));
						}

						conflict.addContext(context);
					}

					sectionContexts.add(context);
				}
			}
		}

		// Report only conflicts involving the originally requested contexts
		for (Iterator<ConfigurationConflict> iter = conflicts.values().iterator(); iter.hasNext();) {
			ConfigurationConflict next = iter.next();
			if (next.conflictingContexts.stream().noneMatch(ctx -> contexts.contains(ctx))) {
				iter.remove();
			}
		}

		return conflicts.values();
	}

	/**
	 * Returns the ResourceSet associated to the ConfigurationManager,
	 * ie. the ResourceSet containing all Environments and Contexts
	 *
	 * @return
	 */
	@Override
	public ResourceSet getResourceSet() {
		return resourceSet;
	}

	@Override
	public boolean isCustomizable(Context propertyViewConfiguration) {

		if (isMissing(propertyViewConfiguration)) {
			// missing contexts are implicitly customizable. Only customizable
			// contexts can go missing in the first place
			return true;
		}

		if (customizableContexts.containsKey(propertyViewConfiguration)) {
			return customizableContexts.get(propertyViewConfiguration);
		}

		// Default value for isCustomizable is true. However, if the context is
		// not stored in customizableContexts, then it's an error. We should
		// disable customization tools for this one...
		return false;
	}

	@Override
	public ViewConstraintEngine getConstraintEngine() {
		return constraintEngine;
	}

	/**
	 * Registers association of a context with a preference page in which to present it
	 * for enablement/customization.
	 * 
	 * @param context
	 *            the context name
	 * @param page
	 *            the preference page identifier
	 * 
	 * @throws IllegalArgumentException
	 *             if the {@code context} or {@link page} is
	 *             {@code null} or empty
	 * 
	 * @see #registerContext(URI, String)
	 */
	public void registerPreferencePageBinding(String context, String page) {
		if ((context == null) || context.isEmpty()) {
			throw new IllegalArgumentException("context name is missing"); //$NON-NLS-1$
		}
		if ((page == null) || page.isEmpty()) {
			throw new IllegalArgumentException("preference page identifier is missing"); //$NON-NLS-1$
		}

		Set<String> contexts = preferencePageBindings.get(page);
		if (contexts == null) {
			contexts = new HashSet<>();
			preferencePageBindings.put(page, contexts);
		}
		contexts.add(context);
	}

	@Override
	public List<Context> getContextsForPreferencePage(String page) {
		return Stream.concat(getContexts().stream(), getMissingContexts().stream())
				.filter(this::isCustomizable) // Only present customizable contexts
				.filter(c -> isBoundToPreferencePage(c, page))
				.collect(Collectors.toList());
	}

	private boolean isBoundToPreferencePage(Context context, String page) {
		boolean result = false;
		String contextName = context.getName();

		if ((page == null) || page.equals(DEFAULT_VIEW_ID)) {
			page = DEFAULT_VIEW_ID;
			Set<String> explicitBindings = preferencePageBindings.getOrDefault(page, Collections.emptySet());

			// Looking for bindings to the default preference page. This includes
			// all contexts that are not bound to any page and those that are
			// explicitly bound to the default page
			result = explicitBindings.contains(contextName)
					|| preferencePageBindings.values().stream().noneMatch(set -> set.contains(contextName));
		} else {
			// Only explicit bindings
			result = preferencePageBindings.getOrDefault(page, Collections.emptySet()).contains(contextName);
		}

		return result;
	}
}

Back to the top