Project

General

Profile

Download (30.3 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2017 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.editor.descriptiveDataSet.matrix;
10

    
11
import java.io.File;
12
import java.util.ArrayList;
13
import java.util.Collection;
14
import java.util.HashMap;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Properties;
18
import java.util.Set;
19
import java.util.UUID;
20
import java.util.stream.Collectors;
21

    
22
import javax.inject.Inject;
23

    
24
import org.apache.commons.collections4.map.LinkedMap;
25
import org.eclipse.core.runtime.ICoreRunnable;
26
import org.eclipse.core.runtime.IProgressMonitor;
27
import org.eclipse.core.runtime.SubMonitor;
28
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
29
import org.eclipse.core.runtime.jobs.Job;
30
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
31
import org.eclipse.e4.ui.di.UISynchronize;
32
import org.eclipse.e4.ui.services.EMenuService;
33
import org.eclipse.jface.layout.GridDataFactory;
34
import org.eclipse.jface.viewers.ComboViewer;
35
import org.eclipse.jface.viewers.IStructuredSelection;
36
import org.eclipse.jface.viewers.StructuredSelection;
37
import org.eclipse.nebula.widgets.nattable.NatTable;
38
import org.eclipse.nebula.widgets.nattable.config.AbstractUiBindingConfiguration;
39
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
40
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
41
import org.eclipse.nebula.widgets.nattable.coordinate.PositionCoordinate;
42
import org.eclipse.nebula.widgets.nattable.coordinate.Range;
43
import org.eclipse.nebula.widgets.nattable.copy.command.InternalCopyDataCommandHandler;
44
import org.eclipse.nebula.widgets.nattable.copy.command.InternalPasteDataCommandHandler;
45
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
46
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
47
import org.eclipse.nebula.widgets.nattable.edit.command.UpdateDataCommandHandler;
48
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommandHandler;
49
import org.eclipse.nebula.widgets.nattable.extension.e4.selection.E4SelectionListener;
50
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
51
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
52
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeData;
53
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeRowModel;
54
import org.eclipse.nebula.widgets.nattable.freeze.CompositeFreezeLayer;
55
import org.eclipse.nebula.widgets.nattable.freeze.FreezeHelper;
56
import org.eclipse.nebula.widgets.nattable.freeze.FreezeLayer;
57
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
58
import org.eclipse.nebula.widgets.nattable.grid.command.ClientAreaResizeCommand;
59
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
60
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
61
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
62
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
63
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
64
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
65
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
66
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
67
import org.eclipse.nebula.widgets.nattable.layer.AbstractLayer;
68
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
69
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
70
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
71
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
72
import org.eclipse.nebula.widgets.nattable.layer.stack.DefaultBodyLayerStack;
73
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
74
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
75
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
76
import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum;
77
import org.eclipse.nebula.widgets.nattable.style.theme.ModernNatTableThemeConfiguration;
78
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
79
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
80
import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel;
81
import org.eclipse.nebula.widgets.nattable.tree.TreeLayer;
82
import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry;
83
import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher;
84
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuAction;
85
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
86
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
87
import org.eclipse.swt.SWT;
88
import org.eclipse.swt.layout.GridData;
89
import org.eclipse.swt.layout.GridLayout;
90
import org.eclipse.swt.widgets.Button;
91
import org.eclipse.swt.widgets.Composite;
92
import org.eclipse.swt.widgets.Menu;
93

    
94
import ca.odell.glazedlists.BasicEventList;
95
import ca.odell.glazedlists.EventList;
96
import ca.odell.glazedlists.SortedList;
97
import ca.odell.glazedlists.TreeList;
98
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
99
import eu.etaxonomy.cdm.api.service.dto.RowWrapperDTO;
100
import eu.etaxonomy.cdm.api.service.dto.SpecimenRowWrapperDTO;
101
import eu.etaxonomy.cdm.common.monitor.IRemotingProgressMonitor;
102
import eu.etaxonomy.cdm.model.description.Character;
103
import eu.etaxonomy.cdm.model.description.DescriptionBase;
104
import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
105
import eu.etaxonomy.cdm.model.description.Feature;
106
import eu.etaxonomy.cdm.model.description.FeatureNode;
107
import eu.etaxonomy.cdm.model.description.FeatureTree;
108
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
109
import eu.etaxonomy.cdm.model.description.State;
110
import eu.etaxonomy.cdm.persistence.dto.SpecimenNodeWrapper;
111
import eu.etaxonomy.taxeditor.editor.internal.TaxeditorEditorPlugin;
112
import eu.etaxonomy.taxeditor.editor.l10n.Messages;
113
import eu.etaxonomy.taxeditor.model.MessagingUtils;
114
import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
115
import eu.etaxonomy.taxeditor.store.CdmStore;
116
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
117

    
118
/**
119
 * Character matrix editor for editing specimen/taxon descriptions in a table
120
 * @author pplitzner
121
 * @since Nov 26, 2017
122
 *
123
 */
124
public class CharacterMatrix extends Composite {
125

    
126
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties"; //$NON-NLS-1$
127

    
128
    static final int LEADING_COLUMN_COUNT = 4;
129
    static final String TAXON_COLUMN = "taxon_column"; //$NON-NLS-1$
130
    static final String COLLECTOR_COLUMN = "collector_column"; //$NON-NLS-1$
131
    static final String IDENTIFIER_COLUMN = "identifier_column"; //$NON-NLS-1$
132
    static final String COUNTRY_COLUMN = "country_column"; //$NON-NLS-1$
133

    
134
    static final String LABEL_TAXON_ROW = "TAXON_ROW"; //$NON-NLS-1$
135
    static final String LABEL_TAXON_AGGREGATED_DESCRIPTION = "TAXON_AGGREGATED_DESCRIPTION"; //$NON-NLS-1$
136
    static final String LABEL_TAXON_AGGREGATED_DESCRIPTION_ICON = "TAXON_AGGREGATED_DESCRIPTION_ICON"; //$NON-NLS-1$
137
    static final String LABEL_TAXON_DEFAULT_DESCRIPTION = "TAXON_DEFAULT_DESCRIPTION"; //$NON-NLS-1$
138
    static final String LABEL_TAXON_DEFAULT_DESCRIPTION_ICON = "TAXON_DEFAULT_DESCRIPTION_ICON"; //$NON-NLS-1$
139
    static final String LABEL_TAXON_LITERATURE_DESCRIPTION = "TAXON_LITERATURE_DESCRIPTION"; //$NON-NLS-1$
140
    static final String LABEL_TAXON_LITERATURE_DESCRIPTION_ICON = "TAXON_LITERATURE_DESCRIPTION_ICON"; //$NON-NLS-1$
141
    static final String LABEL_TAXON_DESCRIPTION = "LABEL_TAXON_DESCRIPTION"; //$NON-NLS-1$
142
    static final String LABEL_DESCRIPTION_HAS_SUPPLEMENTAL_DATA = "LABEL_DESCRIPTION_HAS_SUPPLEMENTAL_DATA"; //$NON-NLS-1$
143

    
144
    @Inject
145
    private UISynchronize sync;
146

    
147
    @Inject
148
    private EMenuService menuService;
149

    
150
    private DescriptiveDataSet descriptiveDataSet;
151

    
152
    private NatTable natTable;
153

    
154
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
155

    
156
    private Map<Feature, List<State>> categoricalFeatureToStateMap = new HashMap<>();
157

    
158
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
159

    
160
    private EventList<Object> descriptions;
161

    
162
    private Collection<SpecimenNodeWrapper> specimenCache = null;
163

    
164
    private Map<Feature, CategoricalDataHistogram> featureToHistogramMap = new HashMap<>();
165

    
166
    private Map<Feature, QuantitativeDataStatistics> featureToQuantDataStatisticsMap = new HashMap<>();
167

    
168
    private ListDataProvider<Object> bodyDataProvider;
169

    
170
    private FreezeLayer freezeLayer;
171

    
172
    private List<Feature> features;
173

    
174
    private CharacterMatrixPart part;
175

    
176
    private AbstractLayer topMostLayer;
177

    
178
    private FixedSummaryRowLayer summaryRowLayer;
179

    
180
    private ConfigRegistry configRegistry;
181

    
182
    private DefaultBodyLayerStack bodyLayer;
183

    
184
    private boolean isTreeView = true;
185

    
186
    private CharacterMatrixToolbar toolbar;
187

    
188
    private boolean isShowTooltips = true;
189

    
190
    private DataLayer bodyDataLayer;
191

    
192
    public CharacterMatrix(Composite parent, CharacterMatrixPart part) {
193
        super(parent, SWT.NONE);
194
        this.part = part;
195
        this.setLayout(new GridLayout());
196

    
197
        createToolBar();
198

    
199
        natTable = new NatTable(this, false);
200

    
201
        createBottomToolbar();
202

    
203
    }
204

    
205
    private void createToolBar(){
206
        toolbar = new CharacterMatrixToolbar(this, SWT.NONE);
207
    }
208

    
209
    @SuppressWarnings("unused")
210
    private void createBottomToolbar() {
211
        new CharacterMatrixBottomToolbar(this, SWT.NONE);
212
    }
213

    
214

    
215
    private void applyStyles(){
216
        ModernNatTableThemeConfiguration configuration = new ModernNatTableThemeConfiguration();
217
        configuration.summaryRowHAlign = HorizontalAlignmentEnum.CENTER;
218
        // NOTE: Getting the colors and fonts from the GUIHelper ensures that
219
        // they are disposed properly (required by SWT)
220
        configuration.cHeaderBgColor = GUIHelper.getColor(211, 211, 211);
221
        configuration.rHeaderBgColor = GUIHelper.getColor(211, 211, 211);
222
        natTable.addConfiguration(configuration);
223

    
224
    }
225

    
226
    void toggleTreeFlat(boolean isTree, Button btnToggleFlat, Button btnToggleTree, Button btnCollapseAll, Button btnExpandAll, Button btnFreezeSuppInfo) {
227
        isTreeView = isTree;
228
        createTable(isTree, freezeLayer.isFrozen());
229
        btnToggleFlat.setEnabled(isTree);
230
        btnToggleTree.setEnabled(!isTree);
231
        btnCollapseAll.setEnabled(isTree);
232
        btnExpandAll.setEnabled(isTree);
233
    }
234

    
235
    public boolean isTreeView() {
236
        return isTreeView;
237
    }
238

    
239
    public void createTable(boolean treeView, boolean freezeSupplementalColumns){
240
        /**
241
         * layers
242
         */
243
        createLayers(treeView);
244

    
245
        /**
246
         * configuration
247
         */
248
        configureNatTable(treeView, configRegistry, topMostLayer, summaryRowLayer);
249

    
250
        /**
251
         * handlers and listeners
252
         */
253
        registerHandlersAndListeners(topMostLayer);
254

    
255
        //grab all space
256
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
257

    
258
        //update label to current data set
259
        toolbar.getWsLabel().setText(descriptiveDataSet.getLabel());
260
        toolbar.getWsLabel().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
261
        toolbar.getWsLabel().getParent().layout();
262

    
263
        //initial freeze of supplemental columns
264
        freezeSupplementalColumns(freezeSupplementalColumns);
265

    
266

    
267
        //add tooltip to table
268
        new CategoricalChartTooltip(this);
269
        new QuantitativeChartTooltip(this);
270

    
271
        this.layout();
272
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
273
    }
274

    
275
    private List<Feature> initFeatureList(FeatureNode node){
276
        List<Feature> features = new ArrayList<>();
277
        node.getChildNodes().forEach(childNode->
278
                {
279
                    Feature feature = childNode.getFeature();
280
                    if(feature.isInstanceOf(Character.class)){
281
                        features.add(childNode.getFeature());
282
                    }
283
                    features.addAll(initFeatureList(childNode));
284
                });
285
        return features;
286
    }
287

    
288
    public void initDescriptiveDataSet(DescriptiveDataSet descriptiveDataSet){
289
        this.descriptiveDataSet = descriptiveDataSet;
290
        //get features/columns stored in descriptive data set
291
        FeatureTree tree = descriptiveDataSet.getDescriptiveSystem();
292
        features = initFeatureList(tree.getRoot());
293

    
294
        //init state data for categorical features
295
        features.forEach(feature->
296
        {
297
            if(feature.isSupportsCategoricalData()){
298
                List<State> supportedStates = new ArrayList<>();
299
                feature.getSupportedCategoricalEnumerations().forEach(voc->supportedStates.addAll(voc.getTerms()));
300
                categoricalFeatureToStateMap.put(feature, supportedStates);
301
            }
302
        });
303
        descriptions = new BasicEventList<>();
304

    
305
    }
306

    
307
    private void createLayers(boolean treeView) {
308
        SortedList<Object> sortedList = new SortedList<>(descriptions, new MatrixRowComparator());
309
        // wrap the SortedList with the TreeList
310
        TreeList<Object> treeList = new TreeList(sortedList, new DescriptionTreeFormat(descriptiveDataSet), TreeList.NODES_START_EXPANDED);
311
        /**
312
         * data provider
313
         */
314
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
315
        bodyDataProvider = treeView?new ListDataProvider<>(treeList, columnPropertyAccessor):new ListDataProvider<>(sortedList, columnPropertyAccessor);
316

    
317
        configRegistry = new ConfigRegistry();
318

    
319

    
320
        /**
321
         * BODY layer
322
         *
323
         *
324

    
325
        CompositeLayer
326
         - (top) SummaryRowLayer
327
         - (bottom) ViewportLayer
328

    
329
             ^
330
        ViewportLayer
331

    
332
             ^
333
        TreeLayer (default visible)
334

    
335
             ^
336
        CompositeFreezeLayer
337
         - viewportLayer
338
         - selectionLayer
339
         - freezeLayer
340

    
341
             ^
342
        FreezeLayer
343

    
344
             ^
345
        SelectionLayer
346

    
347
             ^
348
        ColumnHideShowLayer
349

    
350
             ^
351
        ColumnReorderLayer
352

    
353
             ^
354
        DataLayer
355

    
356
         *
357

    
358
         */
359
        bodyDataLayer = new DataLayer(bodyDataProvider);
360

    
361
        //register labels
362
        CharacterMatrixConfigLabelAccumulator labelAccumulator = new CharacterMatrixConfigLabelAccumulator(this);
363
        bodyDataLayer.setConfigLabelAccumulator(labelAccumulator);
364

    
365

    
366
        propertyToLabelMap.put(TAXON_COLUMN, Messages.CharacterMatrix_TAXON);
367
        propertyToLabelMap.put(COLLECTOR_COLUMN, Messages.CharacterMatrix_COLLECTOR_NO);
368
        propertyToLabelMap.put(IDENTIFIER_COLUMN, Messages.CharacterMatrix_IDENTIFIER);
369
        propertyToLabelMap.put(COUNTRY_COLUMN, Messages.CharacterMatrix_COUNTRY);
370
        for(int i=0;i<features.size();i++){
371
            Feature feature = features.get(i);
372
            initLabels(i, feature);
373
        }
374

    
375
        // layer for event handling of GlazedLists and PropertyChanges
376
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList);
377
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
378
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
379

    
380
        bodyLayer = new DefaultBodyLayerStack(eventLayer);
381
        final SelectionLayer selectionLayer = bodyLayer.getSelectionLayer();
382
        freezeLayer = new FreezeLayer(selectionLayer);
383
        final CompositeFreezeLayer compositeFreezeLayer = new CompositeFreezeLayer(
384
                freezeLayer, bodyLayer.getViewportLayer(), selectionLayer);
385
        TreeLayer treeLayer = new TreeLayer(compositeFreezeLayer, treeRowModel);
386

    
387
        topMostLayer = treeView?treeLayer:compositeFreezeLayer;
388

    
389
        summaryRowLayer = new FixedSummaryRowLayer(bodyDataLayer, topMostLayer, configRegistry, false);
390
        //regoster labels with summary prefix for summary layer
391
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
392
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
393
        for(int i=0;i<features.size();i++){
394
            Feature feature = features.get(i);
395
            summaryColumnLabelAccumulator.registerColumnOverrides(
396
                    i+LEADING_COLUMN_COUNT,
397
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
398
        }
399
        // because the horizontal dependency is the ViewportLayer
400
        // we need to set the composite dependency to false
401
        summaryRowLayer.setHorizontalCompositeDependency(false);
402

    
403
        CompositeLayer composite = new CompositeLayer(1, 2);
404
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0); //$NON-NLS-1$
405
        composite.setChildLayer(GridRegion.BODY, topMostLayer, 0, 1);
406

    
407

    
408
        /**
409
         * column header layer
410
         */
411
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
412
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
413
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
414
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, topMostLayer, selectionLayer);
415

    
416
        // add the SortHeaderLayer to the column header layer stack
417
        // as we use GlazedLists, we use the GlazedListsSortModel which
418
        // delegates the sorting to the SortedList
419
        final SortHeaderLayer<DescriptionBase> sortHeaderLayer = new SortHeaderLayer<>(
420
                columnHeaderLayer,
421
                new GlazedListsSortModel<>(
422
                        sortedList,
423
                        columnPropertyAccessor,
424
                        configRegistry,
425
                        columnHeaderDataLayer));
426

    
427

    
428
        /**
429
         * row header layer
430
         */
431
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
432
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
433
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
434
                composite, selectionLayer);
