Project

General

Profile

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

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

    
22
import javax.inject.Inject;
23

    
24
import org.apache.commons.collections4.map.LinkedMap;
25
import org.eclipse.core.runtime.ICoreRunnable;
26
import org.eclipse.core.runtime.IProgressMonitor;
27
import org.eclipse.core.runtime.SubMonitor;
28
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
29
import org.eclipse.core.runtime.jobs.Job;
30
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
31
import org.eclipse.e4.ui.di.UISynchronize;
32
import org.eclipse.e4.ui.services.EMenuService;
33
import org.eclipse.jface.layout.GridDataFactory;
34
import org.eclipse.jface.viewers.IStructuredSelection;
35
import org.eclipse.jface.viewers.StructuredSelection;
36
import org.eclipse.nebula.widgets.nattable.NatTable;
37
import org.eclipse.nebula.widgets.nattable.config.AbstractUiBindingConfiguration;
38
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
39
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
40
import org.eclipse.nebula.widgets.nattable.coordinate.PositionCoordinate;
41
import org.eclipse.nebula.widgets.nattable.coordinate.Range;
42
import org.eclipse.nebula.widgets.nattable.copy.command.InternalCopyDataCommandHandler;
43
import org.eclipse.nebula.widgets.nattable.copy.command.InternalPasteDataCommandHandler;
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.persistence.gui.PersistenceDialog;
72
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
73
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
74
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
75
import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum;
76
import org.eclipse.nebula.widgets.nattable.style.theme.ModernNatTableThemeConfiguration;
77
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
78
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
79
import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel;
80
import org.eclipse.nebula.widgets.nattable.tree.TreeLayer;
81
import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry;
82
import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher;
83
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuAction;
84
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
85
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
86
import org.eclipse.swt.SWT;
87
import org.eclipse.swt.layout.GridData;
88
import org.eclipse.swt.layout.GridLayout;
89
import org.eclipse.swt.widgets.Button;
90
import org.eclipse.swt.widgets.Composite;
91
import org.eclipse.swt.widgets.Menu;
92

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

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

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

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

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

    
145
    @Inject
146
    private UISynchronize sync;
147

    
148
    @Inject
149
    private EMenuService menuService;
150

    
151
    private DescriptiveDataSet descriptiveDataSet;
152

    
153
    private NatTable natTable;
154

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

    
157
    private Map<Feature, List<TermDto>> categoricalFeatureToStateMap = new HashMap<>();
158

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

    
161
    private EventList<Object> descriptions;
162

    
163
    private Collection<SpecimenNodeWrapper> specimenCache = null;
164

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

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

    
169
    private ListDataProvider<Object> bodyDataProvider;
170

    
171
    private FreezeLayer freezeLayer;
172

    
173
    private List<Feature> features;
174

    
175
    private CharacterMatrixPart part;
176

    
177
    private AbstractLayer topMostLayer;
178

    
179
    private FixedSummaryRowLayer summaryRowLayer;
180

    
181
    private ConfigRegistry configRegistry;
182

    
183
    private DefaultBodyLayerStack bodyLayer;
184

    
185
    private boolean isTreeView = true;
186

    
187
    private CharacterMatrixToolbar toolbar;
188

    
189
    private boolean isShowTooltips = true;
190

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

    
196
        createToolBar();
197

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

    
200
        createBottomToolbar();
201

    
202
    }
203

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

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

    
213

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

    
223
    }
224

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

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

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

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

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

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

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

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

    
265

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

    
270

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

    
274
        // clean up table state
275
        getNatTableState().remove(NatTable.INITIAL_PAINT_COMPLETE_FLAG);
276
        getNatTableState().remove(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY);
277
    }
278

    
279
    private List<Feature> initFeatureList(TermNode<Feature> node){
280
        List<Feature> features = new ArrayList<>();
281
        node.getChildNodes().forEach(childNode->
282
                {
283
                    features.add(childNode.getTerm());
284
                    features.addAll(initFeatureList(childNode));
285
                });
286
        return features;
287
    }
