Project

General

Profile

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

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

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

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

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

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

    
141
    @Inject
142
    private UISynchronize sync;
143

    
144
    @Inject
145
    private EMenuService menuService;
146

    
147
    private DescriptiveDataSet descriptiveDataSet;
148

    
149
    private NatTable natTable;
150

    
151
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
152

    
153
    private Map<Feature, List<State>> categoricalFeatureToStateMap = new HashMap<>();
154

    
155
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
156

    
157
    private EventList<Object> descriptions;
158

    
159
    private Collection<SpecimenNodeWrapper> specimenCache = null;
160

    
161
    private Map<Feature, CategoricalDataHistogram> featureToHistogramMap = new HashMap<>();
162

    
163
    private Map<Feature, QuantitativeDataStatistics> featureToQuantDataStatisticsMap = new HashMap<>();
164

    
165
    private ListDataProvider<Object> bodyDataProvider;
166

    
167
    private FreezeLayer freezeLayer;
168

    
169
    private List<Feature> features;
170

    
171
    private CharacterMatrixPart part;
172

    
173
    private AbstractLayer topMostLayer;
174

    
175
    private FixedSummaryRowLayer summaryRowLayer;
176

    
177
    private ConfigRegistry configRegistry;
178

    
179
    private DefaultBodyLayerStack bodyLayer;
180

    
181
    private boolean isTreeView = true;
182

    
183
    private CharacterMatrixToolbar toolbar;
184

    
185
    private boolean isShowTooltips = true;
186

    
187
    public CharacterMatrix(Composite parent, CharacterMatrixPart part) {
188
        super(parent, SWT.NONE);
189
        this.part = part;
190
        this.setLayout(new GridLayout());
191

    
192
        createToolBar();
193

    
194
        natTable = new NatTable(this, false);
195

    
196
        createBottomToolbar();
197

    
198
    }
199

    
200
    private void createToolBar(){
201
        toolbar = new CharacterMatrixToolbar(this, SWT.NONE);
202
    }
203

    
204
    @SuppressWarnings("unused")
205
    private void createBottomToolbar() {
206
        new CharacterMatrixBottomToolbar(this, SWT.NONE);
207
    }
208

    
209

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

    
219
    }
220

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

    
230
    public boolean isTreeView() {
231
        return isTreeView;
232
    }
233

    
234
    public void createTable(boolean treeView, boolean freezeSupplementalColumns){
235
        /**
236
         * layers
237
         */
238
        createLayers(treeView);
239

    
240
        /**
241
         * configuration
242
         */
243
        configureNatTable(treeView, configRegistry, topMostLayer, summaryRowLayer);
244

    
245
        /**
246
         * handlers and listeners
247
         */
248
        registerHandlersAndListeners(topMostLayer);
249

    
250
        //grab all space
251
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
252

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

    
258
        //initial freeze of supplemental columns
259
        freezeSupplementalColumns(freezeSupplementalColumns);
260

    
261

    
262
        //add tooltip to table
263
        new CategoricalChartTooltip(this);
264
        new QuantitativeChartTooltip(this);
265

    
266
        this.layout();
267
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
268
    }
269

    
270
    private List<Feature> initFeatureList(FeatureNode node){
271
        List<Feature> features = new ArrayList<>();
272
        node.getChildNodes().forEach(childNode->
273
                {
274
                    features.add(childNode.getFeature());
275
                    features.addAll(initFeatureList(childNode));
276
                });
277
        return features;
278
    }
279

    
280
    public void initDescriptiveDataSet(DescriptiveDataSet descriptiveDataSet){
281
        this.descriptiveDataSet = descriptiveDataSet;
282
        //get features/columns stored in descriptive data set
283
        FeatureTree tree = descriptiveDataSet.getDescriptiveSystem();
284
        features = initFeatureList(tree.getRoot());
285

    
286
        //init state data for categorical features
287
        features.forEach(feature->
288
        {
289
            if(feature.isSupportsCategoricalData()){
290
                List<State> supportedStates = new ArrayList<>();
291
                feature.getSupportedCategoricalEnumerations().forEach(voc->supportedStates.addAll(voc.getTerms()));
292
                categoricalFeatureToStateMap.put(feature, supportedStates);
293
            }
294
        });
295
        descriptions = new BasicEventList<>();
296

    
297
    }
