Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: ff93ae87e4a50099c94c2fe876879e2debeed3a9 (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
/*****************************************************************************
 * Copyright (c) 2009 CEA LIST.
 *
 *
 * 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:
 *  Remi Schnekenburger (CEA LIST) remi.schnekenburger@cea.fr - Initial API and implementation
 *
 *****************************************************************************/
package org.eclipse.papyrus.uml.diagram.common.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.palette.PaletteContainer;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.palette.PaletteEntry;
import org.eclipse.gef.palette.PaletteRoot;
import org.eclipse.gef.palette.PaletteSeparator;
import org.eclipse.gef.palette.PaletteToolbar;
import org.eclipse.gef.palette.PanningSelectionToolEntry;
import org.eclipse.gef.palette.ToolEntry;
import org.eclipse.gmf.runtime.common.core.service.ExecutionStrategy;
import org.eclipse.gmf.runtime.common.core.service.IOperation;
import org.eclipse.gmf.runtime.common.core.service.IProvider;
import org.eclipse.gmf.runtime.common.core.service.ProviderChangeEvent;
import org.eclipse.gmf.runtime.common.core.service.ProviderPriority;
import org.eclipse.gmf.runtime.common.core.service.Service;
import org.eclipse.gmf.runtime.common.ui.services.util.ActivityFilterProviderDescriptor;
import org.eclipse.gmf.runtime.common.ui.util.ActivityUtil;
import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin;
import org.eclipse.gmf.runtime.diagram.ui.internal.services.palette.ContributeToPaletteOperation;
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.providers.DefaultPaletteProvider;
import org.eclipse.gmf.runtime.diagram.ui.services.palette.IPaletteProvider;
import org.eclipse.gmf.runtime.diagram.ui.services.palette.PaletteService;
import org.eclipse.gmf.runtime.diagram.ui.services.palette.SelectionToolEx;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.papyrus.infra.viewpoints.policy.PolicyChecker;
import org.eclipse.papyrus.uml.diagram.common.Activator;
import org.eclipse.papyrus.uml.diagram.common.Messages;
import org.eclipse.papyrus.uml.diagram.common.part.IPaletteDescription;
import org.eclipse.papyrus.uml.diagram.common.part.PaletteUtil;
import org.eclipse.papyrus.uml.diagram.common.part.PapyrusPalettePreferences;
import org.eclipse.papyrus.uml.diagram.common.service.XMLPaletteProviderConfiguration.EditorDescriptor;
import org.eclipse.ui.IEditorPart;
import org.osgi.framework.Bundle;

/**
 * Service that contributes to the palette of a given editor with a given
 * content.
 * <p>
 * It replaces the standard palette service. It provides better preferences management, and better customization possibilities.
 */
public class PapyrusPaletteService extends PaletteService implements IPaletteProvider, IPapyrusPaletteConstant, IPreferenceChangeListener {

	/**
	 * A descriptor for palette providers defined by a configuration element.
	 */
	public static class ProviderDescriptor extends ActivityFilterProviderDescriptor {

		/** the provider configuration parsed from XML */
		protected XMLPaletteProviderConfiguration providerConfiguration;

		/**
		 * Constructs a <code>ISemanticProvider</code> descriptor for the
		 * specified configuration element.
		 *
		 * @param element
		 *            The configuration element describing the provider.
		 */
		public ProviderDescriptor(IConfigurationElement element) {
			super(element);

			if (element != null) {
				this.providerConfiguration = parseConfiguration(element);
				Assert.isNotNull(getProviderConfiguration());
			}
		}

		/**
		 * Return the ID of the target editor for this ProviderDescriptor or null if none
		 *
		 * @return
		 */
		public String getTargetEditorID() {
			if (providerConfiguration != null) {
				EditorDescriptor targetEditor = providerConfiguration.getEditor();
				if (targetEditor != null) {
					return targetEditor.getTargetId();
				}
			}
			return null;
		}

		/**
		 * Parses the content of the xml file configuration
		 *
		 * @param element
		 *            the configuration element for this provider descriptor
		 * @return the configuration of the descriptor
		 */
		protected XMLPaletteProviderConfiguration parseConfiguration(IConfigurationElement element) {
			return XMLPaletteProviderConfiguration.parse(element);
		}

		/**
		 * Returns the provider configuration for this descriptor
		 *
		 * @return the provider Configuration for this descriptor
		 */
		protected XMLPaletteProviderConfiguration getProviderConfiguration() {
			return providerConfiguration;
		}

		/**
		 * Returns <code>true</code> if this configuration provides only
		 * predefinition of entries and neither use predefined entries nor
		 * creates new entries.
		 *
		 * @return <code>true</code> if this configuration provides only
		 *         predefinition of entries and neither use predefined entries
		 *         nor creates new entries.
		 */
		// @unused
		public boolean hasOnlyEntriesDefinition() {
			return getProviderConfiguration().hasOnlyEntriesDefinition();
		}

		/**
		 * Returns this contribution's name
		 *
		 * @return this contribution's name
		 */
		public String getContributionName() {
			return getProviderConfiguration().getName();
		}

		/**
		 * Returns this contribution's id
		 *
		 * @return this contribution's id
		 */
		public String getContributionID() {
			return getProviderConfiguration().getID();
		}

		/**
		 * Returns true if this contributor is hidden in the preferences
		 *
		 * @param operation
		 * @return
		 */
		public boolean isHidden(ContributeToPaletteOperation operation) {
			// checks it is not in the list of hidden palettes for the editor
			List<String> hiddenPalettes = PapyrusPalettePreferences.getHiddenPalettes(operation.getEditor());
			return hiddenPalettes.contains(getContributionID());
		}

		/**
		 * Returns the priority for this provider
		 *
		 * @return the priority for this provider
		 */
		public ProviderPriority getPriority() {
			return getProviderConfiguration().getPriority();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean provides(IOperation operation) {
			if (!super.provides(operation)) {
				return false;
			}
			if (!policyInitialized) {
				policy = getPolicy();
				policyInitialized = true;
			}
			if (policy != null) {
				return policy.provides(operation);
			}

			if (operation instanceof ContributeToPaletteOperation) {
				ContributeToPaletteOperation o = (ContributeToPaletteOperation) operation;

				IEditorPart part = o.getEditor();
				if (!(part instanceof DiagramEditorWithFlyOutPalette)) {
					return false;
				}
				boolean supports = getProviderConfiguration().supports(o.getEditor(), o.getContent());

				if (!supports) {
					return false;
				}

				if (isHidden(o)) {
					return false;
				}

				if (!PaletteUtil.areRequiredProfileApplied(part, this)) {
					return false;
				}

				return true;
			}

			return false;
		}

		/**
		 * checks if this provider is providing elements, even if this should be
		 * hidden
		 *
		 * @param operation
		 *            the operation to contribute
		 * @return <code>true</code> if this provider contributes to the
		 *         operation
		 */
		public boolean providesWithVisibility(ContributeToPaletteOperation operation) {
			if (!super.provides(operation)) {
				return false;
			}
			if (!policyInitialized) {
				policy = getPolicy();
				policyInitialized = true;
			}
			if (policy != null) {
				return policy.provides(operation);
			}

			// FIXME: that statement is always true (let's see the method's
			// parameter).
			// => Remove the test
			if (operation instanceof ContributeToPaletteOperation) {
				ContributeToPaletteOperation o = operation;

				// FIXME returns directly the result
				boolean supports = getProviderConfiguration().supports(o.getEditor(), o.getContent());

				if (!supports) {
					return false;
				}

				return true;
			}

			return false;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public IProvider getProvider() {
			if (provider == null) {
				super.getProvider();
				if (provider instanceof DefaultPaletteProvider) {
					IPaletteProvider filtering = new FilteringPaletteProvider((DefaultPaletteProvider) provider, new String[] { GROUP_STANDARD, SEPARATOR_STANDARD, TOOL_SELECTION });
					filtering.setContributions(getElement());
					provider = filtering;
				} else if (provider instanceof IPaletteProvider) {
					((IPaletteProvider) provider).setContributions(getElement());
				}
			}
			return provider;
		}
	}

	/**
	 * Provider descriptor for a extended palette definition.
	 */
	public static class ExtendedProviderDescriptor extends ProviderDescriptor {

		/**
		 * Constructor.
		 *
		 * @param element
		 *            configuration element for this descriptor
		 */
		public ExtendedProviderDescriptor(IConfigurationElement element) {
			super(element);
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		protected ExtendedPaletteProviderConfiguration parseConfiguration(IConfigurationElement element) {
			return ExtendedPaletteProviderConfiguration.parse(element);
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		protected ExtendedPaletteProviderConfiguration getProviderConfiguration() {
			return (ExtendedPaletteProviderConfiguration) providerConfiguration;
		}

		/**
		 * Creates a new local redefinition of the configuration file
		 *
		 * @return the path to the configuration file
		 */
		public String createLocalRedefinition() {
			String filePath = getProviderConfiguration().getPath();
			String bundleId = getProviderConfiguration().getBundleID();
			String realId = bundleId;
			InputStream stream = null;

			Bundle bundle = Platform.getBundle(bundleId);
			if (Platform.isFragment(bundle)) {
				// retrieve the file in the fragment itself
				stream = openConfigurationFile(bundle, filePath);
			} else {
				// this is a plugin. Search in sub fragments, then in the plugin
				Bundle[] fragments = Platform.getFragments(bundle);
				// no fragment, so the file should be in the plugin itself
				if (fragments == null) {
					stream = openConfigurationFile(bundle, filePath);
				} else {
					for (Bundle fragment : fragments) {
						if (stream == null) {
							stream = openConfigurationFile(fragment, filePath);
							realId = fragment.getSymbolicName();
						}
					}

					if (stream == null) {
						// no file in fragments. open in the plugin itself
						stream = openConfigurationFile(bundle, filePath);
						realId = bundle.getSymbolicName();
					}
				}
			}

			// check the stream
			if (stream == null) {
				Activator.log.error("Impossible to read initial file", null);
				return null;
			}

			File stateLocationRootFile = Activator.getDefault().getStateLocation().toFile();
			File bundleFolder = new File(stateLocationRootFile, realId);
			bundleFolder.mkdir();

			// for all intermediate folders in filePath, create a folder in
			// plugin state location
			File root = bundleFolder;
			String[] folders = filePath.split("/");
			for (int i = 0; i < folders.length - 1; i++) { // all intermediate
															// folders. Last one
															// is the file name
															// itself...
				String folderName = folders[i];
				if (folderName != null && folderName.length() != 0) {
					File newFolder = new File(root, folders[i]);
					newFolder.mkdir();
					root = newFolder;
				}
			}

			File newFile = new File(root, folders[folders.length - 1]);
			boolean fileCreated = false;

			// check if file already exists or not
			if (newFile.exists()) {
				fileCreated = true;
			} else {
				try {
					fileCreated = newFile.createNewFile();
				} catch (IOException e) {
					Activator.log.error("Impossible to create new file", e);
					return null;
				}
			}

			if (!fileCreated) {
				Activator.log.error("It was not possible to create the file", null);
				return null;
			}

			try {
				FileOutputStream fileOutputStream = new FileOutputStream(newFile);
				byte[] buf = new byte[1024];
				int len;
				while ((len = stream.read(buf)) > 0) {
					fileOutputStream.write(buf, 0, len);
				}
				stream.close();
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				Activator.log.error("It was not possible to write in the file", e);
				return null;
			} catch (IOException e) {
				Activator.log.error("It was not possible to write in the file", e);
				return null;
			}

			// Needs to add a / to have a correct path or the concatenation will be false.
			if (!filePath.startsWith("/")) {//$NON-NLS-1$
				filePath = "/" + filePath; //$NON-NLS-1$
			}

			return realId + filePath;
		}

		/**
		 * Reads the configuration file in the bundle
		 *
		 * @param bundle
		 * @param filePath
		 * @return
		 */
		protected InputStream openConfigurationFile(Bundle bundle, String filePath) {
			try {
				URL urlFile = bundle.getEntry(filePath);
				urlFile = FileLocator.resolve(urlFile);
				urlFile = FileLocator.toFileURL(urlFile);
				if ("file".equals(urlFile.getProtocol())) { //$NON-NLS-1$
					return new FileInputStream(urlFile.getFile());
				} else if ("jar".equals(urlFile.getProtocol())) { //$NON-NLS-1$
					String path = urlFile.getPath();
					if (path.startsWith("file:")) {
						// strip off the file: and the !/
						int jarPathEndIndex = path.indexOf("!/");
						if (jarPathEndIndex < 0) {
							Activator.log.error("Impossible to find the jar path end", null);
							return null;
						}
						String jarPath = path.substring("file:".length(), jarPathEndIndex);
						ZipFile zipFile = new ZipFile(jarPath);
						filePath = filePath.substring(jarPathEndIndex + 2, path.length());
						ZipEntry entry = zipFile.getEntry(path);
						return zipFile.getInputStream(entry);
						// return new File(filePath);
					}
				}
			} catch (IOException e) {
				Activator.log.error("Impossible to find initial file", e);
			}
			return null;
		}

		/**
		 * Returns the redefinition file URI
		 *
		 * @return the redefinition file URI or <code>null</code> if no local
		 *         redefinition can be found.
		 */
		public URI getRedefinitionFileURI() {
			String path = PapyrusPalettePreferences.getPaletteRedefinition(getContributionID());
			if (path == null) {
				Activator.log.error("Path is null for the given contribution: " + getContributionID(), null);
				return null;
			}

			File stateLocationRootFile = Activator.getDefault().getStateLocation().append(path).toFile();
			if (stateLocationRootFile == null) {
				Activator.log.error("No redefinition file was found for id: " + getContributionID(), null);
				return null;
			}
			if (!stateLocationRootFile.exists()) {
				Activator.log.error("local definition file does not exists : " + stateLocationRootFile, null);
				return null;
			}

			if (!stateLocationRootFile.canRead()) {
				Activator.log.error("Impossible to read local definition of the file " + stateLocationRootFile, null);
				return null;
			}
			URI uri = URI.createFileURI(stateLocationRootFile.getAbsolutePath());
			return uri;
		}
	}

	/**
	 * Provider descriptor for a local palette definition.
	 * <p>
	 * It has no configuration element attached to it, it should not be used everywhere without checks.
	 * </p>
	 */
	public static class LocalProviderDescriptor extends ProviderDescriptor {

		/** palette description */
		protected final IPaletteDescription description;

		/**
		 * Creates a new Local Palette Descriptor
		 *
		 * @param description
		 *            the description of the palette
		 */
		public LocalProviderDescriptor(IPaletteDescription description) {
			super(null);
			this.description = description;
		}

		/**
		 * Returns <code>true</code> if this configuration provides only
		 * predefinition of entries and neither use predefined entries nor
		 * creates new entries.
		 *
		 * @return <code>false</code> as local palettes are never defining tools
		 */
		@Override
		public boolean hasOnlyEntriesDefinition() {
			return false;
		}

		/**
		 * Returns the description of this palette provider
		 *
		 * @return the description of this palette provider
		 */
		public IPaletteDescription getDescription() {
			return description;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public String getContributionName() {
			return description.getName();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public String getContributionID() {
			return description.getPaletteID();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean isHidden(ContributeToPaletteOperation operation) {
			// checks it is not in the list of hidden palettes for the editor
			List<String> hiddenPalettes = PapyrusPalettePreferences.getHiddenPalettes(operation.getEditor());
			return hiddenPalettes.contains(getContributionID());
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public ProviderPriority getPriority() {
			return description.getPriority();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean provides(IOperation operation) {
			boolean isEnable = ActivityUtil.isEnabled(getContributionID(), Activator.ID);

			if (!isEnable) {
				return false;
			}

			if (operation instanceof ContributeToPaletteOperation) {
				ContributeToPaletteOperation o = (ContributeToPaletteOperation) operation;

				IEditorPart part = o.getEditor();
				if (!(part instanceof DiagramEditorWithFlyOutPalette)) {
					return false;
				}

				// will never work, ID of the site is the multi diagram
				// editor...
				if (description.getContributionEditorID() != null) {
					if (!description.getContributionEditorID().equals(((DiagramEditorWithFlyOutPalette) part).getContributorId())) {
						return false;
					}
				}

				if (!PaletteUtil.areRequiredProfileApplied(part, this)) {
					return false;
				}

				if (isHidden(o)) {
					return false;
				}
				return true;
			}

			return false;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean providesWithVisibility(ContributeToPaletteOperation operation) {
			/**
			 * @see org.eclipse.gmf.runtime.common.core.service.IProvider#provides(org.eclipse.gmf.runtime.common.core.service.IOperation)
			 */
			boolean isEnable = ActivityUtil.isEnabled(getContributionID(), Activator.ID);

			if (!isEnable) {
				return false;
			}
			// FIXME: that statement is always true (let's see the method's
			// parameter).
			// => Remove the test
			if (operation instanceof ContributeToPaletteOperation) {
				ContributeToPaletteOperation o = operation;

				IEditorPart part = o.getEditor();
				if (!(part instanceof DiagramEditorWithFlyOutPalette)) {
					return false;
				}

				// will never work, ID of the site is the multi diagram
				// editor...
				if (description.getContributionEditorID() != null) {
					if (!description.getContributionEditorID().equals(((DiagramEditorWithFlyOutPalette) part).getContributorId())) {
						return false;
					}
				}

				return true;
			}

			return false;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public IProvider getProvider() {
			if (provider == null) {
				provider = new LocalPaletteProvider();
				((LocalPaletteProvider) provider).setContributions(description);
			}
			return provider;
		}

	}

	public static class WorkspaceExtendedProviderDescriptor extends LocalProviderDescriptor {
		/**
		 * @param description
		 */
		public WorkspaceExtendedProviderDescriptor(IPaletteDescription description) {
			super(description);
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public IProvider getProvider() {
			if (provider == null) {
				provider = new WorkspaceExtendedPaletteProvider();
				((WorkspaceExtendedPaletteProvider) provider).setContributions(description);
			}
			return provider;
		}
	}

	/**
	 * 
	 * Provider Descriptor for extended palette defined locally (ie not in workspace)
	 *
	 */
	public static class LocalExtendedProviderDescriptor extends LocalProviderDescriptor {
		/**
		 * @param description
		 */
		public LocalExtendedProviderDescriptor(IPaletteDescription description) {
			super(description);
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public IProvider getProvider() {
			if (null == provider) {
				provider = new LocalExtendedPaletteProvider();
				((LocalExtendedPaletteProvider) provider).setContributions(description);
			}
			return provider;
		}
	}

	public static class WorkspaceProviderDescriptor extends LocalProviderDescriptor {

		/**
		 * @param description
		 */
		public WorkspaceProviderDescriptor(IPaletteDescription description) {
			super(description);
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public IProvider getProvider() {
			if (provider == null) {
				provider = new WorkspacePaletteProvider();
				((WorkspacePaletteProvider) provider).setContributions(description);
			}
			return provider;
		}
	}


	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setContributions(IConfigurationElement configElement) {
		//
	}

	/** the singleton instance of the palette service */
	private static PapyrusPaletteService instance;

	/** the standard group id */
	public final static String GROUP_STANDARD = "standardGroup"; //$NON-NLS-1$

	/** the standard separator id */
	public final static String SEPARATOR_STANDARD = "standardSeparator"; //$NON-NLS-1$

	/** the standard separator id */
	public final static String TOOL_SELECTION = "selectionTool"; //$NON-NLS-1$

	/**
	 * Creates a new instance of the Palette Service
	 */
	protected PapyrusPaletteService() {
		super();

		IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(Activator.ID);
		prefs.addPreferenceChangeListener(this);
	}

	/**
	 * add providers for local palettes
	 */
	protected void configureLocalPalettes() {
		// read the preference field that indicates where the local palettes
		// are, their IDs, etc...
		List<IPaletteDescription> localPalettes = PapyrusPalettePreferences.getLocalPalettes();
		// create the providers linked to these configuration

		// remove all local descriptors
		for (org.eclipse.gmf.runtime.common.core.service.Service.ProviderDescriptor descriptor : getProviders()) {
			if (descriptor instanceof LocalProviderDescriptor) {
				removeProvider(descriptor);
			}
		}

		// create new list
		for (IPaletteDescription palette : localPalettes) {
			LocalProviderDescriptor descriptor = new LocalProviderDescriptor(palette);
			addProvider(palette.getPriority(), descriptor);
		}

	}

	/**
	 * add providers for workspace palettes
	 */
	protected void configureWorkspacePalettes() {
		// read the preference field that indicates where the local palettes
		// are, their IDs, etc...
		List<IPaletteDescription> workspacePalettes = PapyrusPalettePreferences.getWorkspacePalettes();
		// create the providers linked to these configuration

		// remove all local descriptors
		for (org.eclipse.gmf.runtime.common.core.service.Service.ProviderDescriptor descriptor : getProviders()) {
			if (descriptor instanceof WorkspaceProviderDescriptor) {
				removeProvider(descriptor);
			}
		}

		// create new list
		for (IPaletteDescription palette : workspacePalettes) {
			LocalProviderDescriptor descriptor = new WorkspaceProviderDescriptor(palette);
			addProvider(palette.getPriority(), descriptor);
		}
	}

	/**
	 * add providers for workspace palettes based on model
	 */
	protected void configureWorkspaceExtendedPalettes() {
		// read the preference field that indicates where the workspace palettes
		// are, their IDs, etc...
		List<IPaletteDescription> workspacePalettes = PapyrusPalettePreferences.getWorkspaceExtendedPalettes();
		// create the providers linked to these configuration
		// remove all local descriptors
		for (org.eclipse.gmf.runtime.common.core.service.Service.ProviderDescriptor descriptor : getProviders()) {
			if (descriptor instanceof WorkspaceExtendedProviderDescriptor) {
				removeProvider(descriptor);
			}
		}

		// create new list
		for (IPaletteDescription palette : workspacePalettes) {
			LocalProviderDescriptor descriptor = new WorkspaceExtendedProviderDescriptor(palette);
			addProvider(palette.getPriority(), descriptor);
		}

	}

	/**
	 * add providers for workspace palettes based on model
	 */
	protected void configureRedefinedPalettes() {
		// Nothing to do
	}


	/**
	 * gets the singleton instance
	 *
	 * @return <code>PaletteService</code>
	 */
	public static synchronized PapyrusPaletteService getInstance() {
		if (instance == null) {
			instance = new PapyrusPaletteService();
			configureProviders();
		}
		return instance;
	}

	/**
	 * Configure providers.
	 */
	private static void configureProviders() {
		getInstance().configureProviders(DiagramUIPlugin.getPluginId(), "paletteProviders"); //$NON-NLS-1$
		getInstance().configureProviders(Activator.ID, PALETTE_DEFINITION);
		getInstance().configureLocalPalettes();
		getInstance().configureWorkspacePalettes();
		getInstance().configureWorkspaceExtendedPalettes();
		getInstance().configureLocalExtendedPalettes();
		getInstance().configureRedefinedPalettes();
	}

	/**
	 * Configure local extended palettes.
	 */
	protected void configureLocalExtendedPalettes() {
		// read the preference field that indicates where the local extended palettes
		// are, their IDs, etc...
		List<IPaletteDescription> localExtendedPalettes = PapyrusPalettePreferences.getLocalExtendedPalettes();
		// create the providers linked to these configuration
		// remove all local descriptors
		for (org.eclipse.gmf.runtime.common.core.service.Service.ProviderDescriptor descriptor : getProviders()) {
			if (descriptor instanceof LocalExtendedProviderDescriptor) {
				removeProvider(descriptor);
			}
		}

		// create new list
		for (IPaletteDescription palette : localExtendedPalettes) {
			LocalExtendedProviderDescriptor descriptor = new LocalExtendedProviderDescriptor(palette);
			addProvider(palette.getPriority(), descriptor);
		}

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected Service.ProviderDescriptor newProviderDescriptor(IConfigurationElement element) {
		// if provider is coming from palette definition extension point :
		// define an extended palette provider...
		String extensionPointId = element.getDeclaringExtension().getExtensionPointUniqueIdentifier();
		if (PALETTE_DEFINITION_FULL_ID.equals(extensionPointId)) {
			return new ExtendedProviderDescriptor(element);
		}
		return new ProviderDescriptor(element);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void contributeToPalette(IEditorPart editor, Object content, PaletteRoot root, Map predefinedEntries) {

		PaletteToolbar standardGroup = new PaletteToolbar(Messages.StandardGroup_Label);
		standardGroup.setDescription(""); //$NON-NLS-1$
		standardGroup.setId(GROUP_STANDARD);
		root.add(standardGroup);

		PaletteSeparator standardSeparator = new PaletteSeparator(SEPARATOR_STANDARD);
		standardGroup.add(standardSeparator);

		ToolEntry selectTool = new PanningSelectionToolEntry();
		selectTool.setId(TOOL_SELECTION);
		selectTool.setToolClass(SelectionToolEx.class);
		standardGroup.add(selectTool);
		root.setDefaultEntry(selectTool);

		execute(new ContributeToPaletteOperation(editor, content, root, predefinedEntries));
	}

	/**
	 * Returns the list of providers for this service
	 *
	 * @return the list of providers for this service
	 */
	@SuppressWarnings("unchecked")
	public List<? extends Service.ProviderDescriptor> getProviders() {
		return getAllProviders();
	}

	/**
	 * Executes the palette operation using the REVERSE execution strategy.
	 *
	 * @param operation
	 * @return List of results
	 */
	@SuppressWarnings("unchecked")
	private List execute(IOperation operation) {
		return execute(ExecutionStrategy.REVERSE, operation);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public PaletteRoot createPalette(final IEditorPart editor, final Object content) {
		final PaletteRoot root = new PaletteRoot();
		try {
			IEditingDomainProvider provider = editor.getAdapter(IEditingDomainProvider.class);
			if (provider != null) {
				EditingDomain domain = provider.getEditingDomain();
				if (domain instanceof TransactionalEditingDomain) {
					((TransactionalEditingDomain) domain).runExclusive(new Runnable() {

						@Override
						public void run() {
							contributeToPalette(editor, content, root, new HashMap());
						}
					});
				}
			}
		} catch (Exception e) {
			Activator.getDefault().logError("Error in PapyrusPaletteService::createPalette()", e); //$NON-NLS-1$
		}

		Diagram diagram = ((DiagramEditor) editor).getDiagram();
		for (Object o : root.getChildren()) {
			if (o instanceof PaletteDrawer) {
				PaletteDrawer drawer = (PaletteDrawer) o;
				boolean isVisible = PolicyChecker.getCurrent().isInPalette(diagram, drawer.getId());
				drawer.setVisible(isVisible);
				if (isVisible) {
					for (Object x : drawer.getChildren()) {
						if (x instanceof PaletteEntry) {
							PaletteEntry entry = (PaletteEntry) x;
							entry.setVisible(PolicyChecker.getCurrent().isInPalette(diagram, entry.getId()));
						}
					}
				}
			}
		}
		return root;
	}


	/**
	 * {@inheritDoc}
	 */
	@Override
	public void updatePalette(PaletteRoot existingRoot, final IEditorPart editor, final Object content) {
		PaletteRoot newRoot = createPalette(editor, content);
		updatePaletteContainerEntries(existingRoot, newRoot);
	}

	/**
	 * Updates the children of an existing palette container to match the
	 * palette entries in a new palette container by adding or removing new
	 * palette entries only. This method works recursively on any children that
	 * are palette container entries. Existing leaf palette entries that are to
	 * be kept remain the same -- they are not replaced with the new palette
	 * entry. This is so that palette state (such as whether a drawer is pinned
	 * or expanded) can be preserved when the palette is updated.
	 *
	 * @param existingContainer
	 *            the palette container to be updated with new entries, have
	 *            obsolete entries removed, and whose existing entries will
	 *            remain the same
	 * @param newContainer
	 *            the new palette entries
	 */
	protected void updatePaletteContainerEntries(PaletteContainer existingContainer, PaletteContainer newContainer) {
		HashMap existingEntryIds = new HashMap();
		for (Iterator iter = existingContainer.getChildren().iterator(); iter.hasNext();) {
			PaletteEntry entry = (PaletteEntry) iter.next();
			existingEntryIds.put(entry.getId(), entry);
		}

		int nextNewIndex = 0;
		// cycle through the new entries
		for (Iterator iter = newContainer.getChildren().iterator(); iter.hasNext();) {
			PaletteEntry newEntry = (PaletteEntry) iter.next();

			PaletteEntry existingEntry = (PaletteEntry) existingEntryIds.get(newEntry.getId());
			if (existingEntry != null) { // is already in existing container
				// update the index
				nextNewIndex = existingContainer.getChildren().indexOf(existingEntry) + 1;

				// remove the entry that was just updated from the map
				existingEntryIds.remove(existingEntry.getId());

				if (existingEntry instanceof PaletteContainer && newEntry instanceof PaletteContainer) {
					// look for new/deleted entries in
					// palette containers
					updatePaletteContainerEntries((PaletteContainer) existingEntry, (PaletteContainer) newEntry);
				}
			} else { // this is a new entry that did not previously exist
				existingContainer.add(nextNewIndex++, newEntry);
			}
		}

		// remove existing entries that were not found in the new container
		for (Iterator iter = existingEntryIds.values().iterator(); iter.hasNext();) {
			PaletteEntry entry = (PaletteEntry) iter.next();
			existingContainer.remove(entry);
		}

	}

	/**
	 * Returns the list of all providers that are really contributing to the
	 * palette
	 *
	 * @param part
	 *            the editor part fopr which the palette is displayed
	 * @param root
	 *            the palette root of the current palette
	 * @return the list of all providers that are really contributing to the
	 *         palette
	 */
	public List<PapyrusPaletteService.ProviderDescriptor> getContributingProviders(IEditorPart part, PaletteRoot root) {
		// init...
		// 1. inits the return list of providers contributing to the specified
		// editor part
		// 2. inits the operation used to check if the provider really provides
		// to this service
		// 3. inits the list of ids of hidden palettes
		List<PapyrusPaletteService.ProviderDescriptor> descriptors = new ArrayList<PapyrusPaletteService.ProviderDescriptor>();
		final ContributeToPaletteOperation o = new ContributeToPaletteOperation(part, part.getEditorInput(), root, new HashMap());
		// For each provider, checks it contributes to the palette of this
		// editor part
		Iterator<? extends Service.ProviderDescriptor> it = getProviders().iterator();
		while (it.hasNext()) {
			Service.ProviderDescriptor provider = it.next();
			if (provider instanceof PapyrusPaletteService.ProviderDescriptor) {

				PapyrusPaletteService.ProviderDescriptor papyrusProviderDesc = (PapyrusPaletteService.ProviderDescriptor) provider;

				// get provider name
				String name = papyrusProviderDesc.getContributionName();
				if (name == null || name.equals("")) {
					name = papyrusProviderDesc.getContributionID();
				}

				// check if the name of the descriptor does not correspond to
				// the name of a palette
				// that should not be removed
				boolean add = isChangeable(papyrusProviderDesc, name);

				// check if this provider is really contributing this palette
				add = add && isContributing(papyrusProviderDesc, o);

				if (add) {
					descriptors.add(papyrusProviderDesc);
				}
			} else {
				Activator.getDefault().logInfo("impossible to cast this provider: " + provider);
			}
		}

		return descriptors;
	}

	/**
	 * Checks if the name does not belong to a set of names that should not be
	 * in the action list
	 *
	 * @param provider
	 *            the provider to check
	 * @param name
	 *            the name of the provider to check
	 * @return <code>true</code> if the provider should appear in the list of
	 *         actions
	 */
	protected boolean isChangeable(PapyrusPaletteService.ProviderDescriptor provider, String name) {
		assert name != null;
		final String[] providersToRemove = new String[] { "<Unnamed>", "Presentation Palette", "Geoshapes", "org.eclipse.papyrus.uml.diagram.common" };
		final List<String> providersList = Arrays.asList(providersToRemove);

		// if the name is in the list, it is not changeable
		if (providersList.contains(name)) {
			return false;
		}
		// if it contains predefined entries in its name, it should return false
		return name.indexOf("Predefined Entries") == -1;
	}

	/**
	 * Checks if the provider descriptor is able to fill the palette for the
	 * current active diagram
	 *
	 * @param provider
	 *            the provider to check
	 * @return <code>true</code> if the provider is able to fill the palette for
	 *         the current active diagram
	 */
	protected boolean isContributing(PapyrusPaletteService.ProviderDescriptor provider, ContributeToPaletteOperation o) {
		return provider.providesWithVisibility(o);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void preferenceChange(PreferenceChangeEvent event) {
		// listen for local palette preferences...

		String id = event.getKey();
		if (IPapyrusPaletteConstant.PALETTE_WORKSPACE_DEFINITIONS.equals(id)) {
			// refresh available palette table viewer
			getInstance().configureWorkspacePalettes();
			providerChanged(new ProviderChangeEvent(this));
		} else if (IPapyrusPaletteConstant.EXTENDED_PALETTE_WORKSPACE_DEFINITIONS.equals(id)) {
			// refresh available palette table viewer
			getInstance().configureWorkspaceExtendedPalettes();
			providerChanged(new ProviderChangeEvent(this));
		} else if (IPapyrusPaletteConstant.LOCAL_EXTENDED_PALETTE_DEFINITIONS.equals(id)) {
			// refresh available palette table viewer
			getInstance().configureLocalExtendedPalettes();
			providerChanged(new ProviderChangeEvent(this));
		} else if (IPapyrusPaletteConstant.PALETTE_LOCAL_DEFINITIONS.equals(id)) {
			// refresh available palette table viewer
			getInstance().configureLocalPalettes();
			providerChanged(new ProviderChangeEvent(this));
		} else if (IPapyrusPaletteConstant.PALETTE_CUSTOMIZATIONS_ID.equals(id)) {
			// refresh available palette table viewer
			providerChanged(new ProviderChangeEvent(this));
		} else if (IPapyrusPaletteConstant.PALETTE_REDEFINITIONS.equals(id)) {
			for (Service.ProviderDescriptor descriptor : getProviders()) {
				removeProvider(descriptor);
			}
			configureProviders();
			// refresh available palette table viewer
			providerChanged(new ProviderChangeEvent(this));
		}
	}

	/**
	 * Notifies the listeners for this abstract provider that the specified
	 * event has occurred.
	 *
	 * @param event
	 *            The provider change event to be fired.
	 */
	@Override
	protected void fireProviderChange(ProviderChangeEvent event) {
		// Bug 407849: If a listener throws an exception, the operation is rolled back. This could have bad side effects, as explained in the bug
		try {
			super.fireProviderChange(event);
		} catch (Exception e) {
			Activator.log.error(e);
		}

	}
}

Back to the top