435
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211"); //$NON-NLS-1$
436

    
437

    
438
        /**
439
         * corner layer
440
         */
441
        ILayer cornerLayer = new CornerLayer(
442
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
443
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
444

    
445

    
446
        /**
447
         * GRID layer (composition of all other layers)
448
         */
449
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
450

    
451
        natTable.setLayer(gridLayer);
452

    
453
    }
454

    
455
    private void registerHandlersAndListeners(AbstractLayer topMostLayer) {
456
        // add the ExportCommandHandler to the ViewportLayer in order to make
457
        // exporting work
458
        topMostLayer.registerCommandHandler(new ExportCommandHandler(topMostLayer));
459

    
460
        //selection listener
461
        E4SelectionListener selectionListener = new CellSelectionListener(part.getSelectionService(),
462
                bodyLayer.getSelectionLayer(), bodyDataProvider, part);
463
        bodyLayer.getSelectionLayer().addLayerListener(selectionListener);
464
        selectionListener.setFullySelectedRowsOnly(false);
465

    
466
        //register handler for view configuration menu
467
        natTable.registerCommandHandler(toolbar.getDisplayPersistenceDialogCommandHandler());
468

    
469
        //register handlers for copy&paste
470
        natTable.registerCommandHandler(
471
                new InternalPasteDataCommandHandler(bodyLayer.getSelectionLayer(), natTable.getInternalCellClipboard()));
472
        natTable.registerCommandHandler(
473
                new InternalCopyDataCommandHandler(bodyLayer.getSelectionLayer(), natTable.getInternalCellClipboard()));
474
        natTable.registerCommandHandler(new UpdateDataCommandHandler(bodyDataLayer));
475
    }