298

    
299
    private void createLayers(boolean treeView) {
300
        // use the SortedList constructor with 'null' for the Comparator
301
        // because the Comparator will be set by configuration
302
        SortedList<Object> sortedList = new SortedList<>(descriptions, new MatrixRowComparator());
303
        // wrap the SortedList with the TreeList
304
        TreeList<Object> treeList = new TreeList(sortedList, new DescriptionTreeFormat(descriptiveDataSet), TreeList.NODES_START_EXPANDED);
305
        /**
306
         * data provider
307
         */
308
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
309
        bodyDataProvider = treeView?new ListDataProvider<>(treeList, columnPropertyAccessor):new ListDataProvider<>(sortedList, columnPropertyAccessor);
310

    
311
        configRegistry = new ConfigRegistry();
312

    
313

    
314
        /**
315
         * BODY layer
316
         *
317
         *
318

    
319
        CompositeLayer
320
         - (top) SummaryRowLayer
321
         - (bottom) ViewportLayer
322

    
323
             ^
324
        ViewportLayer
325

    
326
             ^
327
        TreeLayer (default visible)
328

    
329
             ^
330
        CompositeFreezeLayer
331
         - viewportLayer
332
         - selectionLayer
333
         - freezeLayer
334

    
335
             ^
336
        FreezeLayer
337

    
338
             ^
339
        SelectionLayer
340

    
341
             ^
342
        ColumnHideShowLayer
343

    
344
             ^
345
        ColumnReorderLayer
346

    
347
             ^
348
        DataLayer
349

    
350
         *
351

    
352
         */
353
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
354

    
355
        //register labels
356
        CharacterMatrixConfigLabelAccumulator labelAccumulator = new CharacterMatrixConfigLabelAccumulator(this);
357
        bodyDataLayer.setConfigLabelAccumulator(labelAccumulator);
358

    
359

    
360
        propertyToLabelMap.put(TAXON_COLUMN, Messages.CharacterMatrix_TAXON);
361
        propertyToLabelMap.put(COLLECTOR_COLUMN, Messages.CharacterMatrix_COLLECTOR_NO);
362
        propertyToLabelMap.put(IDENTIFIER_COLUMN, Messages.CharacterMatrix_IDENTIFIER);
363
        propertyToLabelMap.put(COUNTRY_COLUMN, Messages.CharacterMatrix_COUNTRY);
364
        for(int i=0;i<features.size();i++){
365
            Feature feature = features.get(i);
366
            initLabels(i, feature);
367
        }
368

    
369
        // layer for event handling of GlazedLists and PropertyChanges
370
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList);
371
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
372
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
373

    
374
        bodyLayer = new DefaultBodyLayerStack(eventLayer);
375
        final SelectionLayer selectionLayer = bodyLayer.getSelectionLayer();
376
        freezeLayer = new FreezeLayer(selectionLayer);
377
        final CompositeFreezeLayer compositeFreezeLayer = new CompositeFreezeLayer(
378
                freezeLayer, bodyLayer.getViewportLayer(), selectionLayer);
379
        TreeLayer treeLayer = new TreeLayer(compositeFreezeLayer, treeRowModel);
380

    
381
        topMostLayer = treeView?treeLayer:compositeFreezeLayer;
382

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

    
397
        CompositeLayer composite = new CompositeLayer(1, 2);
398
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0); //$NON-NLS-1$
399
        composite.setChildLayer(GridRegion.BODY, topMostLayer, 0, 1);
400

    
401

    
402
        /**
403
         * column header layer
404
         */
405
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
406
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
407
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
408
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, topMostLayer, selectionLayer);
409

    
410
        // add the SortHeaderLayer to the column header layer stack
411
        // as we use GlazedLists, we use the GlazedListsSortModel which
412
        // delegates the sorting to the SortedList
413
        final SortHeaderLayer<DescriptionBase> sortHeaderLayer = new SortHeaderLayer<>(
414
                columnHeaderLayer,
415
                new GlazedListsSortModel<>(
416
                        sortedList,
417
                        columnPropertyAccessor,
418
                        configRegistry,
419
                        columnHeaderDataLayer));
420

    
421

    
422
        /**
423
         * row header layer
424
         */
425
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
426
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
427
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
428
                composite, selectionLayer);
429
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211"); //$NON-NLS-1$
430

    
431

    
432
        /**
433
         * corner layer
434
         */
435
        ILayer cornerLayer = new CornerLayer(
436
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
437
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
438

    
439

    
440
        /**
441
         * GRID layer (composition of all other layers)
442
         */
443
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
444

    
445
        natTable.setLayer(gridLayer);
446

    
447
    }