288

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

    
295
        //init state data for categorical features
296
        features.forEach(feature->fetchSupportedStates(feature));
297

    
298
        descriptions = new BasicEventList<>();
299

    
300
    }
301

    
302
    private void fetchSupportedStates(Feature feature) {
303
        if(feature.isSupportsCategoricalData()){
304
            Set<TermVocabulary<State>> supportedCategoricalEnumerations = feature.getSupportedCategoricalEnumerations();
305
            List<UUID> vocUuids = new ArrayList<>();
306
            for (TermVocabulary<State> termVocabulary : supportedCategoricalEnumerations) {
307
                vocUuids.add(termVocabulary.getUuid());
308
            }
309
            List<TermDto> supportedStates = new ArrayList<>(CdmStore.getService(IVocabularyService.class).getTerms(vocUuids));
310
            categoricalFeatureToStateMap.put(feature, supportedStates);
311
        }
312
    }
313

    
314
    private void createLayers(boolean treeView) {
315
        SortedList<Object> sortedList = new SortedList<>(descriptions, new MatrixRowComparator());
316
        // wrap the SortedList with the TreeList
317
        TreeList<Object> treeList = new TreeList(sortedList, new DescriptionTreeFormat(descriptiveDataSet), TreeList.NODES_START_EXPANDED);
318
        /**
319
         * data provider
320
         */
321
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
322
        bodyDataProvider = treeView?new ListDataProvider<>(treeList, columnPropertyAccessor):new ListDataProvider<>(sortedList, columnPropertyAccessor);
323

    
324
        configRegistry = new ConfigRegistry();
325

    
326

    
327
        /**
328
         * BODY layer
329
         *
330
         *
331

    
332
        CompositeLayer
333
         - (top) SummaryRowLayer
334
         - (bottom) ViewportLayer
335

    
336
             ^
337
        ViewportLayer
338

    
339
             ^
340
        TreeLayer (default visible)
341

    
342
             ^
343
        CompositeFreezeLayer
344
         - viewportLayer
345
         - selectionLayer
346
         - freezeLayer
347

    
348
             ^
349
        FreezeLayer
350

    
351
             ^
352
        SelectionLayer
353

    
354
             ^
355
        ColumnHideShowLayer
356

    
357
             ^
358
        ColumnReorderLayer
359

    
360
             ^
361
        DataLayer
362

    
363
         *
364

    
365
         */
366
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
367
        bodyDataLayer.registerCommandHandler(new CopyPasteUpdateDataCommandHandler(bodyDataLayer));
368

    
369
        //register labels
370
        CharacterMatrixConfigLabelAccumulator labelAccumulator = new CharacterMatrixConfigLabelAccumulator(this);
371
        bodyDataLayer.setConfigLabelAccumulator(labelAccumulator);
372

    
373

    
374
        propertyToLabelMap.put(TAXON_COLUMN, Messages.CharacterMatrix_TAXON);
375
        propertyToLabelMap.put(COLLECTOR_COLUMN, Messages.CharacterMatrix_COLLECTOR_NO);
376
        propertyToLabelMap.put(IDENTIFIER_COLUMN, Messages.CharacterMatrix_IDENTIFIER);
377
        propertyToLabelMap.put(COUNTRY_COLUMN, Messages.CharacterMatrix_COUNTRY);
378
        for(int i=0;i<features.size();i++){
379
            Feature feature = features.get(i);
380
            initLabels(i, feature);
381
        }
382

    
383
        // layer for event handling of GlazedLists and PropertyChanges
384
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, (EventList)bodyDataProvider.getList());
385

    
386
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
387
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
388

    
389
        bodyLayer = new DefaultBodyLayerStack(eventLayer);
390
        final SelectionLayer selectionLayer = bodyLayer.getSelectionLayer();
391
        freezeLayer = new FreezeLayer(selectionLayer);
392
        final CompositeFreezeLayer compositeFreezeLayer = new CompositeFreezeLayer(
393
                freezeLayer, bodyLayer.getViewportLayer(), selectionLayer);
