Project

General

Profile

Download (29.5 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.Collections;
15
import java.util.HashMap;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Properties;
19
import java.util.Set;
20
import java.util.UUID;
21
import java.util.stream.Collectors;
22

    
23
import javax.inject.Inject;
24

    
25
import org.apache.commons.collections4.map.LinkedMap;
26
import org.eclipse.core.runtime.ICoreRunnable;
27
import org.eclipse.core.runtime.IProgressMonitor;
28
import org.eclipse.core.runtime.SubMonitor;
29
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
30
import org.eclipse.core.runtime.jobs.Job;
31
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
32
import org.eclipse.e4.ui.di.UISynchronize;
33
import org.eclipse.e4.ui.services.EMenuService;
34
import org.eclipse.jface.layout.GridDataFactory;
35
import org.eclipse.jface.viewers.ComboViewer;
36
import org.eclipse.jface.viewers.IStructuredSelection;
37
import org.eclipse.jface.viewers.StructuredSelection;
38
import org.eclipse.nebula.widgets.nattable.NatTable;
39
import org.eclipse.nebula.widgets.nattable.config.AbstractUiBindingConfiguration;
40
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
41
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
42
import org.eclipse.nebula.widgets.nattable.coordinate.PositionCoordinate;
43
import org.eclipse.nebula.widgets.nattable.coordinate.Range;
44
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
45
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
46
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommandHandler;
47
import org.eclipse.nebula.widgets.nattable.extension.e4.selection.E4SelectionListener;
48
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
49
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
50
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeData;
51
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeRowModel;
52
import org.eclipse.nebula.widgets.nattable.freeze.CompositeFreezeLayer;
53
import org.eclipse.nebula.widgets.nattable.freeze.FreezeHelper;
54
import org.eclipse.nebula.widgets.nattable.freeze.FreezeLayer;
55
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
56
import org.eclipse.nebula.widgets.nattable.grid.command.ClientAreaResizeCommand;
57
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
58
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
59
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
60
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
61
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
62
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
63
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
64
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
65
import org.eclipse.nebula.widgets.nattable.layer.AbstractLayer;
66
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
67
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
68
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
69
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
70
import org.eclipse.nebula.widgets.nattable.layer.stack.DefaultBodyLayerStack;
71
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
72
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
73
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
74
import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum;
75
import org.eclipse.nebula.widgets.nattable.style.theme.ModernNatTableThemeConfiguration;
76
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
77
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
78
import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel;
79
import org.eclipse.nebula.widgets.nattable.tree.TreeLayer;
80
import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry;
81
import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher;
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.application.CdmApplicationState;
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.Character;
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_AGGREGATED_DESCRIPTION_ICON = "TAXON_AGGREGATED_DESCRIPTION_ICON"; //$NON-NLS-1$
135
    static final String LABEL_TAXON_DEFAULT_DESCRIPTION = "TAXON_DEFAULT_DESCRIPTION"; //$NON-NLS-1$
136
    static final String LABEL_TAXON_DEFAULT_DESCRIPTION_ICON = "TAXON_DEFAULT_DESCRIPTION_ICON"; //$NON-NLS-1$
137
    static final String LABEL_TAXON_LITERATURE_DESCRIPTION = "TAXON_LITERATURE_DESCRIPTION"; //$NON-NLS-1$
138
    static final String LABEL_TAXON_LITERATURE_DESCRIPTION_ICON = "TAXON_LITERATURE_DESCRIPTION_ICON"; //$NON-NLS-1$
139
    static final String LABEL_TAXON_DESCRIPTION = "LABEL_TAXON_DESCRIPTION"; //$NON-NLS-1$
140
    static final String LABEL_DESCRIPTION_HAS_SUPPLEMENTAL_DATA = "LABEL_DESCRIPTION_HAS_SUPPLEMENTAL_DATA"; //$NON-NLS-1$
141

    
142
    @Inject
143
    private UISynchronize sync;
144

    
145
    @Inject
146
    private EMenuService menuService;
147

    
148
    private DescriptiveDataSet descriptiveDataSet;
149

    
150
    private NatTable natTable;
151

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

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

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

    
158
    private EventList<Object> descriptions;
159

    
160
    private Collection<SpecimenNodeWrapper> specimenCache = null;
161

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

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

    
166
    private ListDataProvider<Object> bodyDataProvider;
167

    
168
    private FreezeLayer freezeLayer;
169

    
170
    private List<Feature> features;
171

    
172
    private CharacterMatrixPart part;
173

    
174
    private AbstractLayer topMostLayer;
175

    
176
    private FixedSummaryRowLayer summaryRowLayer;
177

    
178
    private ConfigRegistry configRegistry;
179

    
180
    private DefaultBodyLayerStack bodyLayer;
181

    
182
    private boolean isTreeView = true;
183

    
184
    private CharacterMatrixToolbar toolbar;
185

    
186
    private boolean isShowTooltips = true;
187

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

    
193
        createToolBar();
194

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

    
197
        createBottomToolbar();
198

    
199
    }
200

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

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

    
210

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

    
220
    }