448

    
449
    private void registerHandlersAndListeners(AbstractLayer topMostLayer) {
450
        // add the ExportCommandHandler to the ViewportLayer in order to make
451
        // exporting work
452
        topMostLayer.registerCommandHandler(new ExportCommandHandler(topMostLayer));
453

    
454
        //selection listener
455
        E4SelectionListener selectionListener = new CellSelectionListener(part.getSelectionService(),
456
                bodyLayer.getSelectionLayer(), bodyDataProvider, part);
457
        bodyLayer.getSelectionLayer().addLayerListener(selectionListener);
458
        selectionListener.setFullySelectedRowsOnly(false);
459

    
460
        //register handler for view configuration menu
461
        natTable.registerCommandHandler(toolbar.getDisplayPersistenceDialogCommandHandler());
462
    }
463

    
464
    private void configureNatTable(boolean treeView,
465
            ConfigRegistry configRegistry,
466
            AbstractLayer topMostLayer,
467
            FixedSummaryRowLayer summaryRowLayer) {
468
        /**
469
         * CONFIGURATION
470
         */
471
        natTable.setConfigRegistry(configRegistry);
472

    
473
        applyStyles();
474

    
475
        //add default configuration because autoconfigure is set to false in constructor
476
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
477

    
478
        //FIXME: this is for DEBUG ONLY
479
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
480

    
481
        // override the default sort configuration and change the mouse bindings
482
        // to sort on a single click
483
        if(!treeView){
484
            natTable.addConfiguration(new SingleClickSortConfiguration());
485
        }
486

    
487
        natTable.addConfiguration(new CharacterMatrixLabelStyleConfiguration());
488

    
489
        // add the header menu configuration for adding the column header menu
490
        // with hide/show actions
491
        natTable.addConfiguration(new CharacterMatrixHeaderMenuConfiguration(natTable));
492

    
493
        // add custom configuration for data conversion and add column labels to viewport layer
494
        topMostLayer.addConfiguration(new CellEditorDataConversionConfiguration(this));
495

    
496
        //register aggregation configuration
497
        summaryRowLayer.addConfiguration(new AggregationConfiguration(this));
498

    
499
      //+++CONTEXT MENU+++
500
        menuService.registerContextMenu(natTable, "eu.etaxonomy.taxeditor.editor.popupmenu.charactermatrix"); //$NON-NLS-1$
501
        // get the menu registered by EMenuService
502
        final Menu e4Menu = natTable.getMenu();
503
        // remove the menu reference from NatTable instance
504
        natTable.setMenu(null);
505
        natTable.addConfiguration(
506
                new AbstractUiBindingConfiguration() {
507
            @Override
508
            public void configureUiBindings(
509
                    UiBindingRegistry uiBindingRegistry) {
510
                // add e4 menu to NatTable
511
                new PopupMenuBuilder(natTable, e4Menu)
512
                    .build();
513

    
514
                // register the UI binding for header, corner and body region
515
                uiBindingRegistry.registerMouseDownBinding(
516
                        new MouseEventMatcher(
517
                                SWT.NONE,
518
                                null,
519
                                MouseEventMatcher.RIGHT_BUTTON),
520
                        new PopupMenuAction(e4Menu));
521
            }
522
        });
523

    
524
        natTable.configure();
525
    }
526

    
527
    void freezeSupplementalColumns(boolean freeze){
528
        if(freeze){
529
            FreezeHelper.freeze(freezeLayer, bodyLayer.getViewportLayer(),
530
                    new PositionCoordinate(bodyLayer.getViewportLayer(), 0, 0),
531
                    new PositionCoordinate(bodyLayer.getViewportLayer(), LEADING_COLUMN_COUNT-1, -1));
532
        }
533
        else{
534
            FreezeHelper.unfreeze(freezeLayer, bodyLayer.getViewportLayer());
535
        }
536
    }
537

    
538
    void selectStateItem(ComboViewer comboStates, String stateName){
539
        String[] items = comboStates.getCombo().getItems();
540
        for(int i=0;i<items.length;i++){
541
            if(items[i].equals(stateName)){
542
                comboStates.getCombo().select(i);
543
                break;
544
            }
545
        }
546
    }