476

    
477
    private void configureNatTable(boolean treeView,
478
            ConfigRegistry configRegistry,
479
            AbstractLayer topMostLayer,
480
            FixedSummaryRowLayer summaryRowLayer) {
481
        /**
482
         * CONFIGURATION
483
         */
484
        natTable.setConfigRegistry(configRegistry);
485

    
486
        applyStyles();
487

    
488
        //add default configuration because autoconfigure is set to false in constructor
489
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
490

    
491
        // this is for DEBUG ONLY
492
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
493

    
494
        // override the default sort configuration and change the mouse bindings
495
        // to sort on a single click
496
        if(!treeView){
497
            natTable.addConfiguration(new SingleClickSortConfiguration());
498
        }
499

    
500
        natTable.addConfiguration(new CharacterMatrixLabelStyleConfiguration());
501

    
502
        // add the header menu configuration for adding the column header menu
503
        // with hide/show actions
504
        natTable.addConfiguration(new CharacterMatrixHeaderMenuConfiguration(natTable));
505

    
506
        // add custom configuration for data conversion and add column labels to viewport layer
507
        topMostLayer.addConfiguration(new CellEditorDataConversionConfiguration(this));
508

    
509
        //register aggregation configuration
510
        summaryRowLayer.addConfiguration(new AggregationConfiguration(this));
511

    
512
        //copy&paste configuration
513
        natTable.addConfiguration(new CopyPasteEditBindings(bodyLayer.getSelectionLayer(), natTable.getInternalCellClipboard()));
514

    
515
      //+++CONTEXT MENU+++
516
        menuService.registerContextMenu(natTable, "eu.etaxonomy.taxeditor.editor.popupmenu.charactermatrix"); //$NON-NLS-1$
517
        // get the menu registered by EMenuService
518
        final Menu e4Menu = natTable.getMenu();
519
        // remove the menu reference from NatTable instance
520
        natTable.setMenu(null);
521
        natTable.addConfiguration(
522
                new AbstractUiBindingConfiguration() {
523
            @Override
524
            public void configureUiBindings(
525
                    UiBindingRegistry uiBindingRegistry) {
526
                // add e4 menu to NatTable
527
                new PopupMenuBuilder(natTable, e4Menu)
528
                    .build();
529

    
530
                // register the UI binding for header, corner and body region
531
                uiBindingRegistry.registerMouseDownBinding(
532
                        new MouseEventMatcher(
533
                                SWT.NONE,
534
                                null,
535
                                MouseEventMatcher.RIGHT_BUTTON),
536
                        new PopupMenuAction(e4Menu));
537
            }
538
        });
539

    
540
        natTable.configure();
541
    }