221

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

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

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

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

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

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

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

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

    
262

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

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

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

    
284
    public void initDescriptiveDataSet(DescriptiveDataSet descriptiveDataSet){
285
        this.descriptiveDataSet = descriptiveDataSet;
286
        //get features/columns stored in descriptive data set
287
        FeatureTree tree = descriptiveDataSet.getDescriptiveSystem();
288
        features = initFeatureList(tree.getRoot());
289

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

    
301
    }
302

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

    
313
        configRegistry = new ConfigRegistry();
314

    
315

    
316
        /**
317
         * BODY layer
318
         *
319
         *
320

    
321
        CompositeLayer
322
         - (top) SummaryRowLayer
323
         - (bottom) ViewportLayer
324

    
325
             ^
326
        ViewportLayer
327

    
328
             ^
329
        TreeLayer (default visible)
330

    
331
             ^
332
        CompositeFreezeLayer
333
         - viewportLayer
334
         - selectionLayer
335
         - freezeLayer
336

    
337
             ^
338
        FreezeLayer
339

    
340
             ^
341
        SelectionLayer
342

    
343
             ^
344
        ColumnHideShowLayer
345

    
346
             ^
347
        ColumnReorderLayer
348

    
349
             ^
350
        DataLayer
351

    
352
         *
353

    
354
         */
355
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
356

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

    
361

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

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

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

    
383
        topMostLayer = treeView?treeLayer:compositeFreezeLayer;
384

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

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

    
403

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

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

    
423

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

    
433

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

    
441

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

    
447
        natTable.setLayer(gridLayer);
448

    
449
    }
450

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

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

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

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

    
475
        applyStyles();
476

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

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

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

    
489
        natTable.addConfiguration(new CharacterMatrixLabelStyleConfiguration());
490

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

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

    
498
        //register aggregation configuration
499
        summaryRowLayer.addConfiguration(new AggregationConfiguration(this));
500

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

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

    
526
        natTable.configure();
527
    }
528

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

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

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

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

    
570
    public void loadDescriptions(DescriptiveDataSet descriptiveDataSet) {
571
        UUID monitorUuid =  CdmApplicationState.getLongRunningTasksService().monitGetRowWrapper(descriptiveDataSet);
572

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

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

    
639
    private void loadingDone() {
640
        this.part.loadingDone();
641
        createTable(isTreeView, freezeLayer.isFrozen());
642
        Collections.sort(descriptions, new MatrixRowComparator());
643
    }
644

    
645
    public List<State> getSupportedStatesForCategoricalFeature(Feature feature){
646
        return categoricalFeatureToStateMap.get(feature);
647
    }
648

    
649
    public Map<Integer, Feature> getIndexToFeatureMap() {
650
        return indexToFeatureMap;
651
    }
652

    
653
    public LinkedMap<String, String> getPropertyToLabelMap() {
654
        return propertyToLabelMap;
655
    }
656

    
657
    public void setDirty() {
658
        part.setDirty();
659
    }
660

    
661
    public CharacterMatrixPart getPart() {
662
        return part;
663
    }
664

    
665
    public NatTable getNatTable() {
666
        return natTable;
667
    }
668

    
669
    public EventList<Object> getDescriptions() {
670
        return descriptions;
671
    }
672

    
673
    public DescriptiveDataSet getDescriptiveDataSet() {
674
        return descriptiveDataSet;
675
    }
676

    
677
    public Collection<SpecimenNodeWrapper> getSpecimenCache() {
678
        return specimenCache;
679
    }
680

    
681
    public void setSpecimenCache(Collection<SpecimenNodeWrapper> specimenCache) {
682
        this.specimenCache = specimenCache.stream()
683
                .filter(wrapper ->
684
        //map descriptions on a list of uuids of the described specimen
685
        !this.descriptions.stream()
686
        .filter(rowWrapper->rowWrapper instanceof SpecimenRowWrapperDTO)
687
        .map(specimenRowWrapper->((SpecimenRowWrapperDTO) specimenRowWrapper).getSpecimen().getUuid())
688
        .collect(Collectors.toList())
689
        //an check if the specimen to add is already contained
690
        .contains(wrapper.getUuidAndTitleCache().getUuid())
691
        )
692
        .collect(Collectors.toList());
693
    }
694

    
695
    public Properties getNatTableState() {
696
        return toolbar.getNatTableState();
697
    }
698

    
699
    public ListDataProvider<Object> getBodyDataProvider() {
700
        return bodyDataProvider;
701
    }
702

    
703
    DefaultBodyLayerStack getBodyLayer() {
704
        return bodyLayer;
705
    }
706

    
707
    File getStatePropertiesFile() {
708
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
709
    }
710

    
711
    public List<Feature> getFeatures() {
712
        return features;
713
    }
714

    
715
    public Map<Feature, CategoricalDataHistogram> getFeatureToHistogramMap() {
716
        return featureToHistogramMap;
717
    }
718

    
719
    public Map<Feature, QuantitativeDataStatistics> getFeatureToQuantDataStatisticsMap() {
720
        return featureToQuantDataStatisticsMap;
721
    }
722

    
723
    public void toogleIsShowTooltips() {
724
        this.isShowTooltips = !this.isShowTooltips;
725
    }
726

    
727
    public boolean isShowTooltips() {
728
        return isShowTooltips;
729
    }
730

    
731
    public ICdmEntitySession getCdmEntitiySession(){
732
        return part.getCdmEntitySession();
733
    }
734

    
735
}
(6-6/19)