547

    
548
    private void initLabels(int index, Feature feature) {
549
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
550

    
551
        String featureLabel = feature.getLabel();
552
        String property = featureLabel;
553
        //show unit for quantitative data
554
        if(feature.isSupportsQuantitativeData()){
555
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
556
            if(recommendedMeasurementUnits.size()>1){
557
                MessagingUtils.warningDialog(Messages.CharacterMatrix_INIT_PROBLEM, CharacterMatrix.class,
558
                        String.format(Messages.CharacterMatrix_INIT_PROBLEM_MESSAGE, feature.getLabel()));
559
            }
560
            if(recommendedMeasurementUnits.size()==1){
561
                MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
562
                featureLabel += " ["+unit.getIdInVocabulary()+"]"; //$NON-NLS-1$ //$NON-NLS-2$
563
            }
564
        }
565
        propertyToLabelMap.put(property, featureLabel);
566
    }
567

    
568
    public void loadDescriptions(DescriptiveDataSet descriptiveDataSet) {
569
        UUID monitorUuid = CdmStore.getService(IDescriptiveDataSetService.class).monitGetRowWrapper(descriptiveDataSet);
570

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

    
626
    public IStructuredSelection getSelection(){
627
        Set<Range> selectedRowPositions = bodyLayer.getSelectionLayer().getSelectedRowPositions();
628
        List<Object> selectedObjects = new ArrayList<>();
629
        for (Range range : selectedRowPositions) {
630
            for(int i=range.start;i<range.end;i++){
631
                selectedObjects.add(bodyDataProvider.getRowObject(i));
632
            }
633
        }
634
        return new StructuredSelection(selectedObjects);
635
    }
636

    
637
    private void loadingDone() {
638
        this.part.loadingDone();
639
    }
640

    
641
    public List<State> getSupportedStatesForCategoricalFeature(Feature feature){
642
        return categoricalFeatureToStateMap.get(feature);
643
    }
644

    
645
    public Map<Integer, Feature> getIndexToFeatureMap() {
646
        return indexToFeatureMap;
647
    }
648

    
649
    public LinkedMap<String, String> getPropertyToLabelMap() {
650
        return propertyToLabelMap;
651
    }
652

    
653
    public void setDirty() {
654
        part.setDirty();
655
    }
656

    
657
    public NatTable getNatTable() {
658
        return natTable;
659
    }
660

    
661
    public EventList<Object> getDescriptions() {
662
        return descriptions;
663
    }
664

    
665
    public DescriptiveDataSet getDescriptiveDataSet() {
666
        return descriptiveDataSet;
667
    }
668

    
669
    public Collection<SpecimenNodeWrapper> getSpecimenCache() {
670
        return specimenCache;
671
    }
672

    
673
    public void setSpecimenCache(Collection<SpecimenNodeWrapper> specimenCache) {
674
        this.specimenCache = specimenCache.stream()
675
                .filter(wrapper ->
676
        //map descriptions on a list of uuids of the described specimen
677
        !this.descriptions.stream()
678
        .filter(rowWrapper->rowWrapper instanceof SpecimenRowWrapperDTO)
679
        .map(specimenRowWrapper->((SpecimenRowWrapperDTO) specimenRowWrapper).getSpecimen().getUuid())
680
        .collect(Collectors.toList())
681
        //an check if the specimen to add is already contained
682
        .contains(wrapper.getUuidAndTitleCache().getUuid())
683
        )
684
        .collect(Collectors.toList());
685
    }
686

    
687
    public Properties getNatTableState() {
688
        return toolbar.getNatTableState();
689
    }
690

    
691
    public ListDataProvider<Object> getBodyDataProvider() {
692
        return bodyDataProvider;
693
    }
694

    
695
    DefaultBodyLayerStack getBodyLayer() {
696
        return bodyLayer;
697
    }
698

    
699
    File getStatePropertiesFile() {
700
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
701
    }
702

    
703
    public List<Feature> getFeatures() {
704
        return features;
705
    }
706

    
707
    public void addUpdateResult(UpdateResult result){
708
        part.addUpdateResult(result);
709
    }
710

    
711
    public Map<Feature, CategoricalDataHistogram> getFeatureToHistogramMap() {
712
        return featureToHistogramMap;
713
    }
714

    
715
    public Map<Feature, QuantitativeDataStatistics> getFeatureToQuantDataStatisticsMap() {
716
        return featureToQuantDataStatisticsMap;
717
    }
718

    
719
    public void toogleIsShowTooltips() {
720
        this.isShowTooltips = !this.isShowTooltips;
721
    }
722

    
723
    public boolean isShowTooltips() {
724
        return isShowTooltips;
725
    }
726

    
727
    public ICdmEntitySession getCdmEntitiySession(){
728
        return part.getCdmEntitySession();
729
    }
730

    
731
}
(6-6/19)