Project

General

Profile

Download (29.1 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.DebugMenuConfiguration;
82
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuAction;
83
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
84
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
85
import org.eclipse.swt.SWT;
86
import org.eclipse.swt.layout.GridData;
87
import org.eclipse.swt.layout.GridLayout;
88
import org.eclipse.swt.widgets.Button;
89
import org.eclipse.swt.widgets.Composite;
90
import org.eclipse.swt.widgets.Menu;
91

    
92
import ca.odell.glazedlists.BasicEventList;
93
import ca.odell.glazedlists.EventList;
94
import ca.odell.glazedlists.SortedList;
95
import ca.odell.glazedlists.TreeList;
96
import eu.etaxonomy.cdm.api.service.IDescriptiveDataSetService;
97
import eu.etaxonomy.cdm.api.service.UpdateResult;
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.description.DescriptionBase;
102
import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
103
import eu.etaxonomy.cdm.model.description.Feature;
104
import eu.etaxonomy.cdm.model.description.FeatureNode;
105
import eu.etaxonomy.cdm.model.description.FeatureTree;
106
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
107
import eu.etaxonomy.cdm.model.description.State;
108
import eu.etaxonomy.cdm.persistence.dto.SpecimenNodeWrapper;
109
import eu.etaxonomy.taxeditor.editor.internal.TaxeditorEditorPlugin;
110
import eu.etaxonomy.taxeditor.editor.l10n.Messages;
111
import eu.etaxonomy.taxeditor.model.MessagingUtils;
112
import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
113
import eu.etaxonomy.taxeditor.store.CdmStore;
114
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
115

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

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

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

    
132
    static final String LABEL_TAXON_ROW = "TAXON_ROW"; //$NON-NLS-1$
133
    static final String LABEL_TAXON_AGGREGATED_DESCRIPTION = "TAXON_AGGREGATED_DESCRIPTION"; //$NON-NLS-1$
134
    static final String LABEL_TAXON_DEFAULT_DESCRIPTION = "TAXON_DEFAULT_DESCRIPTION"; //$NON-NLS-1$
135
    static final String LABEL_TAXON_LITERATURE_DESCRIPTION = "TAXON_LITERATURE_DESCRIPTION"; //$NON-NLS-1$
136
    static final String LABEL_TAXON_DESCRIPTION = "LABEL_TAXON_DESCRIPTION"; //$NON-NLS-1$
137
    static final String LABEL_DESCRIPTION_HAS_SUPPLEMENTAL_DATA = "LABEL_DESCRIPTION_HAS_SUPPLEMENTAL_DATA"; //$NON-NLS-1$
138

    
139
    @Inject
140
    private UISynchronize sync;
141

    
142
    @Inject
143
    private EMenuService menuService;
144

    
145
    private DescriptiveDataSet descriptiveDataSet;
146

    
147
    private NatTable natTable;
148

    
149
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
150

    
151
    private Map<Feature, List<State>> categoricalFeatureToStateMap = new HashMap<>();
152

    
153
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
154

    
155
    private EventList<Object> descriptions;
156

    
157
    private Collection<SpecimenNodeWrapper> specimenCache = null;
158

    
159
    private Map<Feature, CategoricalDataHistogram> featureToHistogramMap = new HashMap<>();
160

    
161
    private Map<Feature, QuantitativeDataStatistics> featureToQuantDataStatisticsMap = new HashMap<>();
162

    
163
    private ListDataProvider<Object> bodyDataProvider;
164

    
165
    private FreezeLayer freezeLayer;
166

    
167
    private List<Feature> features;
168

    
169
    private CharacterMatrixPart part;
170

    
171
    private AbstractLayer topMostLayer;
172

    
173
    private FixedSummaryRowLayer summaryRowLayer;
174

    
175
    private ConfigRegistry configRegistry;
176

    
177
    private DefaultBodyLayerStack bodyLayer;
178

    
179
    private boolean isTreeView = true;
180

    
181
    private CharacterMatrixToolbar toolbar;
182

    
183
    private boolean isShowTooltips = true;
184

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

    
190
        createToolBar();
191

    
192
        natTable = new NatTable(this, false);
193

    
194
        createBottomToolbar();
195

    
196
    }