394
        TreeLayer treeLayer = new TreeLayer(compositeFreezeLayer, treeRowModel);
395

    
396
        topMostLayer = treeView?treeLayer:compositeFreezeLayer;
397

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

    
412
        CompositeLayer composite = new CompositeLayer(1, 2);
413
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0); //$NON-NLS-1$
414
        composite.setChildLayer(GridRegion.BODY, topMostLayer, 0, 1);
415

    
416

    
417
        /**
418
         * column header layer
419
         */
420
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
421
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
422
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
423
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, topMostLayer, selectionLayer);
424

    
425
        // add the SortHeaderLayer to the column header layer stack
426
        // as we use GlazedLists, we use the GlazedListsSortModel which
427
        // delegates the sorting to the SortedList
428
        final SortHeaderLayer<DescriptionBase> sortHeaderLayer = new SortHeaderLayer<>(
429
                columnHeaderLayer,
430
                new GlazedListsSortModel<>(
431
                        sortedList,
432
                        columnPropertyAccessor,
433
                        configRegistry,
434
                        columnHeaderDataLayer));
435

    
436

    
437
        /**
438
         * row header layer
439
         */
440
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
441
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
442
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
443
                composite, selectionLayer);
444
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211"); //$NON-NLS-1$
445

    
446

    
447
        /**
448
         * corner layer
449
         */
450
        ILayer cornerLayer = new CornerLayer(
451
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
452
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
453

    
454

    
455
        /**
456
         * GRID layer (composition of all other layers)
457
         */
458
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
459

    
460
        natTable.setLayer(gridLayer);
461

    
462
    }
463

    
464
    private void registerHandlersAndListeners() {
465
        natTable.registerCommandHandler(new ExportCommandHandler(natTable));
466

    
467
        //selection listener
468
        E4SelectionListener selectionListener = new CellSelectionListener(part.getSelectionService(),
469
                bodyLayer.getSelectionLayer(), bodyDataProvider, part);
470
        bodyLayer.getSelectionLayer().addLayerListener(selectionListener);
471
        selectionListener.setFullySelectedRowsOnly(false);
472

    
473
        //register handler for view configuration menu
474
        natTable.registerCommandHandler(toolbar.getDisplayPersistenceDialogCommandHandler());
475

    
476
        //register handlers for copy&paste
477
        natTable.registerCommandHandler(
478
                new InternalPasteDataCommandHandler(bodyLayer.getSelectionLayer(), natTable.getInternalCellClipboard()));
479
        natTable.registerCommandHandler(
480
                new InternalCopyDataCommandHandler(bodyLayer.getSelectionLayer(), natTable.getInternalCellClipboard()));
481
    }
482

    
483
    private void configureNatTable(boolean treeView,
484
            ConfigRegistry configRegistry,
485
            AbstractLayer topMostLayer,
486
            FixedSummaryRowLayer summaryRowLayer) {
487
        /**
488
         * CONFIGURATION
489
         */
490
        natTable.setConfigRegistry(configRegistry);
491

    
492
        applyStyles();
493

    
494
        //add default configuration because autoconfigure is set to false in constructor
495
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
496

    
497
        // this is for DEBUG ONLY
498
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
499

    
500
        // override the default sort configuration and change the mouse bindings
501
        // to sort on a single click
502
        if(!treeView){
503
            natTable.addConfiguration(new SingleClickSortConfiguration());
504
        }
505

    
506
        natTable.addConfiguration(new CharacterMatrixLabelStyleConfiguration());
507

    
508
        // add the header menu configuration for adding the column header menu
509
        // with hide/show actions
510
        natTable.addConfiguration(new CharacterMatrixHeaderMenuConfiguration(natTable));
511

    
512
        // add custom configuration for data conversion and add column labels to viewport layer
513
        topMostLayer.addConfiguration(new CellEditorDataConversionConfiguration(this));
514

    
515
        //register aggregation configuration
516
        summaryRowLayer.addConfiguration(new AggregationConfiguration(this));
517

    
518
        //copy&paste configuration
519
        natTable.addConfiguration(new CopyPasteEditBindings(bodyLayer.getSelectionLayer(), natTable.getInternalCellClipboard()));
520

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

    
536
                // register the UI binding for header, corner and body region
537
                uiBindingRegistry.registerMouseDownBinding(
538
                        new MouseEventMatcher(
539
                                SWT.NONE,
540
                                GridRegion.BODY,
541
                                MouseEventMatcher.RIGHT_BUTTON),
542
                        new PopupMenuAction(e4Menu));
543
            }