542

    
543
    void freezeSupplementalColumns(boolean freeze){
544
        if(freeze){
545
            FreezeHelper.freeze(freezeLayer, bodyLayer.getViewportLayer(),
546
                    new PositionCoordinate(bodyLayer.getViewportLayer(), 0, 0),
547
                    new PositionCoordinate(bodyLayer.getViewportLayer(), LEADING_COLUMN_COUNT-1, -1));
548
        }
549
        else{
550
            FreezeHelper.unfreeze(freezeLayer, bodyLayer.getViewportLayer());
551
        }
552
    }
553

    
554
    void selectStateItem(ComboViewer comboStates, String stateName){
555
        String[] items = comboStates.getCombo().getItems();
556
        for(int i=0;i<items.length;i++){
557
            if(items[i].equals(stateName)){
558
                comboStates.getCombo().select(i);
559
                break;
560
            }
561
        }
562
    }
563

    
564
    private void initLabels(int index, Feature feature) {
565
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
566

    
567
        String featureLabel = feature.getLabel();
568
        String property = featureLabel;
569
        //show unit for quantitative data
570
        if(feature.isSupportsQuantitativeData()){
571
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
572
            if(recommendedMeasurementUnits.size()>1){
573
                MessagingUtils.warningDialog(Messages.CharacterMatrix_INIT_PROBLEM, CharacterMatrix.class,
574
                        String.format(Messages.CharacterMatrix_INIT_PROBLEM_MESSAGE, feature.getLabel()));
575
            }
576
            if(recommendedMeasurementUnits.size()==1){
577
                MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
578
                featureLabel += " ["+unit.getIdInVocabulary()+"]"; //$NON-NLS-1$ //$NON-NLS-2$
579
            }
580
        }
581
        propertyToLabelMap.put(property, featureLabel);
582
    }
