Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 3a2d7ca61be2f007c741601575f80cde9082cbd3 (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
/*****************************************************************************
 * Copyright (c) 2012 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:
 *  Vincent Lorenzo (CEA LIST) vincent.lorenzo@cea.fr - Initial API and implementation
 *
 *****************************************************************************/
package org.eclipse.papyrus.infra.nattable.manager.table;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EventObject;
import java.util.List;

import org.eclipse.core.commands.State;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.command.CompoundCommand;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.window.Window;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.ui.NatEventData;
import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper;
import org.eclipse.papyrus.infra.nattable.command.CommandIds;
import org.eclipse.papyrus.infra.nattable.dialog.DisplayedAxisSelectorDialog;
import org.eclipse.papyrus.infra.nattable.manager.axis.AxisManagerFactory;
import org.eclipse.papyrus.infra.nattable.manager.axis.CompositeAxisManager;
import org.eclipse.papyrus.infra.nattable.manager.axis.IAxisManager;
import org.eclipse.papyrus.infra.nattable.manager.axis.ICompositeAxisManager;
import org.eclipse.papyrus.infra.nattable.manager.cell.CellManagerFactory;
import org.eclipse.papyrus.infra.nattable.messages.Messages;
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.nattableaxisconfiguration.AbstractHeaderAxisConfiguration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisconfiguration.AxisManagerRepresentation;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisprovider.AbstractAxisProvider;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisprovider.IMasterAxisProvider;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisprovider.ISlaveAxisProvider;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableaxisprovider.NattableaxisproviderPackage;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableconfiguration.CellEditorDeclaration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattableconfiguration.NattableconfigurationPackage;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattablelabelprovider.FeatureLabelProviderConfiguration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattablelabelprovider.ILabelProviderConfiguration;
import org.eclipse.papyrus.infra.nattable.model.nattable.nattablelabelprovider.ObjectLabelProviderConfiguration;
import org.eclipse.papyrus.infra.nattable.utils.AxisUtils;
import org.eclipse.papyrus.infra.nattable.utils.HeaderAxisConfigurationManagementUtils;
import org.eclipse.papyrus.infra.nattable.utils.NattableConfigAttributes;
import org.eclipse.papyrus.infra.nattable.utils.StringComparator;
import org.eclipse.papyrus.infra.nattable.utils.TableEditingDomainuUtils;
import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
import org.eclipse.papyrus.infra.services.labelprovider.service.LabelProviderService;
import org.eclipse.papyrus.infra.widgets.providers.FlattenableRestrictedFilteredContentProvider;
import org.eclipse.papyrus.infra.widgets.providers.IRestrictedContentProvider;
import org.eclipse.papyrus.infra.widgets.providers.IStaticContentProvider;
import org.eclipse.papyrus.infra.widgets.selectors.ReferenceSelector;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;

public class NattableModelManager extends AbstractNattableWidgetManager implements INattableModelManager, IAdaptable {

	/**
	 * the column manager
	 */
	private ICompositeAxisManager columnManager;

	/**
	 * the line manager
	 */
	private ICompositeAxisManager rowManager;

	/**
	 * the model of the table on which we are working
	 */
	private List<Object> verticalElements;

	private List<Object> horizontalElements;

	private Adapter invertAxisListener;

	private AbstractAxisProvider rowProvider;

	private AbstractAxisProvider columnProvider;

	/**
	 * this listener listen the stack events and refresh nattable
	 */
	private CommandStackListener refreshListener;

	/**
	 * the focus listener
	 */
	private FocusListener focusListener;

	/**
	 * we need to keep it to be able to remove listener (required when we destroy the context of the table)
	 */
	private TransactionalEditingDomain contextEditingDomain;

	private Adapter changeAxisProvider;

	private AdapterImpl changeAxisProviderHistory;


	/**
	 * 
	 * Constructor.
	 * 
	 * @param rawModel
	 * 
	 *        the model of the managed table
	 */
	public NattableModelManager(final Table rawModel) {
		super(rawModel);
		this.rowProvider = rawModel.getCurrentRowAxisProvider();
		this.columnProvider = rawModel.getCurrentColumnAxisProvider();
		this.verticalElements = Collections.synchronizedList(new ArrayList<Object>());
		this.horizontalElements = Collections.synchronizedList(new ArrayList<Object>());


		this.invertAxisListener = new AdapterImpl() {

			@Override
			public void notifyChanged(Notification msg) {
				if(msg.getEventType() == Notification.SET) {
					final Object oldValue = msg.getOldValue();
					final Object newValue = msg.getNewValue();
					if(oldValue != null && newValue != null) {
						if(msg.getFeature() == NattablePackage.eINSTANCE.getTable_InvertAxis()) {
							invertJavaObject();

						}
					}
				}
			}
		};

		rawModel.eAdapters().add(this.invertAxisListener);
		init();
		if(rawModel.isInvertAxis()) {
			invertJavaObject();
		}

		changeAxisProvider = new AdapterImpl() {

			public void notifyChanged(final Notification msg) {
				if(msg.getFeature() == NattablePackage.eINSTANCE.getTable_CurrentColumnAxisProvider() || msg.getFeature() == NattablePackage.eINSTANCE.getTable_CurrentRowAxisProvider()) {

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

						@Override
						public void run() {
							init();
							refreshNatTable();
						}
					});
				}
			}

		};

		changeAxisProviderHistory = new AdapterImpl() {

			public void notifyChanged(final Notification msg) {
				if(msg.getFeature() == NattablePackage.eINSTANCE.getTable_ColumnAxisProvidersHistory() || msg.getFeature() == NattablePackage.eINSTANCE.getTable_RowAxisProvidersHistory()) {

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

						@Override
						public void run() {
							init();
						}
					});
				}
			}

		};

		rawModel.eAdapters().add(changeAxisProvider);

	}


	@Override
	public NatTable createNattable(Composite parent, int style, IWorkbenchPartSite site) {
		final NatTable nattable = super.createNattable(parent, style, site);
		this.refreshListener = new CommandStackListener() {

			/**
			 * 
			 * @see org.eclipse.emf.common.command.CommandStackListener#commandStackChanged(java.util.EventObject)
			 * 
			 * @param event
			 */
			public void commandStackChanged(EventObject event) {
				//we refresh the table after each command, only when it is visible
				//its allows to refresh the text and the appearance of the table
				//this refresh doesn't manage the add/remove axis
				Display.getDefault().asyncExec(new Runnable() {

					public void run() {
						if(nattable != null && !nattable.isDisposed() && nattable.isVisible()) {
							nattable.refresh();
						}
					}
				});

			}
		};

		getContextEditingDomain().getCommandStack().addCommandStackListener(this.refreshListener);

		this.focusListener = new FocusListener() {

			public void focusLost(FocusEvent e) {
				//nothing to do
			}

			public void focusGained(FocusEvent e) {
				updateToggleActionState();
			}
		};
		nattable.addFocusListener(this.focusListener);
		updateToggleActionState();//required, because the focus listener is not notified just after the creation of the widget
		return nattable;
	}

	/**
	 * this command update the status of the toggle actions
	 */
	protected void updateToggleActionState() {
		final ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getService(ICommandService.class);
		if(commandService != null) {

			final AbstractHeaderAxisConfiguration columnAxisConfiguration = HeaderAxisConfigurationManagementUtils.getColumnAbstractHeaderAxisUsedInTable(getTable());
			final AbstractHeaderAxisConfiguration rowAxisConfiguration = HeaderAxisConfigurationManagementUtils.getRowAbstractHeaderAxisUsedInTable(getTable());
			//update the header configuration
			org.eclipse.core.commands.Command command = commandService.getCommand(CommandIds.COMMAND_COLUMN_DISPLAY_INDEX_ID);
			updateToggleCommandState(command, columnAxisConfiguration.isDisplayIndex());

			command = commandService.getCommand(CommandIds.COMMAND_COLUMN_DISPLAY_LABEL_ID);
			updateToggleCommandState(command, columnAxisConfiguration.isDisplayLabel());

			command = commandService.getCommand(CommandIds.COMMAND_COLUMN_DISPLAY_INDEX_STYLE_ID);
			updateRadioCommandState(command, columnAxisConfiguration.getIndexStyle().getLiteral());

			command = commandService.getCommand(CommandIds.COMMAND_ROW_DISPLAY_INDEX_ID);
			updateToggleCommandState(command, rowAxisConfiguration.isDisplayIndex());

			command = commandService.getCommand(CommandIds.COMMAND_ROW_DISPLAY_LABEL_ID);
			updateToggleCommandState(command, rowAxisConfiguration.isDisplayLabel());

			command = commandService.getCommand(CommandIds.COMMAND_ROW_DISPLAY_INDEX_STYLE_ID);
			updateRadioCommandState(command, rowAxisConfiguration.getIndexStyle().getLiteral());


			//update the label header configuration
			final List<ILabelProviderConfiguration> columnLabelConfigurations = columnAxisConfiguration.getOwnedLabelConfigurations();
			final List<ILabelProviderConfiguration> rowLabelConfigurations = rowAxisConfiguration.getOwnedLabelConfigurations();
			for(final ILabelProviderConfiguration current : columnLabelConfigurations) {
				if(current instanceof ObjectLabelProviderConfiguration) {
					final ObjectLabelProviderConfiguration labelConfig = (ObjectLabelProviderConfiguration)current;
					command = commandService.getCommand(CommandIds.COMMAND_COLUMN_LABEL_DISPLAY_ICON);
					updateToggleCommandState(command, labelConfig.isDisplayIcon());

					command = commandService.getCommand(CommandIds.COMMAND_COLUMN_LABEL_DISPLAY_LABEL);
					updateToggleCommandState(command, labelConfig.isDisplayLabel());

					if(labelConfig instanceof FeatureLabelProviderConfiguration) {
						final FeatureLabelProviderConfiguration labelFeatureConf = (FeatureLabelProviderConfiguration)labelConfig;
						command = commandService.getCommand(CommandIds.COMMAND_COLUMN_LABEL_FEATURE_DISPLAY_IS_DERIVED);
						updateToggleCommandState(command, labelFeatureConf.isDisplayIsDerived());

						command = commandService.getCommand(CommandIds.COMMAND_COLUMN_LABEL_FEATURE_DISPLAY_MULTIPLICITY);
						updateToggleCommandState(command, labelFeatureConf.isDisplayMultiplicity());

						command = commandService.getCommand(CommandIds.COMMAND_COLUMN_LABEL_FEATURE_DISPLAY_TYPE);
						updateToggleCommandState(command, labelFeatureConf.isDisplayType());


						command = commandService.getCommand(CommandIds.COMMAND_COLUMN_LABEL_FEATURE_DISPLAY_NAME);
						updateToggleCommandState(command, labelFeatureConf.isDisplayName());
					}
				}
			}

			for(final ILabelProviderConfiguration current : rowLabelConfigurations) {
				if(current instanceof ObjectLabelProviderConfiguration) {
					final ObjectLabelProviderConfiguration labelConfig = (ObjectLabelProviderConfiguration)current;

					command = commandService.getCommand(CommandIds.COMMAND_ROW_LABEL_DISPLAY_ICON);
					updateToggleCommandState(command, labelConfig.isDisplayIcon());

					command = commandService.getCommand(CommandIds.COMMAND_ROW_LABEL_DISPLAY_LABEL);
					updateToggleCommandState(command, labelConfig.isDisplayLabel());

					if(labelConfig instanceof FeatureLabelProviderConfiguration) {
						final FeatureLabelProviderConfiguration labelFeatureConf = (FeatureLabelProviderConfiguration)labelConfig;
						command = commandService.getCommand(CommandIds.COMMAND_ROW_LABEL_FEATURE_DISPLAY_IS_DERIVED);
						updateToggleCommandState(command, labelFeatureConf.isDisplayIsDerived());

						command = commandService.getCommand(CommandIds.COMMAND_ROW_LABEL_FEATURE_DISPLAY_MULTIPLICITY);
						updateToggleCommandState(command, labelFeatureConf.isDisplayMultiplicity());

						command = commandService.getCommand(CommandIds.COMMAND_ROW_LABEL_FEATURE_DISPLAY_TYPE);
						updateToggleCommandState(command, labelFeatureConf.isDisplayType());

						command = commandService.getCommand(CommandIds.COMMAND_ROW_LABEL_FEATURE_DISPLAY_NAME);
						updateToggleCommandState(command, labelFeatureConf.isDisplayName());
					}
				}
			}

			//update the property IMasterObjectAxisProvider#disconnectslave
			if(columnProvider instanceof ISlaveAxisProvider) {
				command = commandService.getCommand(CommandIds.COMMAND_ROW_DISCONNECT_SLAVE);
				updateToggleCommandState(command, ((IMasterAxisProvider)rowProvider).isDisconnectSlave());
			}

			if(rowProvider instanceof ISlaveAxisProvider) {
				command = commandService.getCommand(CommandIds.COMMAND_COLUMN_DISCONNECT_SLAVE);
				updateToggleCommandState(command, ((IMasterAxisProvider)columnProvider).isDisconnectSlave());
			}

			//we update the state for the invert axis command
			command = commandService.getCommand(CommandIds.COMMAND_INVERT_AXIS);
			updateToggleCommandState(command, getTable().isInvertAxis());

		} else {
			throw new RuntimeException(String.format("The Eclipse service {0} has not been found", ICommandService.class)); //$NON-NLS-1$
		}

	}

	/**
	 * 
	 * @param command
	 *        an eclipse command
	 * @param newValue
	 *        the new boolean value to set to the state of this command
	 */
	private void updateToggleCommandState(final org.eclipse.core.commands.Command command, final boolean newValue) {
		if(command != null) {
			final State state = command.getState(CommandIds.TOGGLE_STATE);
			if(state != null) {
				state.setValue(newValue);
			}
		}
	}

	/**
	 * 
	 * @param command
	 *        an eclispe command
	 * @param newValue
	 *        the new value to set to the state of this command
	 */
	private void updateRadioCommandState(final org.eclipse.core.commands.Command command, final Object newValue) {
		if(command != null) {
			final State state = command.getState(CommandIds.RADIO_STATE);
			if(state != null) {
				state.setValue(newValue);
			}
		}
	}

	public void invertJavaObject() {
		AbstractAxisProvider newColumProvider = this.rowProvider;
		AbstractAxisProvider newRowProvider = this.columnProvider;
		List<Object> newVerticalElementList = this.horizontalElements;
		List<Object> newHorizontalElementList = this.verticalElements;
		ICompositeAxisManager newRowManager = this.columnManager;
		ICompositeAxisManager newColumnManager = this.rowManager;

		NattableModelManager.this.columnProvider = newColumProvider;
		NattableModelManager.this.rowProvider = newRowProvider;

		NattableModelManager.this.verticalElements = newVerticalElementList;
		NattableModelManager.this.horizontalElements = newHorizontalElementList;

		NattableModelManager.this.rowManager = newRowManager;
		NattableModelManager.this.columnManager = newColumnManager;
		updateToggleActionState();
		configureNatTable();
		refreshNatTable();
	}

	/**
	 * create the line and the columns managers
	 */
	protected void init() {
		if(this.columnManager != null) {
			this.columnManager.dispose();
		}
		if(this.rowManager != null) {
			this.rowManager.dispose();
		}
		this.columnProvider = getTable().getCurrentColumnAxisProvider();
		this.rowProvider = getTable().getCurrentRowAxisProvider();
		this.columnManager = createAxisManager(getTable().getTableConfiguration().getColumnHeaderAxisConfiguration().getAxisManagers(), getTable().getCurrentColumnAxisProvider());
		this.rowManager = createAxisManager(getTable().getTableConfiguration().getRowHeaderAxisConfiguration().getAxisManagers(), getTable().getCurrentRowAxisProvider());

		boolean allIsSlave = this.columnManager.isSlave() && this.rowManager.isSlave();
		Assert.isTrue(!allIsSlave, Messages.NattableModelManager_AtLeastOfOneTheAxisManagerMustBeAMaster);
	}

	/**
	 * 
	 * @param ids
	 *        the ids of the axis manager to use
	 * @param contentProvider
	 *        the content provider in the model
	 * @return the created axis manager to use to manage the {@link IAxisContentsProvider}
	 */
	protected ICompositeAxisManager createAxisManager(final List<AxisManagerRepresentation> representations, final AbstractAxisProvider contentProvider) {
		final List<IAxisManager> managers = new ArrayList<IAxisManager>();
		for(AxisManagerRepresentation current : representations) {
			final IAxisManager manager = AxisManagerFactory.INSTANCE.getAxisManager(current);
			assert manager != null;
			manager.init(this, current, contentProvider);
			managers.add(manager);
		}
		final ICompositeAxisManager compositeAxisManager = new CompositeAxisManager();
		compositeAxisManager.init(this, null, contentProvider);
		compositeAxisManager.setSubAxisManager(managers);
		return compositeAxisManager;
	}


	/**
	 * 
	 * @see org.eclipse.ui.services.IDisposable#dispose()
	 * 
	 */
	@Override
	public void dispose() {
		this.columnManager.dispose();
		this.rowManager.dispose();
		getContextEditingDomain().getCommandStack().removeCommandStackListener(this.refreshListener);
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#addRows(java.util.Collection)
	 * 
	 * @param objectsToAdd
	 *        the list of the objects to add in rows
	 */
	public void addRows(final Collection<Object> objectsToAdd) {
		final EditingDomain domain = getContextEditingDomain();
		final Command cmd = getAddRowElementCommand(objectsToAdd);
		if(cmd != null && cmd.canExecute()) {
			domain.getCommandStack().execute(cmd);
		}
	}

	/**
	 * called when the manager is used vertically
	 */
	public int getColumnCount() {
		return this.getColumnElementsList().size();
	}

	/**
	 * called when the manager is used horizontally
	 */

	public int getRowCount() {
		return this.getRowElementsList().size();
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#addColumns(java.util.Collection)
	 * 
	 * @param objectsToAdd
	 *        the list of the objects to add in columns
	 */
	public void addColumns(final Collection<Object> objectsToAdd) {
		final EditingDomain domain = getContextEditingDomain();
		final Command cmd = getAddColumnElementCommand(objectsToAdd);
		if(cmd != null && cmd.canExecute()) {
			domain.getCommandStack().execute(cmd);
		}
	}

	/**
	 * Returns the EditingDomain associated to the table
	 * 
	 * @return
	 */
	private EditingDomain getTableEditingDomain() {
		return TableEditingDomainuUtils.getTableContextEditingDomain(getTable());
	}

	/**
	 * Returns the EditingDomain associated to the context
	 * 
	 * @return
	 */
	private EditingDomain getContextEditingDomain() {
		return TableEditingDomainuUtils.getTableContextEditingDomain(getTable());
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#getBodyDataProvider()
	 * 
	 * @return the data provider for the body of the table
	 */
	public IDataProvider getBodyDataProvider() {
		return this;
	}

	/**
	 * 
	 * @see org.eclipse.nebula.widgets.nattable.data.IDataProvider#getDataValue(int, int)
	 * 
	 * @param columnIndex
	 *        the index of the column
	 * @param rowIndex
	 *        the index of the row
	 * @return the contents to display in the cell localted to columnIndex and
	 *         rowIndex
	 */
	public Object getDataValue(final int columnIndex, final int rowIndex) {
		final Object row;
		final Object column;
		final Object obj1 = this.verticalElements.get(columnIndex);
		final Object obj2 = this.horizontalElements.get(rowIndex);
		if(getTable().isInvertAxis()) {
			column = obj2;
			row = obj1;
		} else {
			row = obj2;
			column = obj1;
		}
		return CellManagerFactory.INSTANCE.getCrossValue(column, row, this);
	}

	public void setDataValue(final int columnIndex, final int rowIndex, final Object newValue) {
		final Object row;
		final Object column;
		final Object obj1 = this.verticalElements.get(columnIndex);
		final Object obj2 = this.horizontalElements.get(rowIndex);
		if(getTable().isInvertAxis()) {
			column = obj2;
			row = obj1;
		} else {
			row = obj2;
			column = obj1;
		}
		CellManagerFactory.INSTANCE.setCellValue((TransactionalEditingDomain)getContextEditingDomain(), column, row, newValue, this);
	}

	/**
	 * refresh NatTable (asyncExec)
	 */
	public void refreshNatTable() {
		Display.getDefault().asyncExec(new Runnable() {

			public void run() {
				NattableModelManager.this.natTable.refresh();
			}
		});
	}


	/**
	 * 
	 * @param axis
	 *        the axis for which must refresh the contents
	 */
	public void updateAxisContents(final AbstractAxisProvider axis) {
		Display.getDefault().asyncExec(new Runnable() {//required, because we get the event before the changes

			public void run() {
				if(NattableModelManager.this.natTable != null && !NattableModelManager.this.natTable.isDisposed()) {
					if(axis == NattableModelManager.this.columnProvider) {
						updateColumnContents();
					} else {
						updateRowContents();
					}
				}
			}
		});
	}

	/**
	 * refresh the row contents
	 */
	private void updateRowContents() {
		NattableModelManager.this.rowManager.updateAxisContents();
		CellEditorDeclaration declaration = getCellEditorDeclarationToUse(getTable());
		if(declaration.equals(CellEditorDeclaration.ROW)) {
			configureNatTable();
			refreshNatTable();
		} else {
			refreshNatTable();
		}
	}



	/**
	 * refresh the column contents
	 */
	private void updateColumnContents() {
		NattableModelManager.this.columnManager.updateAxisContents();
		CellEditorDeclaration declaration = getCellEditorDeclarationToUse(getTable());
		if(declaration.equals(CellEditorDeclaration.COLUMN)) {
			configureNatTable();
			refreshNatTable();
		} else {
			refreshNatTable();
		}
	}

	/**
	 * 
	 * @param table
	 *        the table
	 * @return
	 *         the celleditor declaration to use according to the table configuration and {@link Table#isInvertAxis()}
	 */
	private CellEditorDeclaration getCellEditorDeclarationToUse(final Table table) {
		CellEditorDeclaration declaration = table.getTableConfiguration().getCellEditorDeclaration();
		if(getTable().isInvertAxis()) {
			if(declaration.equals(CellEditorDeclaration.COLUMN)) {
				declaration = CellEditorDeclaration.ROW;
			} else if(declaration.equals(CellEditorDeclaration.ROW)) {
				declaration = CellEditorDeclaration.COLUMN;
			}
		}
		return declaration;
	}

	public List<Object> getColumnElementsList() {
		return this.verticalElements;
	}

	public List<Object> getRowElementsList() {
		return this.horizontalElements;
	}

	public boolean canInsertRow(Collection<Object> objectsToAdd, int index) {
		return this.rowManager.canInsertAxis(objectsToAdd, index);
	}

	public boolean canInsertColumns(Collection<Object> objectsToAdd, int index) {
		return this.columnManager.canInsertAxis(objectsToAdd, index);
	}

	public boolean canDropColumnsElement(Collection<Object> objectsToAdd) {
		return this.columnManager.canDropAxisElement(objectsToAdd);
	}

	public boolean canDropRowElement(Collection<Object> objectsToAdd) {
		return this.rowManager.canDropAxisElement(objectsToAdd);
	}

	public void insertRows(Collection<Object> objectsToAdd, int index) {
		this.rowManager.getInsertAxisCommand(objectsToAdd, index);

	}

	public void insertColumns(Collection<Object> objectsToAdd, int index) {
		this.columnManager.getInsertAxisCommand(objectsToAdd, index);
	}

	public Object getColumnElement(int index) {
		return this.verticalElements.get(index);
	}

	public Object getRowElement(int index) {
		return this.horizontalElements.get(index);
	}

	public List<Object> getElementsList(AbstractAxisProvider axisProvider) {
		if(axisProvider == this.columnProvider) {
			return this.verticalElements;
		} else if(axisProvider == this.rowProvider) {
			return this.horizontalElements;
		}
		return null;
	}

	public boolean canMoveRows() {
		return this.rowManager.canMoveAxis();
	}

	public boolean canMoveColumns() {
		return this.columnManager.canMoveAxis();
	}

	public void moveColumnElement(final Object axisToMove, final int newIndex) {
		this.columnManager.moveAxis(axisToMove, newIndex);
	}

	// not tested
	public void moveRowElement(final Object axisToMove, final int newIndex) {
		this.rowManager.moveAxis(axisToMove, newIndex);
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#invertAxis()
	 * 
	 */
	public void invertAxis() {
		final CompoundCommand cmd = new CompoundCommand(Messages.NattableModelManager_SwitchLinesAndColumns);
		final EditingDomain domain = getContextEditingDomain();
		boolean oldValue = getTable().isInvertAxis();
		if(canInvertAxis()) {
			Command tmp = new SetCommand(domain, getTable(), NattablePackage.eINSTANCE.getTable_InvertAxis(), !oldValue);
			cmd.append(tmp);
			domain.getCommandStack().execute(cmd);
		}
	}

	public boolean canInvertAxis() {
		return this.columnManager.canBeUsedAsRowManager() && this.rowManager.canBeUsedAsColumnManager();
	}

	public boolean canCreateRowElement(String elementType) {
		return this.rowManager.canCreateAxisElement(elementType);
	}

	public boolean canCreateColumnElement(String elementType) {
		// TODO Auto-generated method stub
		return true;
	}

	public Command getAddRowElementCommand(Collection<Object> objectsToAdd) {
		final EditingDomain domain = getContextEditingDomain();
		final CompoundCommand cmd = new CompoundCommand(Messages.NattableModelManager_AddRowCommand);
		Command tmp = this.rowManager.getAddAxisCommand(domain, objectsToAdd);
		if(tmp != null) {
			cmd.append(tmp);
		}
		final AbstractAxisProvider rowsProvider = AxisUtils.getAxisProviderUsedForRows(this);
		final AbstractAxisProvider columnsProvider = AxisUtils.getAxisProviderUsedForColumns(this);
		boolean addComplementaryAxis = rowsProvider instanceof IMasterAxisProvider && columnsProvider instanceof ISlaveAxisProvider && !((IMasterAxisProvider)rowsProvider).isDisconnectSlave();
		if(addComplementaryAxis) {
			tmp = this.columnManager.getComplementaryAddAxisCommand(domain, objectsToAdd);
			if(tmp != null) {
				cmd.append(tmp);
			}
		}
		return cmd;
	}

	public Command getAddColumnElementCommand(Collection<Object> objectsToAdd) {
		final EditingDomain domain = getContextEditingDomain();
		final CompoundCommand cmd = new CompoundCommand(Messages.NattableModelManager_AddColumnCommand);
		Command tmp = this.columnManager.getAddAxisCommand(domain, objectsToAdd);
		if(tmp != null) {
			cmd.append(tmp);
		}
		final AbstractAxisProvider rowsProvider = AxisUtils.getAxisProviderUsedForRows(this);
		final AbstractAxisProvider columnsProvider = AxisUtils.getAxisProviderUsedForColumns(this);
		boolean addComplementaryAxis = columnsProvider instanceof IMasterAxisProvider && rowsProvider instanceof ISlaveAxisProvider && !((IMasterAxisProvider)columnsProvider).isDisconnectSlave();
		if(addComplementaryAxis) {
			tmp = this.rowManager.getComplementaryAddAxisCommand(domain, objectsToAdd);
			if(tmp != null) {
				cmd.append(tmp);
			}
		}
		return cmd;
	}

	public Command getDestroyColumnElementCommand(Collection<Object> objectsToDestroy) {
		final EditingDomain domain = getContextEditingDomain();
		final Command cmd = this.columnManager.getDestroyAxisCommand(domain, objectsToDestroy);
		return cmd;
	}

	public Command getDestroyRowElementCommand(Collection<Object> objectsToDestroy) {
		final EditingDomain domain = getContextEditingDomain();
		final Command cmd = this.rowManager.getDestroyAxisCommand(domain, objectsToDestroy);
		return cmd;
	}


	public boolean declareEditorsOnColumns() {
		return true;
	}

	public boolean declareEditorsOnRows() {
		return false;
	}

	public ITableAxisElementProvider getTableAxisElementProvider() {// FIXME :
																	// must be
																	// renamed?
		return this;
	}




	/**
	 * When the axis manager is dynamic, we can't destroy axis
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#canCreateDestroyColumnsAxis()
	 * 
	 * @return
	 */
	@Override
	public boolean canCreateDestroyColumnsAxis() {
		return !this.columnManager.isDynamic() && this.columnManager.createPossibleAxisContentProvider(true) != null;
	}

	/**
	 * When the axis manager is dynamic, we can't destroy axis
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#canCreateDestroyRowsAxis()
	 * 
	 * @return
	 */
	@Override
	public boolean canCreateDestroyRowsAxis() {
		return !this.rowManager.isDynamic() && this.rowManager.createPossibleAxisContentProvider(true) != null;
	}

	/**
	 * 
	 * @param serv
	 *        the label provider service
	 * @param editedAxisManager
	 *        the manager used for the edited axis
	 * @param secondAxisManager
	 *        the manager used for the other axis
	 * @param isEditingColumns
	 *        boolean indicating if we are editing columns or rows
	 */
	private final void openCreateDestroyAxisManagerDialog(boolean isEditingColumns) {
		final String dialogTitle;
		final String dialogCheckBoxTootip;
		final String dialogQuestion;

		final IAxisManager editedAxisManager;
		final IAxisManager secondAxisManager;
		final String checkBoxMessage = Messages.NattableModelManager_DisconnectThisAxisManager;
		if(isEditingColumns) {
			dialogTitle = Messages.NattableModelManager_SelectColumns;
			dialogCheckBoxTootip = Messages.NattableModelManager_DisableTheAutomaticAdditionOfColumnsWhenARowIsAdded;
			dialogQuestion = String.format(Messages.NattableModelManager_TheCheckBoxHasNotBeenCheckedToAvoidAutomaticColumnAddition, checkBoxMessage);

			editedAxisManager = columnManager;
			secondAxisManager = rowManager;
		} else {
			dialogTitle = Messages.NattableModelManager_SelectRows;
			dialogCheckBoxTootip = Messages.NattableModelManager_DisableTheAutomaticAdditionOfRowsWhenAColumnIsAdded;
			dialogQuestion = String.format(Messages.NattableModelManager_TheCheckBoxHasNotBeenCheckedToAvoidAutomaticRowAddition, checkBoxMessage);

			editedAxisManager = rowManager;
			secondAxisManager = columnManager;
		}
		final LabelProviderService serv = this.natTable.getConfigRegistry().getConfigAttribute(NattableConfigAttributes.LABEL_PROVIDER_SERVICE_CONFIG_ATTRIBUTE, DisplayMode.NORMAL, NattableConfigAttributes.LABEL_PROVIDER_SERVICE_ID);
		final ILabelProvider labelProvider = serv.getLabelProvider();
		final AbstractAxisProvider editedAxisProvider = editedAxisManager.getRepresentedContentProvider();
		final AbstractAxisProvider secondAxisProvider = secondAxisManager.getRepresentedContentProvider();
		ReferenceSelector selector = new ReferenceSelector(true) {

			@Override
			public void createControls(Composite parent) {
				super.createControls(parent);
				this.treeViewer.setComparator(new ViewerComparator(new StringComparator()));//should always be string element
			}
		};
		selector.setLabelProvider(labelProvider);

		IStaticContentProvider provider = editedAxisManager.createPossibleAxisContentProvider(true);
		if(provider != null) {
			selector.setContentProvider(new FlattenableRestrictedFilteredContentProvider((IRestrictedContentProvider)provider, selector));

			final DisplayedAxisSelectorDialog dialog = new DisplayedAxisSelectorDialog(Display.getDefault().getActiveShell(), selector, dialogTitle, true, false, -1);
			boolean displayCheckBox = editedAxisProvider instanceof ISlaveAxisProvider;
			dialog.setDisplayCheckBox(displayCheckBox);
			boolean checkboxValue = secondAxisProvider instanceof IMasterAxisProvider && ((IMasterAxisProvider)secondAxisProvider).isDisconnectSlave();
			if(displayCheckBox) {
				dialog.setCheckBoxValues(checkBoxMessage, dialogCheckBoxTootip, checkboxValue);
			}

			dialog.setInformationDialogValues(Messages.NattableModelManager_DisconnectAxisManagerInformationDialogTitle, dialogQuestion);
			dialog.setLabelProvider(labelProvider);
			dialog.setInitialElementSelections(new ArrayList<Object>(editedAxisManager.getAllManagedAxis()));

			int open = dialog.open();
			if(open == Window.OK) {
				Collection<Object> existingColumns = editedAxisManager.getAllManagedAxis();
				ArrayList<Object> checkedColumns = new ArrayList<Object>();
				checkedColumns.addAll(Arrays.asList(dialog.getResult()));

				ArrayList<Object> columnsToAdd = new ArrayList<Object>(checkedColumns);
				columnsToAdd.removeAll(existingColumns);
				CompoundCommand compoundCommand = new CompoundCommand("Update Existing Axis Command"); //$NON-NLS-1$
				if(columnsToAdd.size() > 0) {
					Command addAxisElementCommand = null;
					if(isEditingColumns) {
						addAxisElementCommand = getAddColumnElementCommand(columnsToAdd);
					} else {
						addAxisElementCommand = getAddRowElementCommand(columnsToAdd);
					}
					compoundCommand.append(addAxisElementCommand);
				}

				ArrayList<Object> axisToDestroy = new ArrayList<Object>(existingColumns);
				axisToDestroy.removeAll(checkedColumns);
				if(axisToDestroy.size() > 0) {
					Command destroyAxisElementCommand = null;
					if(isEditingColumns) {
						destroyAxisElementCommand = getDestroyColumnElementCommand(axisToDestroy);
					} else {
						destroyAxisElementCommand = getDestroyRowElementCommand(axisToDestroy);
					}
					compoundCommand.append(destroyAxisElementCommand);
				}

				final boolean newState = dialog.isChecked();
				if(displayCheckBox && checkboxValue != newState) {
					final TransactionalEditingDomain domain = (TransactionalEditingDomain)getTableEditingDomain();
					final IEditCommandRequest request = new SetRequest(domain, secondAxisProvider, NattableaxisproviderPackage.eINSTANCE.getIMasterAxisProvider_DisconnectSlave(), newState);
					final IElementEditService commandProvider = ElementEditServiceUtils.getCommandProvider(secondAxisProvider);
					compoundCommand.append(new GMFtoEMFCommandWrapper(commandProvider.getEditCommand(request)));
				}

				if(!compoundCommand.isEmpty()) {
					getContextEditingDomain().getCommandStack().execute(compoundCommand);
					updateToggleActionState();
				}
			}
		} else {
			MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.NattableModelManager_CreateDestroyAxis, Messages.NattableModelManager_ActionNotYetSupported);
		}
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#openCreateDestroyRowsManagerDialog()
	 * 
	 */
	@Override
	public void openCreateDestroyRowsManagerDialog() {
		openCreateDestroyAxisManagerDialog(false);
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#openCreateDestroyColumnsManagerDialog()
	 * 
	 */
	public void openCreateDestroyColumnsManagerDialog() {
		openCreateDestroyAxisManagerDialog(true);
	}

	public void sortColumnsByName(final boolean alphabeticOrder) {
		this.columnManager.sortAxisByName(alphabeticOrder, this.natTable.getConfigRegistry());
	}


	public void sortRowsByName(final boolean alphabeticOrder) {
		this.rowManager.sortAxisByName(alphabeticOrder, this.natTable.getConfigRegistry());
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#getVerticalAxisProvider()
	 * 
	 * @return
	 */
	public AbstractAxisProvider getVerticalAxisProvider() {
		if(getTable().isInvertAxis()) {
			return getTable().getCurrentRowAxisProvider();
		} else {
			return getTable().getCurrentColumnAxisProvider();
		}
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#getHorizontalAxisProvider()
	 * 
	 * @return
	 */
	public AbstractAxisProvider getHorizontalAxisProvider() {
		if(getTable().isInvertAxis()) {
			return getTable().getCurrentColumnAxisProvider();
		} else {
			return getTable().getCurrentRowAxisProvider();
		}
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#canEditColumnHeader(int)
	 * 
	 * @param evaluationContext
	 * @return
	 */
	public boolean canEditColumnHeader(final NatEventData evaluationContext) {
		return this.columnManager.canEditAxisHeader(evaluationContext);
	}

	/***
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#canEditRowHeader(org.eclipse.nebula.widgets.nattable.ui.NatEventData)
	 * 
	 * @param eventData
	 * @return
	 */
	@Override
	public boolean canEditRowHeader(NatEventData evaluationContext) {
		return this.rowManager.canEditAxisHeader(evaluationContext);
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#openEditRowAliasDialog(org.eclipse.nebula.widgets.nattable.ui.NatEventData)
	 * 
	 * @param event
	 */
	public void openEditRowAliasDialog(NatEventData event) {
		this.rowManager.openEditAxisAliasDialog(event, event.getNatTable().getRowIndexByPosition(event.getRowPosition()));
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#openEditColumnAliasDialog(org.eclipse.nebula.widgets.nattable.ui.NatEventData)
	 * 
	 * @param event
	 */
	public void openEditColumnAliasDialog(NatEventData event) {
		this.columnManager.openEditAxisAliasDialog(event, event.getNatTable().getColumnIndexByPosition(event.getColumnPosition()));
	}

	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#getColumnAxisManager()
	 * 
	 * @return
	 */
	@Override
	public IAxisManager getColumnAxisManager() {
		return this.columnManager;
	}


	/**
	 * 
	 * @see org.eclipse.papyrus.infra.nattable.manager.table.INattableModelManager#getRowAxisManager()
	 * 
	 * @return
	 */
	@Override
	public IAxisManager getRowAxisManager() {
		return this.rowManager;
	}


	public void setTableName(String name) {
		SetRequest setNameRequest = new SetRequest(getTable(), NattableconfigurationPackage.eINSTANCE.getTableNamedElement_Name(), name);
		IElementEditService editService = ElementEditServiceUtils.getCommandProvider(getTable());
		ICommand setNameCommand = editService.getEditCommand(setNameRequest);
		getTableEditingDomain().getCommandStack().execute(new GMFtoEMFCommandWrapper(setNameCommand));
	}


	public String getTableName() {
		return getTable().getName();
	}


	@Override
	public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
		if(adapter == NatTable.class) {
			return this.natTable;
		}
		return null;
	}

}

Back to the top