544
        });
545

    
546
        natTable.configure();
547
    }
548

    
549
    void freezeSupplementalColumns(boolean freeze){
550
        if(freeze){
551
            FreezeHelper.freeze(freezeLayer, bodyLayer.getViewportLayer(),
552
                    new PositionCoordinate(bodyLayer.getViewportLayer(), 0, 0),
553
                    new PositionCoordinate(bodyLayer.getViewportLayer(), LEADING_COLUMN_COUNT-1, -1));
554
        }
555
        else{
556
            FreezeHelper.unfreeze(freezeLayer, bodyLayer.getViewportLayer());
557
        }
558
    }
559

    
560
    private void initLabels(int index, Feature feature) {
561
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
562

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

    
580
    public void loadDescriptions(DescriptiveDataSet descriptiveDataSet) {
581
        UUID monitorUuid =  CdmApplicationState.getLongRunningTasksService().monitGetRowWrapper(descriptiveDataSet);
582

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

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

    
649
    private void loadingDone() {
650
        this.part.loadingDone();
651
        createTable(isTreeView, freezeLayer.isFrozen());
652
    }
653

    
654
    public List<TermDto> getSupportedStatesForCategoricalFeature(Feature feature){
655
        return categoricalFeatureToStateMap.get(feature);
656
    }
657

    
658
    public Map<Integer, Feature> getIndexToFeatureMap() {
659
        return indexToFeatureMap;
660
    }
661

    
662
    public LinkedMap<String, String> getPropertyToLabelMap() {
663
        return propertyToLabelMap;
664
    }
665

    
666
    public void setDirty() {
667
        part.setDirty();
668
    }
669

    
670
    public CharacterMatrixPart getPart() {
671
        return part;
672
    }
673

    
674
    public NatTable getNatTable() {
675
        return natTable;
676
    }
677

    
678
    public EventList<Object> getDescriptions() {
679
        return descriptions;
680
    }
681

    
682
    public DescriptiveDataSet getDescriptiveDataSet() {
683
        return descriptiveDataSet;
684
    }
685

    
686
    public Collection<SpecimenNodeWrapper> getSpecimenCache() {
687
        return specimenCache;
688
    }
689

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

    
704
    public Properties getNatTableState() {
705
        return toolbar.getNatTableState();
706
    }
707

    
708
    public ListDataProvider<Object> getBodyDataProvider() {
709
        return bodyDataProvider;
710
    }
711

    
712
    DefaultBodyLayerStack getBodyLayer() {
713
        return bodyLayer;
714
    }
715

    
716
    File getStatePropertiesFile() {
717
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
718
    }
719

    
720
    public List<Feature> getFeatures() {
721
        return features;
722
    }
723

    
724
    public Map<Feature, CategoricalDataHistogram> getFeatureToHistogramMap() {
725
        return featureToHistogramMap;
726
    }
727

    
728
    public Map<Feature, QuantitativeDataStatistics> getFeatureToQuantDataStatisticsMap() {
729
        return featureToQuantDataStatisticsMap;
730
    }
731

    
732
    public void toogleIsShowTooltips() {
733
        this.isShowTooltips = !this.isShowTooltips;
734
    }
735

    
736
    public boolean isShowTooltips() {
737
        return isShowTooltips;
738
    }
739

    
740
    public ICdmEntitySession getCdmEntitiySession(){
741
        return part.getCdmEntitySession();
742
    }
743

    
744
}
(6-6/21)