583

    
584
    public void loadDescriptions(DescriptiveDataSet descriptiveDataSet) {
585
        UUID monitorUuid =  CdmApplicationState.getLongRunningTasksService().monitGetRowWrapper(descriptiveDataSet);
586

    
587
        final Collection<RowWrapperDTO> wrappers = new ArrayList<>();
588
        String jobLabel = Messages.CharacterMatrix_LOAD_CHARACTER_DATA;
589
        Job job = Job.create(jobLabel, (ICoreRunnable) monitor -> {
590
            SubMonitor subMonitor = SubMonitor.convert(monitor);
591
            subMonitor.beginTask(jobLabel, IProgressMonitor.UNKNOWN);
592
            IRemotingProgressMonitor remotingMonitor;
593
            try {
594
                 remotingMonitor = CdmStore.getProgressMonitorClientManager()
595
                .pollMonitor(jobLabel,
596
                        monitorUuid,
597
                        50,
598
                        null,
599
                        (List)null,
600
                        subMonitor);
601
            } catch (InterruptedException e) {
602
                MessagingUtils.informationDialog(Messages.CharacterMatrix_LOADING_FAILED_TITLE,
603
                        Messages.CharacterMatrix_LOADING_FAILED_MESSAGE);
604
                return;
605
            }
606
            Object result = remotingMonitor.getResult();
607
            if(result instanceof Collection){
608
                wrappers.addAll((Collection<RowWrapperDTO>) result);
609
            }
610
            if(result instanceof Exception){
611
                MessagingUtils.errorDialog("Exception during description loading", this.getClass(), "An exception occured during loading", TaxeditorEditorPlugin.PLUGIN_ID, (Throwable) result, true);
612
            }
613
            else if(wrappers.isEmpty()){
614
                MessagingUtils.informationDialog(Messages.CharacterMatrix_NO_DESCRIPTION_TITLE,
615
                        Messages.CharacterMatrix_NO_DESCRIPTION_MESSAGE);
616
            }
617
            monitor.done();
618
        });
619
        job.addJobChangeListener(new JobChangeAdapter(){
620
            @Override
621
            public void done(IJobChangeEvent event) {
622
                sync.syncExec(()->{
623
                    List<RowWrapperDTO> rowsWithoutTaxonNode = wrappers.stream().filter(row->row.getTaxonNode()==null).collect(Collectors.toList());
624
                    if(!rowsWithoutTaxonNode.isEmpty()){
625
                        String collect = rowsWithoutTaxonNode.stream().
626
                        map(row->row.getDescription().toString())
627
                        .collect(Collectors.joining("\n\n - ")); //$NON-NLS-1$
628
                        MessagingUtils.warningDialog(
629
                                Messages.CharacterMatrix_NO_NODE_FOUND_TITLE,
630
                                this.getClass(),
631
                                String.format(Messages.CharacterMatrix_NO_NODE_FOUND_MESSAGE, collect)
632
                                );
633
                    }
634
                    wrappers.stream().filter(row->row.getTaxonNode()!=null).forEach(wrapper->CharacterMatrix.this.descriptions.add(wrapper));
635
                    loadingDone();
636
                });
637
            }
638
        });
639
        job.schedule();
640
    }