197

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

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

    
207

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

    
217
    }
218

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

    
228
    public boolean isTreeView() {
229
        return isTreeView;
230
    }
231

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

    
238
        /**
239
         * configuration
240
         */
241
        configureNatTable(treeView, configRegistry, topMostLayer, summaryRowLayer);
242

    
243
        /**
244
         * handlers and listeners
245
         */
246
        registerHandlersAndListeners(topMostLayer);
247

    
248
        //grab all space
249
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
250

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

    
256
        //initial freeze of supplemental columns
257
        freezeSupplementalColumns(freezeSupplementalColumns);
258

    
259

    
260
        //add tooltip to table
261
        new CategoricalChartTooltip(this);
262
        new QuantitativeChartTooltip(this);
263

    
264
        this.layout();
265
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
266
    }
267

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

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

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

    
295
    }
296

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

    
309
        configRegistry = new ConfigRegistry();
310

    
311

    
312
        /**
313
         * BODY layer
314
         *
315
         *
316

    
317
        CompositeLayer
318
         - (top) SummaryRowLayer
319
         - (bottom) ViewportLayer
320

    
321
             ^
322
        ViewportLayer
323

    
324
             ^
325
        TreeLayer (default visible)
326

    
327
             ^
328
        CompositeFreezeLayer
329
         - viewportLayer
330
         - selectionLayer
331
         - freezeLayer
332

    
333
             ^
334
        FreezeLayer
335

    
336
             ^
337
        SelectionLayer
338

    
339
             ^
340
        ColumnHideShowLayer
341

    
342
             ^
343
        ColumnReorderLayer
344

    
345
             ^
346
        DataLayer
347

    
348
         *
349

    
350
         */
351
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
352

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

    
357

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

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

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

    
379
        topMostLayer = treeView?treeLayer:compositeFreezeLayer;
380

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

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

    
399

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

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

    
419

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

    
429

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

    
437

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

    
443
        natTable.setLayer(gridLayer);
444

    
445
    }
446

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

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

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

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

    
471
        applyStyles();
472

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

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

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

    
485
        natTable.addConfiguration(new CharacterMatrixLabelStyleConfiguration());
486

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

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

    
494
        //register aggregation configuration
495
        summaryRowLayer.addConfiguration(new AggregationConfiguration(this));
496

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

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

    
522
        natTable.configure();
523
    }
524

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

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

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

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

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

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

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

    
635
    private void loadingDone() {
636
        this.part.loadingDone();
637
    }
638

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

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

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

    
651
    public void setDirty() {
652
        part.setDirty();
653
    }
654

    
655
    public NatTable getNatTable() {
656
        return natTable;
657
    }
658

    
659
    public EventList<Object> getDescriptions() {
660
        return descriptions;
661
    }
662

    
663
    public DescriptiveDataSet getDescriptiveDataSet() {
664
        return descriptiveDataSet;
665
    }
666

    
667
    public Collection<SpecimenNodeWrapper> getSpecimenCache() {
668
        return specimenCache;
669
    }
670

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

    
685
    public Properties getNatTableState() {
686
        return toolbar.getNatTableState();
687
    }
688

    
689
    public ListDataProvider<Object> getBodyDataProvider() {
690
        return bodyDataProvider;
691
    }
692

    
693
    DefaultBodyLayerStack getBodyLayer() {
694
        return bodyLayer;
695
    }
696

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

    
701
    public List<Feature> getFeatures() {
702
        return features;
703
    }
704

    
705
    public void addUpdateResult(UpdateResult result){
706
        part.addUpdateResult(result);
707
    }
708

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

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

    
717
    public void toogleIsShowTooltips() {
718
        this.isShowTooltips = !this.isShowTooltips;
719
    }
720

    
721
    public boolean isShowTooltips() {
722
        return isShowTooltips;
723
    }
724

    
725
    public ICdmEntitySession getCdmEntitiySession(){
726
        return part.getCdmEntitySession();
727
    }
728

    
729
}
(6-6/19)