Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 1ea642efaa77ca1878c152a7af6e166b80758cab (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
/*****************************************************************************
 * Copyright (c) 2015, 2016 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:
 *  Nicolas FAUVERGUE (ALL4TEC) nicolas.fauvergue@all4tec.net - Initial API and implementation
 *  Christian W. Damus - bugs 493858, 493853
 *  Vincent Lorenzo (CEA-LIST) vincent.lorenzo@cea.fr - bug 494537
 *****************************************************************************/
package org.eclipse.papyrus.uml.properties.widgets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CompoundCommand;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EModelElement;
import org.eclipse.emf.ecore.EObject;
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.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.editparts.AbstractEditPart;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.papyrus.infra.core.resource.EditingDomainServiceFactory;
import org.eclipse.papyrus.infra.core.resource.ModelSet;
import org.eclipse.papyrus.infra.core.services.ServiceDescriptor;
import org.eclipse.papyrus.infra.core.services.ServiceDescriptor.ServiceTypeKind;
import org.eclipse.papyrus.infra.core.services.ServiceException;
import org.eclipse.papyrus.infra.core.services.ServiceMultiException;
import org.eclipse.papyrus.infra.core.services.ServiceStartKind;
import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
import org.eclipse.papyrus.infra.emf.nattable.selection.EObjectSelectionExtractor;
import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
import org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager;
import org.eclipse.papyrus.infra.nattable.manager.table.NattableModelManager;
import org.eclipse.papyrus.infra.nattable.manager.table.TreeNattableModelManager;
import org.eclipse.papyrus.infra.nattable.model.nattable.NattableFactory;
import org.eclipse.papyrus.infra.nattable.model.nattable.NattablePackage;
import org.eclipse.papyrus.infra.nattable.model.nattable.Table;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxis.IAxis;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisconfiguration.AxisManagerRepresentation;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisconfiguration.EStructuralFeatureValueFillingConfiguration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisconfiguration.IAxisConfiguration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisconfiguration.TableHeaderAxisConfiguration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisprovider.AbstractAxisProvider;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisprovider.NattableaxisproviderFactory;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisprovider.NattableaxisproviderPackage;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableconfiguration.TableConfiguration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattablestyle.BooleanValueStyle;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattablestyle.NattablestyleFactory;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattablestyle.Style;
import org.eclipse.papyrus.infra.nattable.tree.ITreeItemAxisHelper;
import org.eclipse.papyrus.infra.nattable.utils.NamedStyleConstants;
import org.eclipse.papyrus.infra.nattable.utils.NattableModelManagerFactory;
import org.eclipse.papyrus.infra.properties.contexts.Property;
import org.eclipse.papyrus.infra.properties.ui.modelelement.CompositeModelElement;
import org.eclipse.papyrus.infra.properties.ui.modelelement.DataSource;
import org.eclipse.papyrus.infra.properties.ui.modelelement.DataSourceChangedEvent;
import org.eclipse.papyrus.infra.properties.ui.modelelement.EMFModelElement;
import org.eclipse.papyrus.infra.properties.ui.modelelement.IDataSourceListener;
import org.eclipse.papyrus.infra.properties.ui.modelelement.ModelElement;
import org.eclipse.papyrus.infra.properties.ui.widgets.AbstractPropertyEditor;
import org.eclipse.papyrus.uml.properties.Activator;
import org.eclipse.papyrus.uml.properties.modelelement.UMLNotationModelElement;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.uml2.uml.Element;

/**
 * The property editor for the nattable widget.
 */
public class NattablePropertyEditor extends AbstractPropertyEditor {

	/**
	 * the save option to uses
	 */
	private static final Map<Object, Object> saveOptions = new HashMap<Object, Object>();

	static {
		saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
		saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
		saveOptions.put(XMLResource.OPTION_SAVE_TYPE_INFORMATION, true);
	}
	/**
	 * the folders in which we wil save the table configured by the user.
	 */
	private static final String TABLES_PREFERENCES_FOLDER_NAME = "tables";//$NON-NLS-1$

	/**
	 * The file in which the table will be saved
	 * 
	 * It doesn't work using .notation as extension file. In this case, the commands are not executed, because it is read-only, but why ?
	 */
	private static final String FILE_EXTENSION = "table";//$NON-NLS-1$

	/**
	 * The composite.
	 */
	protected Group self = null;;

	/**
	 * The table configuration URI.
	 */
	private URI tableConfigURI = null;

	/**
	 * The nattable widget.
	 */
	protected NatTable natTableWidget = null;

	/**
	 * The nattable manager.
	 */
	protected INattableModelManager nattableManager = null;

	/**
	 * The dispose listener.
	 */
	private DisposeListener nattableDisposeListener = null;

	/**
	 * The data source listener.
	 */
	private IDataSourceListener dataSourceListener;

	/**
	 * The service registry used to manipulate the table
	 */
	private ServicesRegistry serviceRegistry = null;

	/**
	 * the resource where the table will be saved
	 */
	private Resource resource = null;

	/**
	 * the edited Papyrus table
	 */
	private Table table = null;

	/**
	 * the table configuration
	 */
	private TableConfiguration tableConfiguration = null;

	/**
	 * if <code>true</code> we register table configuration by eClass and not only by table type
	 */
	private boolean registerTableConfigurationByEClass = false;

	/**
	 * Constructor.
	 *
	 * @param parent
	 *            The parent composite.
	 * @param style
	 *            The style of the composite.
	 */
	public NattablePropertyEditor(final Composite parent, final int style) {
		self = new Group(parent, SWT.NONE);
		FillLayout fillLayout = new FillLayout();
		fillLayout.marginHeight = 10;
		fillLayout.marginWidth = 10;
		self.setLayout(fillLayout);
	}

	/**
	 * 
	 * @param newValue
	 *            if <code>true</code> we register the table configuration by type AND by the ECLass of the selected element
	 * @since 2.0
	 */
	public final void setRegisterTableConfigurationByEClass(final boolean newValue) {
		this.registerTableConfigurationByEClass = newValue;
	}

	/**
	 * Set the table URI.
	 * 
	 * @param uri
	 *            The URI of the table (as String).
	 * @since 2.0
	 */
	public void setTableConfigurationURI(final String uri) {
		tableConfigURI = URI.createURI(uri);
		checkInput();
	}

	/**
	 * Get the table configuration URI.
	 * 
	 * @return The table configuration URI.
	 * @since 2.0
	 * 
	 */
	public String getTableConfigurationURI() {
		return tableConfigURI == null ? null : tableConfigURI.toString();
	}

	/**
	 * Set the table URI.
	 * 
	 * @param uri
	 *            The URI of the table (as String).
	 * 
	 * @deprecated since 2.0, use setTableConfigurationURI instead
	 */
	@Deprecated
	public void setTableURI(final String uri) {
		setTableConfigurationURI(uri);
	}

	/**
	 * Get the table configuration URI.
	 * 
	 * @return The table configuration URI.
	 * @deprecated since 2.0, use getTableConfigurationUri instead
	 */
	public String getTableURI() {
		return getTableConfigurationURI();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.papyrus.infra.properties.ui.widgets.AbstractPropertyEditor#checkInput()
	 */
	@Override
	protected void checkInput() {
		if (tableConfigURI != null) {
			super.checkInput();
		}
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.papyrus.infra.properties.ui.widgets.AbstractPropertyEditor#doBinding()
	 */
	@Override
	protected void doBinding() {
		super.doBinding();

		final ModelElement modelElement = input.getModelElement(propertyPath);

		// The data needed to create the table
		final List<Object> rows = new ArrayList<Object>();
		EObject sourceElement = null;
		EStructuralFeature feature = null;

		// Manage the data needed for the table creation
		if (modelElement instanceof CompositeModelElement) {
			if (!((CompositeModelElement) modelElement).getSubElements().isEmpty()) {
				if (((CompositeModelElement) modelElement).getSubElements().get(0) instanceof UMLNotationModelElement) {
					final EModelElement eModelElement = ((UMLNotationModelElement) ((CompositeModelElement) modelElement).getSubElements().get(0)).getEModelElement();
					// Fill the list of views to determinate the axis to display (cannot be created without the table editing domain)
					for (ModelElement subModelElement : ((CompositeModelElement) modelElement).getSubElements()) {
						if (subModelElement instanceof UMLNotationModelElement) {
							rows.add(((UMLNotationModelElement) subModelElement).getEModelElement());
						}
					}
					sourceElement = eModelElement;
				} else if (((CompositeModelElement) modelElement).getSubElements().get(0) instanceof EMFModelElement) {
					final EMFModelElement emfModelElement = (EMFModelElement) ((CompositeModelElement) modelElement).getSubElements().get(0);
					sourceElement = emfModelElement.getSource();
					feature = emfModelElement.getFeature(getLocalPropertyPath());
				}
			}
		} else if (modelElement instanceof UMLNotationModelElement) {
			final EModelElement eModelElement = ((UMLNotationModelElement) modelElement).getEModelElement();
			// Fill the list of views to determinate the axis to display (cannot be created without the table editing domain)
			rows.add(eModelElement);
			sourceElement = eModelElement;
		} else if (modelElement instanceof EMFModelElement) {
			final EMFModelElement emfModelElement = (EMFModelElement) modelElement;
			sourceElement = emfModelElement.getSource();
			feature = emfModelElement.getFeature(getLocalPropertyPath());
		} else {
			displayError("Invalid table context"); //$NON-NLS-1$
			return;
		}

		// Create the widgets
		createWidgets(sourceElement, feature, rows);
	}

	/**
	 * This allow to create the widgets.
	 * 
	 * @param sourceElement
	 *            The source Element.
	 * @param feature
	 *            The feature.
	 * @param rows
	 *            The rows of the table.
	 * @since 2.0
	 */
	protected void createWidgets(final EObject sourceElement, final EStructuralFeature feature, final Collection<?> rows) {
		createPreviousWidgets(sourceElement, feature);
		createTableWidget(sourceElement, feature, rows);
		createFollowingWidgets(sourceElement, feature);

		// Configure the layout and the layout data
		configureLayout(sourceElement);
		self.layout();
	}

	/**
	 * This allow to create the widgets displayed before the table widget.
	 * 
	 * @param sourceElement
	 *            The source Element.
	 * @param feature
	 *            The feature.
	 * @since 2.0
	 */
	protected void createPreviousWidgets(final EObject sourceElement, final EStructuralFeature feature) {
		// To implement if some widgets are needed before the table widget
	}

	/**
	 * This allow to create the table widget or to reuse a table previously used in the property view
	 * 
	 * @param sourceElement
	 *            The source Element.
	 * @param feature
	 *            The parent structural feature.
	 * @param rows
	 *            The rows of the table.
	 * 
	 * @since 2.0
	 */
	protected void createTableWidget(final EObject sourceElement, final EStructuralFeature feature, final Collection<?> rows) {
		// 1. we initialize a service registry
		if (this.serviceRegistry == null) {
			try {
				this.serviceRegistry = createServiceRegistry(sourceElement);
			} catch (Exception e) {
				Activator.log.error(e);
			}
		}

		if (this.serviceRegistry == null) {
			displayError("Cannot initialize the service registry"); //$NON-NLS-1$
			return;
		}

		// 2. get the editing domain
		TransactionalEditingDomain domain = getTableEditingDomain();
		if (domain == null) {
			displayError("Cannot found the editing domain"); //$NON-NLS-1$
			return;
		}

		// 3. Create the table or get an existing one
		this.table = getOrCreateTable(sourceElement, feature, rows);

		if (this.table == null) {
			displayError("Cannot initialize the table"); //$NON-NLS-1$
			return;
		}

		// 4. we configure the table
		final CompoundCommand cc = new CompoundCommand("Configure table command");//$NON-NLS-1$

		// 4.1 we register it into a resource if required
		if (this.table.eResource() == null) {
			cc.append(addTableToResource(domain, this.resource, this.table));
		}

		// 4.2 we configure the table
		configureTable(domain, this.table, sourceElement, feature, rows, cc);

		if (!cc.canExecute()) {
			displayError("The table can't be initialized");//$NON-NLS-1$
			return;
		}
		domain.getCommandStack().execute(cc);
		if (this.table.getContext() == null) {
			displayError("The context of the table hasn't be set");//$NON-NLS-1$
			return;
		}
		// 5. Create the widget
		this.nattableManager = NattableModelManagerFactory.INSTANCE.createNatTableModelManager(this.table, new EObjectSelectionExtractor());
		this.natTableWidget = createNatTableWidget(this.nattableManager, self, SWT.NONE, rows);

		self.addDisposeListener(getDisposeListener());
		// Configure the layout and the layout data
		configureLayout();

		((NattableModelManager) nattableManager).refreshNatTable();
	}

	/**
	 * This allow to create the widgets displayed after the table widget.
	 * 
	 * @param sourceElement
	 *            The source Element.
	 * @param feature
	 *            The feature.
	 * @since 2.0
	 */
	protected void createFollowingWidgets(final EObject sourceElement, final EStructuralFeature feature) {
		// To implement if some widgets are needed after the table widget
	}

	/**
	 * 
	 * @param parent
	 *            the composite parent
	 * @param style
	 *            the style to use to create the nattable widget
	 * @param rows
	 *            the initial rows
	 * @return
	 * 		the created nattable widget
	 * @since 2.0
	 */
	protected NatTable createNatTableWidget(final INattableModelManager manager, final Composite parent, final int style, Collection<?> rows) {
		NatTable natTable = manager.createNattable(self, style, null);
		natTable.setBackground(self.getBackground());
		return natTable;
	}

	/**
	 * 
	 * @param sourceElement
	 *            the source element used to initiatiaze the table
	 * @return
	 * 		the service registry to use for the table displayed in property view
	 * @throws Exception
	 * 
	 *             Duplicated code from org.eclipse.papyrus.junit.utils.rules.ModelSetFixture
	 * @since 2.0
	 */
	protected ServicesRegistry createServiceRegistry(EObject sourceElement) throws Exception {
		ServicesRegistry result = new ServicesRegistry();

		result.add(ModelSet.class, 10, new ModelSet());

		ServiceDescriptor desc = new ServiceDescriptor(TransactionalEditingDomain.class, EditingDomainServiceFactory.class.getName(), ServiceStartKind.STARTUP, 10);// , Collections.singletonList(ResourceSet.class.getName()));
		desc.setServiceTypeKind(ServiceTypeKind.serviceFactory);
		desc.setClassBundleID(Activator.PLUGIN_ID);
		result.add(desc);

		result.startRegistry();
		return result;
	}

	/**
	 * 
	 * @param domain
	 *            the editing domain to use
	 * @param table
	 *            the edited table
	 * @param sourceElement
	 *            the source element (id the context of the table
	 * @param synchronizedFeature
	 *            the feature on which the table is synchronized
	 * @param rows
	 *            the initial rows for the table
	 * @param command
	 *            the compound command used to do additional stuff
	 * 
	 * @since 2.0
	 */
	protected void configureTable(final TransactionalEditingDomain domain, final Table table, final EObject sourceElement, final EStructuralFeature synchronizedFeature, Collection<?> rows, CompoundCommand command) {
		Assert.isNotNull(domain);
		// 1. we register the context of the table
		Command setContextCommand = SetCommand.create(domain, table, NattablePackage.eINSTANCE.getTable_Context(), sourceElement);
		command.append(setContextCommand);
	}

	/**
	 * This allows to configure the tree table.
	 * 
	 * @param nattableManager
	 *            The nattable model manager.
	 * @param sourceElement
	 *            The source Element.
	 * @param feature
	 *            The feature.
	 * @param rows
	 *            The rows of the table.
	 * @deprecated since 2.0, moved into {@link TreeNattablePropertyEditor}
	 */
	@Deprecated
	protected void configureTreeTable(final TreeNattableModelManager nattableManager, final EObject sourceElement, final EStructuralFeature feature, final Collection<?> rows) {
		// Do nothing
	}

	/**
	 * This allows to configure the layout and the layout data.
	 * 
	 * @deprecated since 2.0.0
	 */
	@Deprecated
	protected void configureLayout() {
		// Adapt the group to the table preferred size
		final GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);

		// The preferred height of the nattable calculate it for each row (even if some are hidden)
		// So to calculate the correct height for the composite :
		// - Calculate the header height
		// - Calculate the body height
		// Add these values and add some extra to have correct displays
		final int headerHeight = natTableWidget.getPreferredHeight() - nattableManager.getBodyLayerStack().getRowHideShowLayer().getPreferredHeight();
		final int bodyHeight = nattableManager.getBodyLayerStack().getRowHideShowLayer().getHeight();
		// 16px must be added because of the left area slider
		final int extra = 20 + 16;
		data.minimumHeight = headerHeight + bodyHeight + extra;
		self.setLayoutData(data);

		self.layout();
		natTableWidget.layout();
	}

	/**
	 * This allows to configure the layout and the layout data.
	 * 
	 * @param sourceElement
	 *            The source element.
	 * @since 2.0
	 */
	protected void configureLayout(final EObject sourceElement) {
		// Configure the size of the parent container
		configureSize(sourceElement);

		natTableWidget.layout();

		((NattableModelManager) nattableManager).refreshNatTable();
	}

	/**
	 * This allows to configure the size of the parent container.
	 * 
	 * @param sourceElement
	 *            The source element.
	 * @since 2.0
	 */
	protected void configureSize(final EObject sourceElement) {
		// Adapt the group to the table preferred size
		final GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);

		// The preferred height of the nattable calculate it for each row (even if some are hidden)
		// So to calculate the correct height for the composite :
		// - Calculate the header height
		// - Calculate the body height
		// Add these values and add some extra to have correct displays
		final int headerHeight = natTableWidget.getPreferredHeight() - nattableManager.getBodyLayerStack().getRowHideShowLayer().getPreferredHeight();
		final int bodyHeight = nattableManager.getBodyLayerStack().getRowHideShowLayer().getHeight();
		// 16px must be added because of the left area slider
		final int extra = 20 + 16;
		data.minimumHeight = headerHeight + bodyHeight + extra;
		self.setLayoutData(data);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.papyrus.infra.properties.ui.widgets.AbstractPropertyEditor#updateDescription(java.lang.String)
	 */
	@Override
	protected void updateDescription(String description) {
		self.setToolTipText(description);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.papyrus.infra.properties.ui.widgets.AbstractPropertyEditor#updateLabel(java.lang.String)
	 */
	@Override
	public void updateLabel(final String label) {
		if (showLabel) {
			((Group) self).setText(getLabel());
		}
	}

	/**
	 * This allow to display the error.
	 * 
	 * @param message
	 *            The error message to display.
	 */
	protected void displayError(final String message) {
		final CLabel label = new CLabel(self, SWT.NONE);
		label.setText(message);
		label.setImage(org.eclipse.papyrus.infra.widgets.Activator.getDefault().getImage("icons/error.gif")); //$NON-NLS-1$
	}

	/**
	 * 
	 * @param sourceElement
	 *            the source Element
	 * @param synchronizedFeature
	 *            the synchronized feature
	 * @param rows
	 * @return
	 * 		the existing table or the new created one
	 * @since 2.0
	 */
	protected Table getOrCreateTable(final EObject sourceElement, final EStructuralFeature synchronizedFeature, final Collection<?> rows) {
		Table returnedTable = null;
		final TableConfiguration tableConfiguration = getTableConfiguration();
		if (tableConfiguration == null) {
			return null;
		}

		if (this.serviceRegistry != null) {
			URI tableURI = createTableURI(sourceElement, tableConfiguration);
			final ResourceSet resourceSet = getResourceSet();
			((ModelSet) resourceSet).createModels(tableURI);
			boolean exists = resourceSet.getURIConverter().exists(tableURI, Collections.emptyMap());
			if (exists) {
				this.resource = resourceSet.getResource(tableURI, true);
			} else {
				this.resource = resourceSet.createResource(tableURI);
			}

			Iterator<EObject> iter = this.resource.getContents().iterator();
			while (iter.hasNext() && returnedTable == null) {// the resource should contains only 1 table and this one will get the good type
				EObject object = iter.next();
				if (object instanceof Table) {
					TableConfiguration configuration = ((Table) object).getTableConfiguration();
					if (configuration != null && configuration.getType().equals(getTableConfiguration().getType())) {
						returnedTable = (Table) object;
					}
				}
			}

			if (null == returnedTable) {
				returnedTable = createTable(sourceElement, synchronizedFeature);
			}

		}

		return returnedTable;
	}

	/**
	 * 
	 * @return
	 * 		the resource set to use to load/store emf files
	 * @since 2.0
	 */
	protected ResourceSet getResourceSet() {
		ResourceSet set = null;
		if (this.serviceRegistry != null) {
			try {
				set = this.serviceRegistry.getService(ModelSet.class);
			} catch (ServiceException e) {
				Activator.log.error(e);
			}
		}
		return set;
	}

	/**
	 * 
	 * @param sourceElement
	 *            the source Element
	 * @param tableConfiguration
	 *            the tableConfiguration
	 * @return
	 * 		the URI to use to save and load the table
	 * @since 2.0
	 */
	protected URI createTableURI(final EObject sourceElement, final TableConfiguration tableConfiguration) {
		IPath preferencePath = Activator.getDefault().getStateLocation();
		// we create a folder to save the tables used by the property view and we start to create the name of the model owning the table
		preferencePath = preferencePath.append(TABLES_PREFERENCES_FOLDER_NAME).append(tableConfiguration.getType());

		// we continue to build the path, adding the good suffix to the name of the model
		final StringBuilder b = new StringBuilder().append(preferencePath.toPortableString());
		if (this.registerTableConfigurationByEClass) {
			final ModelElement modelElement = input.getModelElement(propertyPath);
			EClass eClass = null;
			if (modelElement instanceof CompositeModelElement) {
				CompositeModelElement compoModelElement = (CompositeModelElement) modelElement;
				Iterator<ModelElement> iter = compoModelElement.getSubElements().iterator();
				while (eClass == null && iter.hasNext()) {
					ModelElement tmp = iter.next();
					if (tmp instanceof UMLNotationModelElement) {
						EditPart part = ((UMLNotationModelElement) tmp).getEditPart();
						eClass = EMFHelper.getEObject(part).eClass();
					} else if (tmp instanceof EMFModelElement) {
						eClass = ((EMFModelElement) tmp).getSource().eClass();
					}
				}
			}

			if (modelElement instanceof UMLNotationModelElement) {
				EditPart part = ((UMLNotationModelElement) modelElement).getEditPart();
				eClass = EMFHelper.getEObject(part).eClass();
			}
			b.append("_"); //$NON-NLS-1$
			b.append(eClass.getName());
		}
		URI newURI = URI.createFileURI(b.toString()).appendFileExtension(FILE_EXTENSION);
		return newURI;
	}


	/**
	 * This allow to create the nattable.
	 * 
	 * @param sourceElement
	 *            The context element.
	 * @param synchronizedFeature
	 *            The synchronized feature.
	 * @param rows
	 *            The rows of the table.
	 * @return The created table.
	 * 
	 * @since 2.0
	 */
	protected Table createTable(final EObject sourceElement, final EStructuralFeature synchronizedFeature) {
		final TableConfiguration tableConfiguration = getTableConfiguration();
		if (tableConfiguration == null) {
			return null;
		}
		final Table table = NattableFactory.eINSTANCE.createTable();
		table.setTableConfiguration(tableConfiguration);
		final Property property = getModelProperty();
		if (property != null) {
			String description = property.getDescription();
			if (description != null) {
				table.setDescription(description);
			}
		}

		table.setName(getLabel());

		AbstractAxisProvider rowProvider = tableConfiguration.getDefaultRowAxisProvider();
		if (rowProvider == null) {
			rowProvider = NattableaxisproviderFactory.eINSTANCE.createMasterObjectAxisProvider();
		} else {
			rowProvider = EcoreUtil.copy(rowProvider);
		}

		AbstractAxisProvider columnProvider = tableConfiguration.getDefaultColumnAxisProvider();
		if (columnProvider == null) {
			columnProvider = NattableaxisproviderFactory.eINSTANCE.createSlaveObjectAxisProvider();
		} else {
			columnProvider = EcoreUtil.copy(columnProvider);
		}

		table.getColumnAxisProvidersHistory().add(columnProvider);
		table.setCurrentColumnAxisProvider(columnProvider);
		table.getRowAxisProvidersHistory().add(rowProvider);
		table.setCurrentRowAxisProvider(rowProvider);
		for (final Style style : tableConfiguration.getStyles()) {
			table.getStyles().add(EcoreUtil.copy(style));
		}

		// for the table displayed in property view, we want to use all the available place, so we add a specific named style each time
		final BooleanValueStyle fillStyle = NattablestyleFactory.eINSTANCE.createBooleanValueStyle();
		fillStyle.setName(NamedStyleConstants.FILL_COLUMNS_SIZE);
		fillStyle.setBooleanValue(true);
		table.getStyles().add(fillStyle);

		// for the table displayed in property view, we expand all directly
		final BooleanValueStyle expandStyle = NattablestyleFactory.eINSTANCE.createBooleanValueStyle();
		expandStyle.setName(NamedStyleConstants.EXPAND_ALL);
		expandStyle.setBooleanValue(true);
		table.getStyles().add(expandStyle);

		return table;
	}

	/**
	 * This allow to create the nattable.
	 * 
	 * @param sourceElement
	 *            The context element.
	 * @param synchronizedFeature
	 *            The synchronized feature.
	 * @param rows
	 *            The rows of the table.
	 * @return The created table.
	 * 
	 * @deprecated since 2.0, use the same method without the collections of rows as arguments. Rows are set later in the new implementation
	 */
	@Deprecated
	protected Table createTable(final EObject sourceElement, final EStructuralFeature synchronizedFeature, final Collection<?> rows) {
		final TableConfiguration tableConfiguration = getTableConfiguration();
		if (tableConfiguration == null) {
			return null;
		}
		final Table table = NattableFactory.eINSTANCE.createTable();
		table.setTableConfiguration(tableConfiguration);
		final Property property = getModelProperty();
		if (property != null) {
			String description = property.getDescription();
			if (description != null) {
				table.setDescription(description);
			}
		}

		table.setName(getLabel());

		AbstractAxisProvider rowProvider = tableConfiguration.getDefaultRowAxisProvider();
		if (rowProvider == null) {
			rowProvider = NattableaxisproviderFactory.eINSTANCE.createMasterObjectAxisProvider();
		} else {
			rowProvider = EcoreUtil.copy(rowProvider);
		}

		AbstractAxisProvider columnProvider = tableConfiguration.getDefaultColumnAxisProvider();
		if (columnProvider == null) {
			columnProvider = NattableaxisproviderFactory.eINSTANCE.createSlaveObjectAxisProvider();
		} else {
			columnProvider = EcoreUtil.copy(columnProvider);
		}

		if (null != synchronizedFeature) {
			TableHeaderAxisConfiguration rowHeaderAxisconfig = tableConfiguration.getRowHeaderAxisConfiguration();
			for (IAxisConfiguration axisConfig : rowHeaderAxisconfig.getOwnedAxisConfigurations()) {
				if (axisConfig instanceof EStructuralFeatureValueFillingConfiguration) {
					((EStructuralFeatureValueFillingConfiguration) axisConfig).setListenFeature(synchronizedFeature);
				}
			}
		}
		table.getColumnAxisProvidersHistory().add(columnProvider);
		table.setCurrentColumnAxisProvider(columnProvider);
		table.getRowAxisProvidersHistory().add(rowProvider);
		table.setCurrentRowAxisProvider(rowProvider);
		for (final Style style : tableConfiguration.getStyles()) {
			table.getStyles().add(EcoreUtil.copy(style));
		}

		return table;
	}


	/**
	 * This allow to add the tree item axis.
	 * 
	 * @param axisProvider
	 *            The axis provider.
	 * @param rep
	 *            The axis manager representation.
	 * @param object
	 *            The object to add.
	 * 
	 * @deprecated since 2.0, moved into {@link TreeNattablePropertyEditor} with command
	 */
	@Deprecated
	protected void addTreeItemAxis(final AbstractAxisProvider axisProvider, final AxisManagerRepresentation rep, final Object object) {
		if (object instanceof View && isStereotypedElement((View) object)) {
			TransactionalEditingDomain domain = getTableEditingDomain();
			final IAxis axis = ITreeItemAxisHelper.createITreeItemAxis(null, null, object, rep);
			Command addCommand = AddCommand.create(getTableEditingDomain(), axisProvider, NattableaxisproviderPackage.eINSTANCE.getAxisProvider_Axis(), Collections.singleton(axis));
			domain.getCommandStack().execute(addCommand);
		}
	}

	/**
	 * 
	 * @return
	 * 		the editing domain to use
	 * 
	 * @since 2.0
	 */
	protected TransactionalEditingDomain getTableEditingDomain() {
		try {
			return this.serviceRegistry.getService(TransactionalEditingDomain.class);
		} catch (ServiceException e) {
			Activator.log.error(e);
		}
		return null;
	}

	/**
	 * Check is the element of the view is stereotyped.
	 * 
	 * @param view
	 *            The view.
	 * @return <code>true</code> if the element of view is stereotyped, <code>false</code> otherwise.
	 */
	protected boolean isStereotypedElement(final View view) {
		boolean result = false;
		if (view.getElement() instanceof Element && !((Element) view.getElement()).getAppliedStereotypes().isEmpty()) {
			result = true;
		}
		return result;
	}

	/**
	 * Get the table configuration (from the table configuration URI).
	 * 
	 * @return The table configuration.
	 */
	protected TableConfiguration getTableConfiguration() {
		if (this.tableConfiguration == null) {
			ResourceSet resourceSet = getResourceSet();
			if (resourceSet != null) {
				try {
					this.tableConfiguration = (TableConfiguration) EMFHelper.loadEMFModel(resourceSet, this.tableConfigURI);
				} catch (Exception ex) {
					Activator.log.error("Invalid table configuration", ex); //$NON-NLS-1$
				}
			}
		}
		return this.tableConfiguration;
	}

	/**
	 * This allow to create the dispose listener for the nattable table manager.
	 * 
	 * @return The dispose nattable manager listener.
	 */
	protected DisposeListener getDisposeListener() {
		if (null == this.nattableDisposeListener) {
			this.nattableDisposeListener = new DisposeListener() {

				public void widgetDisposed(DisposeEvent e) {
					disposeListener();
				}
			};
		}
		return nattableDisposeListener;
	}

	/**
	 * This allows to dispose the listeners.
	 * 
	 * @since 2.0
	 */
	protected void disposeListener() {
		if (NattablePropertyEditor.this.serviceRegistry != null) {
			// we dispose it to avoid unecessary refresh
			if (null != this.nattableManager) {
				this.nattableManager.dispose();
			}
			if (null != this.natTableWidget) {
				this.natTableWidget.dispose();
			}
			TransactionalEditingDomain domain = getTableEditingDomain();
			if (domain != null && this.table != null) {
				Command cmd = getDisposeTableCommand(domain, this.table);
				domain.getCommandStack().execute(cmd);
			}
			if (NattablePropertyEditor.this.resource != null) {
				try {
					NattablePropertyEditor.this.resource.save(saveOptions);
				} catch (IOException e1) {
					Activator.log.error(e1);
				}
			}
			try {
				NattablePropertyEditor.this.serviceRegistry.disposeRegistry();
			} catch (ServiceMultiException e1) {
				Activator.log.error(e1);
			}
			NattablePropertyEditor.this.serviceRegistry = null;
			NattablePropertyEditor.this.table = null;

		}
	}

	/**
	 * 
	 * @param domain
	 *            the editing domain
	 * @param table
	 *            the table to clean before dispose
	 * @return
	 * 		the command to use to clean the table before disposing it
	 * @since 2.0
	 */
	protected CompoundCommand getDisposeTableCommand(final TransactionalEditingDomain domain, final Table table) {
		CompoundCommand disposeCommand = new CompoundCommand("Command used to clean the table before disposing it"); //$NON-NLS-1$
		disposeCommand.append(SetCommand.create(domain, table, NattablePackage.eINSTANCE.getTable_Context(), null));
		disposeCommand.append(SetCommand.create(domain, table, NattablePackage.eINSTANCE.getTable_Owner(), null));
		// assuming the table is synchronized and not inverted :
		disposeCommand.append(SetCommand.create(domain, table.getCurrentRowAxisProvider(), NattableaxisproviderPackage.eINSTANCE.getAxisProvider_Axis(), Collections.emptyList()));

		return disposeCommand;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.papyrus.infra.properties.ui.widgets.AbstractPropertyEditor#unhookDataSourceListener(org.eclipse.papyrus.infra.properties.ui.modelelement.DataSource)
	 */
	@Override
	protected void unhookDataSourceListener(DataSource oldInput) {
		oldInput.removeDataSourceListener(getDataSourceListener());
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.papyrus.infra.properties.ui.widgets.AbstractPropertyEditor#hookDataSourceListener(org.eclipse.papyrus.infra.properties.ui.modelelement.DataSource)
	 */
	@Override
	protected void hookDataSourceListener(DataSource newInput) {
		newInput.addDataSourceListener(getDataSourceListener());
	}

	/**
	 * This allow to create the data source listener.
	 * 
	 * @return The created data source listener.
	 */
	private IDataSourceListener getDataSourceListener() {
		if (dataSourceListener == null) {
			dataSourceListener = new IDataSourceListener() {

				public void dataSourceChanged(final DataSourceChangedEvent event) {
					// bug 494537 - The diagram selection changed, but the property view has not been disposed
					disposeListener();
					// Bug 492560: The self children control was not all disposed correclty
					if (null != self) {
						if (self.getChildren().length > 0) {
							for (Control control : self.getChildren()) {
								control.dispose();
							}
						}
						self.removeDisposeListener(getDisposeListener());
						nattableDisposeListener = null;
						self.layout();
					}
					// Get the datasource
					final DataSource dataSource = event.getDataSource();
					final StructuredSelection selection = (StructuredSelection) dataSource.getSelection();

					// Manage the context selection
					final List<Object> contexts = new ArrayList<Object>(selection.size());
					final Iterator<?> selectionIterator = selection.iterator();
					while (selectionIterator.hasNext()) {
						Object selectedObject = selectionIterator.next();
						if (selectedObject instanceof AbstractEditPart) {
							contexts.add(((AbstractEditPart) selectedObject).getModel());
						} else {
							contexts.add(selectedObject);
						}
					}

					// Get the model element
					if (0 < contexts.size()) {
						final ModelElement modelElement = dataSource.getModelElement(propertyPath);
						EObject sourceElement = getEObjectAsTableContext(EMFHelper.getEObject(contexts.get(0)));
						EStructuralFeature feature = null;
						if (modelElement instanceof CompositeModelElement) {
							if (!((CompositeModelElement) modelElement).getSubElements().isEmpty()) {
								if (((CompositeModelElement) modelElement).getSubElements().get(0) instanceof EMFModelElement) {
									final EMFModelElement emfModelElement = (EMFModelElement) ((CompositeModelElement) modelElement).getSubElements().get(0);
									feature = emfModelElement.getFeature(getLocalPropertyPath());
								}
							}
						} else if (modelElement instanceof EMFModelElement) {
							final EMFModelElement emfModelElement = (EMFModelElement) modelElement;
							feature = emfModelElement.getFeature(getLocalPropertyPath());
						}

						// Recreate the table widget, its adjuncts, and their layout
						createWidgets(sourceElement, feature, contexts);
					}
				}
			};
		}

		return dataSourceListener;
	}

	/**
	 * This allows to get the table context as EObject (and avoid View).
	 * 
	 * @param element
	 *            The initial source element.
	 * @return The source element defining Table context.
	 * @since 2.1
	 */
	protected EObject getEObjectAsTableContext(final EObject element) {
		EObject result = element;
		if (result instanceof View) {
			result = ((View) result).getElement();
		}
		return result;
	}

	/**
	 * 
	 * @param domain
	 *            the editing domain to use
	 * @param resource
	 *            the resource where the table must be saved
	 * @param table
	 *            the table to add to the resource
	 * @return
	 * 		the command to add the table to the resource
	 */
	private static final Command addTableToResource(final TransactionalEditingDomain domain, final Resource resource, final Table table) {
		return new RecordingCommand(domain) {

			@Override
			protected void doExecute() {
				resource.getContents().add(table);
			}
		};
	}
}

Back to the top