641

    
642
    public IStructuredSelection getSelection(){
643
        Set<Range> selectedRowPositions = bodyLayer.getSelectionLayer().getSelectedRowPositions();
644
        List<Object> selectedObjects = new ArrayList<>();
645
        for (Range range : selectedRowPositions) {
646
            for(int i=range.start;i<range.end;i++){
647
                selectedObjects.add(bodyDataProvider.getRowObject(i));
648
            }
649
        }
650
        return new StructuredSelection(selectedObjects);
651
    }
652

    
653
    private void loadingDone() {
654
        this.part.loadingDone();
655
        createTable(isTreeView, freezeLayer.isFrozen());
656
    }
657

    
658
    public List<State> getSupportedStatesForCategoricalFeature(Feature feature){
659
        return categoricalFeatureToStateMap.get(feature);
660
    }
661

    
662
    public Map<Integer, Feature> getIndexToFeatureMap() {
663
        return indexToFeatureMap;
664
    }
665

    
666
    public LinkedMap<String, String> getPropertyToLabelMap() {
667
        return propertyToLabelMap;
668
    }
669

    
670
    public void setDirty() {
671
        part.setDirty();
672
    }
673

    
674
    public CharacterMatrixPart getPart() {
675
        return part;
676
    }
677

    
678
    public NatTable getNatTable() {
679
        return natTable;
680
    }
