Project

General

Profile

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

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

    
95
import ca.odell.glazedlists.BasicEventList;
96
import ca.odell.glazedlists.EventList;
97
import ca.odell.glazedlists.SortedList;
98
import ca.odell.glazedlists.TreeList;
99
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
100
import eu.etaxonomy.cdm.api.service.dto.RowWrapperDTO;
101
import eu.etaxonomy.cdm.api.service.dto.SpecimenRowWrapperDTO;
102
import eu.etaxonomy.cdm.common.monitor.IRemotingProgressMonitor;
103
import eu.etaxonomy.cdm.model.description.Character;
104
import eu.etaxonomy.cdm.model.description.DescriptionBase;
105
import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
106
import eu.etaxonomy.cdm.model.description.Feature;
107
import eu.etaxonomy.cdm.model.description.FeatureNode;
108
import eu.etaxonomy.cdm.model.description.FeatureTree;
109
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
110
import eu.etaxonomy.cdm.model.description.State;
111
import eu.etaxonomy.cdm.persistence.dto.SpecimenNodeWrapper;
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<State>> 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
    private DataLayer bodyDataLayer;
192

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

    
198
        createToolBar();
199

    
200
        natTable = new NatTable(this, false);
201

    
202
        createBottomToolbar();
203

    
204
    }
205

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

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

    
215

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

    
225
    }
226

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

    
236
    public boolean isTreeView() {
237
        return isTreeView;
238
    }
239

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

    
246
        /**
247
         * configuration
248
         */
249
        configureNatTable(treeView, configRegistry, topMostLayer, summaryRowLayer);
250

    
251
        /**
252
         * handlers and listeners
253
         */
254
        registerHandlersAndListeners(topMostLayer);
255

    
256
        //grab all space
257
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
258

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

    
264
        //initial freeze of supplemental columns
265
        freezeSupplementalColumns(freezeSupplementalColumns);
266

    
267

    
268
        //add tooltip to table
269
        new CategoricalChartTooltip(this);
270
        new QuantitativeChartTooltip(this);
271

    
272
        this.layout();
273
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
274
    }
275

    
276
    private List<Feature> initFeatureList(FeatureNode node){
277
        List<Feature> features = new ArrayList<>();
278
        node.getChildNodes().forEach(childNode->
279
                {
280
                    Feature feature = childNode.getFeature();
281
                    if(feature.isInstanceOf(Character.class)){
282
                        features.add(childNode.getFeature());
283
                    }
284
                    features.addAll(initFeatureList(childNode));
285
                });
286
        return features;
287
    }
288

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

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

    
306
    }
307

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

    
318
        configRegistry = new ConfigRegistry();
319

    
320

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

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

    
330
             ^
331
        ViewportLayer
332

    
333
             ^
334
        TreeLayer (default visible)
335

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

    
342
             ^
343
        FreezeLayer
344

    
345
             ^
346
        SelectionLayer
347

    
348
             ^
349
        ColumnHideShowLayer
350

    
351
             ^
352
        ColumnReorderLayer
353

    
354
             ^
355
        DataLayer
356

    
357
         *
358

    
359
         */
360
        bodyDataLayer = new DataLayer(bodyDataProvider);
361

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

    
366

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

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

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

    
388
        topMostLayer = treeView?treeLayer:compositeFreezeLayer;
389

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

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

    
408

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

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

    
428

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

    
438

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

    
446

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

    
452
        natTable.setLayer(gridLayer);
453

    
454
    }
455

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

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

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

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

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

    
487
        applyStyles();
488

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

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

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

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

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

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

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

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

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

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

    
541
        natTable.configure();
542
    }
543

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

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

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

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

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

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

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

    
654
    private void loadingDone() {
655
        this.part.loadingDone();
656
        createTable(isTreeView, freezeLayer.isFrozen());
657
        Collections.sort(descriptions, new MatrixRowComparator());
658
    }
659

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
726
    public List<Feature> getFeatures() {
727
        return features;
728
    }
729

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

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

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

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

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

    
750
}
(6-6/20)