Project

General

Profile

Download (30.6 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.export.command.ExportCommandHandler;
48
import org.eclipse.nebula.widgets.nattable.extension.e4.selection.E4SelectionListener;
49
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
50
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
51
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeData;
52
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeRowModel;
53
import org.eclipse.nebula.widgets.nattable.freeze.CompositeFreezeLayer;
54
import org.eclipse.nebula.widgets.nattable.freeze.FreezeHelper;
55
import org.eclipse.nebula.widgets.nattable.freeze.FreezeLayer;
56
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
57
import org.eclipse.nebula.widgets.nattable.grid.command.ClientAreaResizeCommand;
58
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
59
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
60
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
61
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
62
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
63
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
64
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
65
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
66
import org.eclipse.nebula.widgets.nattable.layer.AbstractLayer;
67
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
68
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
69
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
70
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
71
import org.eclipse.nebula.widgets.nattable.layer.stack.DefaultBodyLayerStack;
72
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
73
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
74
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
75
import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum;
76
import org.eclipse.nebula.widgets.nattable.style.theme.ModernNatTableThemeConfiguration;
77
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
78
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
79
import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel;
80
import org.eclipse.nebula.widgets.nattable.tree.TreeLayer;
81
import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry;
82
import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher;
83
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuAction;
84
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
85
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
86
import org.eclipse.swt.SWT;
87
import org.eclipse.swt.layout.GridData;
88
import org.eclipse.swt.layout.GridLayout;
89
import org.eclipse.swt.widgets.Button;
90
import org.eclipse.swt.widgets.Composite;
91
import org.eclipse.swt.widgets.Menu;
92

    
93
import ca.odell.glazedlists.BasicEventList;
94
import ca.odell.glazedlists.EventList;
95
import ca.odell.glazedlists.SortedList;
96
import ca.odell.glazedlists.TreeList;
97
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
98
import eu.etaxonomy.cdm.api.service.dto.RowWrapperDTO;
99
import eu.etaxonomy.cdm.api.service.dto.SpecimenRowWrapperDTO;
100
import eu.etaxonomy.cdm.common.monitor.IRemotingProgressMonitor;
101
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
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<Character> 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
    public CharacterMatrix(Composite parent, CharacterMatrixPart part) {
191
        super(parent, SWT.NONE);
192
        this.part = part;
193
        this.setLayout(new GridLayout());
194

    
195
        createToolBar();
196

    
197
        natTable = new NatTable(this, false);
198

    
199
        createBottomToolbar();
200

    
201
    }
202

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

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

    
212

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

    
222
    }
223

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

    
233
    public boolean isTreeView() {
234
        return isTreeView;
235
    }
236

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

    
243
        /**
244
         * configuration
245
         */
246
        configureNatTable(treeView, configRegistry, topMostLayer, summaryRowLayer);
247

    
248
        /**
249
         * handlers and listeners
250
         */
251
        registerHandlersAndListeners(topMostLayer);
252

    
253
        //grab all space
254
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
255

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

    
261
        //initial freeze of supplemental columns
262
        freezeSupplementalColumns(freezeSupplementalColumns);
263

    
264

    
265
        //add tooltip to table
266
        new CategoricalChartTooltip(this);
267
        new QuantitativeChartTooltip(this);
268

    
269
        this.layout();
270
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
271
    }
272

    
273
    private List<Character> initFeatureList(FeatureNode node){
274
        List<Character> features = new ArrayList<>();
275
        node.getChildNodes().forEach(childNode->
276
                {
277
                    DefinedTermBase feature = childNode.getTerm();
278
                    // FIXME #8146 this is currently checked via the termType of the tree
279
                    // in the init() method. This may be solved by adding generics to FeatureNode
280
                    // so that getTerm is typified. This would make this check obsolete
281
                    if(feature.isInstanceOf(Character.class)){
282
                        features.add((Character) feature);
283
                    }
284
                    features.addAll(initFeatureList(childNode));
285
                });
286
        return features;
287
    }
288

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

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

    
306
    }
307

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

    
318
        configRegistry = new ConfigRegistry();
319

    
320

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

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

    
330
             ^
331
        ViewportLayer
332

    
333
             ^
334
        TreeLayer (default visible)
335

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

    
342
             ^
343
        FreezeLayer
344

    
345
             ^
346
        SelectionLayer
347

    
348
             ^
349
        ColumnHideShowLayer
350

    
351
             ^
352
        ColumnReorderLayer
353

    
354
             ^
355
        DataLayer
356

    
357
         *
358

    
359
         */
360
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
361
        bodyDataLayer.registerCommandHandler(new CopyPasteUpdateDataCommandHandler(bodyDataLayer));
362

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

    
367

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

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

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

    
389
        topMostLayer = treeView?treeLayer:compositeFreezeLayer;
390

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

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

    
409

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

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

    
429

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

    
439

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

    
447

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

    
453
        natTable.setLayer(gridLayer);
454

    
455
    }
456

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

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

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

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

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

    
487
        applyStyles();
488

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

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

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

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

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

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

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

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

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

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

    
541
        natTable.configure();
542
    }
543

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
725
    public List<Character> getFeatures() {
726
        return features;
727
    }
728

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

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

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

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

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

    
749
}
(6-6/21)