681

    
682
    public EventList<Object> getDescriptions() {
683
        return descriptions;
684
    }
685

    
686
    public DescriptiveDataSet getDescriptiveDataSet() {
687
        return descriptiveDataSet;
688
    }
689

    
690
    public Collection<SpecimenNodeWrapper> getSpecimenCache() {
691
        return specimenCache;
692
    }
693

    
694
    public void setSpecimenCache(Collection<SpecimenNodeWrapper> specimenCache) {
695
        this.specimenCache = specimenCache.stream()
696
                .filter(wrapper ->
697
        //map descriptions on a list of uuids of the described specimen
698
        !this.descriptions.stream()
699
        .filter(rowWrapper->rowWrapper instanceof SpecimenRowWrapperDTO)
700
        .map(specimenRowWrapper->((SpecimenRowWrapperDTO) specimenRowWrapper).getSpecimen().getUuid())
701
        .collect(Collectors.toList())
702
        //an check if the specimen to add is already contained
703
        .contains(wrapper.getUuidAndTitleCache().getUuid())
704
        )
705
        .collect(Collectors.toList());
706
    }
707

    
708
    public Properties getNatTableState() {
709
        return toolbar.getNatTableState();
710
    }
711

    
712
    public ListDataProvider<Object> getBodyDataProvider() {
713
        return bodyDataProvider;
714
    }
715

    
716
    DefaultBodyLayerStack getBodyLayer() {
717
        return bodyLayer;
718
    }
719

    
720
    File getStatePropertiesFile() {
721
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
722
    }
723

    
724
    public List<Feature> getFeatures() {
725
        return features;
726
    }
727

    
728
    public Map<Feature, CategoricalDataHistogram> getFeatureToHistogramMap() {
729
        return featureToHistogramMap;
730
    }
731

    
732
    public Map<Feature, QuantitativeDataStatistics> getFeatureToQuantDataStatisticsMap() {
733
        return featureToQuantDataStatisticsMap;
734
    }
735

    
736
    public void toogleIsShowTooltips() {
737
        this.isShowTooltips = !this.isShowTooltips;
738
    }
739

    
740
    public boolean isShowTooltips() {
741
        return isShowTooltips;
742
    }
743

    
744
    public ICdmEntitySession getCdmEntitiySession(){
745
        return part.getCdmEntitySession();
746
    }
747

    
748
}
(6-6/20)