Project

General

Profile

Download (41.7 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.workingSet.matrix;
10

    
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileOutputStream;
14
import java.io.IOException;
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.Collection;
18
import java.util.Collections;
19
import java.util.HashMap;
20
import java.util.HashSet;
21
import java.util.List;
22
import java.util.Map;
23
import java.util.Properties;
24
import java.util.Set;
25
import java.util.UUID;
26

    
27
import javax.annotation.PostConstruct;
28
import javax.annotation.PreDestroy;
29
import javax.inject.Inject;
30

    
31
import org.apache.commons.collections4.map.LinkedMap;
32
import org.eclipse.core.runtime.IProgressMonitor;
33
import org.eclipse.e4.ui.di.Focus;
34
import org.eclipse.e4.ui.di.Persist;
35
import org.eclipse.e4.ui.model.application.ui.MDirtyable;
36
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
37
import org.eclipse.e4.ui.workbench.modeling.ESelectionService;
38
import org.eclipse.jface.layout.GridDataFactory;
39
import org.eclipse.jface.viewers.ArrayContentProvider;
40
import org.eclipse.jface.viewers.ComboViewer;
41
import org.eclipse.jface.viewers.LabelProvider;
42
import org.eclipse.jface.viewers.StructuredSelection;
43
import org.eclipse.jface.window.Window;
44
import org.eclipse.nebula.widgets.nattable.NatTable;
45
import org.eclipse.nebula.widgets.nattable.command.StructuralRefreshCommand;
46
import org.eclipse.nebula.widgets.nattable.command.VisualRefreshCommand;
47
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
48
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
49
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
50
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
51
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
52
import org.eclipse.nebula.widgets.nattable.config.IEditableRule;
53
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
54
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
55
import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes;
56
import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider;
57
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommand;
58
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommandHandler;
59
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
60
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
61
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeData;
62
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeRowModel;
63
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
64
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
65
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
66
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
67
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
68
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
69
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
70
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
71
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
72
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
73
import org.eclipse.nebula.widgets.nattable.hideshow.RowHideShowLayer;
74
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
75
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
76
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
77
import org.eclipse.nebula.widgets.nattable.layer.ILayerListener;
78
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
79
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
80
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent;
81
import org.eclipse.nebula.widgets.nattable.persistence.PersistenceHelper;
82
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommand;
83
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommandHandler;
84
import org.eclipse.nebula.widgets.nattable.persistence.command.IStateChangedListener;
85
import org.eclipse.nebula.widgets.nattable.persistence.command.StateChangeEvent;
86
import org.eclipse.nebula.widgets.nattable.persistence.gui.PersistenceDialog;
87
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
88
import org.eclipse.nebula.widgets.nattable.reorder.RowReorderLayer;
89
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
90
import org.eclipse.nebula.widgets.nattable.selection.event.CellSelectionEvent;
91
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
92
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
93
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
94
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
95
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
96
import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel;
97
import org.eclipse.nebula.widgets.nattable.tree.TreeLayer;
98
import org.eclipse.nebula.widgets.nattable.tree.command.TreeCollapseAllCommand;
99
import org.eclipse.nebula.widgets.nattable.tree.command.TreeExpandAllCommand;
100
import org.eclipse.nebula.widgets.nattable.ui.menu.AbstractHeaderMenuConfiguration;
101
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
102
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
103
import org.eclipse.swt.SWT;
104
import org.eclipse.swt.events.SelectionAdapter;
105
import org.eclipse.swt.events.SelectionEvent;
106
import org.eclipse.swt.layout.GridData;
107
import org.eclipse.swt.layout.GridLayout;
108
import org.eclipse.swt.layout.RowLayout;
109
import org.eclipse.swt.widgets.Button;
110
import org.eclipse.swt.widgets.Composite;
111
import org.eclipse.swt.widgets.Label;
112

    
113
import ca.odell.glazedlists.EventList;
114
import ca.odell.glazedlists.GlazedLists;
115
import ca.odell.glazedlists.SortedList;
116
import ca.odell.glazedlists.TreeList;
117
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
118
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
119
import eu.etaxonomy.cdm.api.service.IWorkingSetService;
120
import eu.etaxonomy.cdm.model.common.TermVocabulary;
121
import eu.etaxonomy.cdm.model.description.DescriptionBase;
122
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
123
import eu.etaxonomy.cdm.model.description.Feature;
124
import eu.etaxonomy.cdm.model.description.FeatureTree;
125
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
126
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
127
import eu.etaxonomy.cdm.model.description.State;
128
import eu.etaxonomy.cdm.model.description.WorkingSet;
129
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
130
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
131
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataCellEditor;
132
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataDisplayConverter;
133
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataCellEditor;
134
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataDisplayConverter;
135
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.supplementalInfo.SupplementalInfoDisplayConverter;
136
import eu.etaxonomy.taxeditor.model.DescriptionHelper;
137
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
138
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
139
import eu.etaxonomy.taxeditor.model.ImageResources;
140
import eu.etaxonomy.taxeditor.model.MessagingUtils;
141
import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
142
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
143
import eu.etaxonomy.taxeditor.store.CdmStore;
144
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
145
import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
146

    
147
/**
148
 * @author pplitzner
149
 * @since Nov 26, 2017
150
 *
151
 */
152
public class CharacterMatrix implements IE4SavablePart, IPartContentHasDetails, IConversationEnabled, IDirtyMarkable,
153
ICdmEntitySessionEnabled{
154

    
155
    private static final List<String> WS_PROPERTY_PATH = Arrays.asList(new String[] {
156
            "descriptions", //$NON-NLS-1$
157
            "descriptions.descriptionElements", //$NON-NLS-1$
158
            "descriptions.descriptionElements.inDescription", //$NON-NLS-1$
159
            "descriptions.descriptionElements.inDescription.descriptionElements", //$NON-NLS-1$
160
            "descriptions.descriptionElements.feature", //$NON-NLS-1$
161
    });
162

    
163
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
164

    
165
    private static final int LEADING_COLUMN_COUNT = 4;
166
    private static final String TAXON_COLUMN = "taxon_column";
167
    private static final String COLLECTOR_COLUMN = "collector_column";
168
    private static final String IDENTIFIER_COLUMN = "identifier_column";
169
    private static final String COUNTRY_COLUMN = "country_column";
170

    
171
    private WorkingSet workingSet;
172

    
173
    private ConversationHolder conversation;
174

    
175
    private ICdmEntitySession cdmEntitySession;
176

    
177
    @Inject
178
    private ESelectionService selService;
179

    
180
    @Inject
181
    private MDirtyable dirty;
182

    
183
    @Inject
184
    private MPart thisPart;
185

    
186
    private NatTable natTable;
187

    
188
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
189

    
190
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
191

    
192
    private Properties natTableState;
193

    
194
    private EventList<Object> descriptions;
195

    
196
    private Collection<SpecimenOrObservationBase> specimenCache = null;
197

    
198
    private ListDataProvider<Object> bodyDataProvider;
199

    
200
    private Label wsLabel;
201

    
202
    private Button btnToggleTree;
203

    
204
    private Button btnToggleFlat;
205

    
206
    private Button btnCollapseAll;
207

    
208
    private Button btnExpandAll;
209

    
210
    private ComboViewer comboStates;
211

    
212
    private Button btnManageState;
213

    
214
    private Button btnExcelExport;
215

    
216
    private Composite buttonPanel;
217

    
218
    private Composite parent;
219

    
220
    private List<Feature> features;
221

    
222
    @PostConstruct
223
    public void create(Composite parent) {
224
        if(CdmStore.isActive() && conversation==null){
225
            conversation = CdmStore.createConversation();
226
        }
227
        if(cdmEntitySession == null){
228
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
229
        }
230
        else{
231
            return;
232
        }
233
        this.parent = parent;
234
        parent.setLayout(new GridLayout());
235

    
236
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
237
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
238
        toolbarComposite.setLayout(new GridLayout(8, false));
239
        natTable = new NatTable(parent, false);
240

    
241
        wsLabel = new Label(toolbarComposite, SWT.NONE);
242

    
243
        btnToggleTree = new Button(toolbarComposite, SWT.PUSH);
244
        btnToggleFlat = new Button(toolbarComposite, SWT.PUSH);
245
        btnCollapseAll = new Button(toolbarComposite, SWT.PUSH);
246
        btnExpandAll = new Button(toolbarComposite, SWT.PUSH);
247
        comboStates = new ComboViewer(toolbarComposite, SWT.DROP_DOWN);
248
        btnManageState = new Button(toolbarComposite, SWT.PUSH);
249
        btnExcelExport = new Button(toolbarComposite, SWT.PUSH);
250

    
251
        /**
252
         * Toogle tree button
253
         */
254
        btnToggleTree.setImage(ImageResources.getImage(ImageResources.HIERARCHICAL));
255
        btnToggleTree.setToolTipText("Show taxon hierarchy");
256
        btnToggleTree.setSelection(true);
257
        btnToggleTree.setEnabled(false);
258
        btnToggleTree.addSelectionListener(new SelectionAdapter() {
259
            @Override
260
            public void widgetSelected(SelectionEvent e) {
261
                toggleTreeFlat(true);
262
            }
263
        });
264

    
265
        /**
266
         * Toogle flat button
267
         */
268
        btnToggleFlat.setImage(ImageResources.getImage(ImageResources.FLAT));
269
        btnToggleFlat.setToolTipText("Show flat list");
270
        btnToggleFlat.addSelectionListener(new SelectionAdapter() {
271
            @Override
272
            public void widgetSelected(SelectionEvent e) {
273
                toggleTreeFlat(false);
274
            }
275
        });
276

    
277
        /**
278
         *
279
         * Collapse button
280
         */
281
        btnCollapseAll.setImage(ImageResources.getImage(ImageResources.COLLAPSE_ALL));
282
        btnCollapseAll.setToolTipText("Collapse all");
283
        btnCollapseAll.addSelectionListener(new SelectionAdapter() {
284
            @Override
285
            public void widgetSelected(SelectionEvent e) {
286
                natTable.doCommand(new TreeCollapseAllCommand());
287
            }
288
        });
289

    
290
        /**
291
         * Expand button
292
         */
293
        btnExpandAll.setImage(ImageResources.getImage(ImageResources.EXPAND_ALL));
294
        btnExpandAll.setToolTipText("Expand all");
295
        btnExpandAll.addSelectionListener(new SelectionAdapter() {
296
            @Override
297
            public void widgetSelected(SelectionEvent e) {
298
                natTable.doCommand(new TreeExpandAllCommand());
299
            }
300
        });
301

    
302
        /**
303
         * Table state persistence
304
         */
305
        natTableState = new Properties();
306
        //load persisted state
307
        File statePropertiesFile = getStatePropertiesFile();
308
        FileInputStream inputStream;
309
        try {
310
            inputStream = new FileInputStream(statePropertiesFile);
311
            natTableState.load(inputStream);
312
        } catch (IOException e) {
313
            MessagingUtils.info("No initial state properties file found for character matrix");
314
        }
315

    
316
        DisplayPersistenceDialogCommandHandler handler =
317
                new DisplayPersistenceDialogCommandHandler(natTableState, natTable);
318
        natTable.registerCommandHandler(handler);
319
        // create a combobox for showing the available view states
320
        Collection<String> availableStates = PersistenceHelper.getAvailableStates(natTableState);
321
        comboStates.setLabelProvider(new LabelProvider(){
322
            @Override
323
            public String getText(Object element) {
324
                if(element instanceof String && ((String) element).isEmpty()){
325
                    return "-default-";
326
                }
327
                return super.getText(element);
328
            }
329
        });
330
        comboStates.setContentProvider(new ArrayContentProvider());
331
        comboStates.addSelectionChangedListener(e->
332
        {
333
            int index = comboStates.getCombo().getSelectionIndex();
334
            if (index >= 0) {
335
                String selected = comboStates.getCombo().getItem(index);
336
                // load the state
337
                natTable.loadState(selected, natTableState);
338
                natTableState.setProperty(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY, selected);
339
            }
340
        });
341
        comboStates.setInput(availableStates);
342
        if(comboStates.getCombo().getItemCount()>0){
343
            comboStates.getCombo().select(0);
344
        }
345

    
346
        // add listener to update the combo on view state management changes
347
        handler.addStateChangeListener(new IStateChangedListener() {
348
            @Override
349
            public void handleStateChange(StateChangeEvent event) {
350
                comboStates.setInput(PersistenceHelper.getAvailableStates(natTableState));
351
                selectStateItem(comboStates, event.getViewConfigName());
352
            }
353
        });
354

    
355
        // add button to show dialog
356
        btnManageState.setImage(ImageResources.getImage(ImageResources.SETTINGS));
357
        btnManageState.setToolTipText("View configuration");
358
        btnManageState.addSelectionListener(new SelectionAdapter() {
359
            @Override
360
            public void widgetSelected(SelectionEvent e) {
361
                natTable.doCommand(new DisplayPersistenceDialogCommand(natTable));
362
                selectStateItem(comboStates, natTableState.get(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY).toString());
363
            }
364
        });
365

    
366
        /**
367
         * excel export
368
         */
369
        btnExcelExport.setToolTipText("Export to Excel");
370
        btnExcelExport.setImage(ImageResources.getImage(ImageResources.EXPORT));
371
        btnExcelExport.addSelectionListener(new SelectionAdapter() {
372
            @Override
373
            public void widgetSelected(SelectionEvent e) {
374
                natTable.doCommand(
375
                        new ExportCommand(
376
                                natTable.getConfigRegistry(),
377
                                natTable.getShell()));
378
            }
379
        });
380

    
381
        buttonPanel = new Composite(parent, SWT.NONE);
382

    
383
        buttonPanel.setLayout(new RowLayout());
384
        GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonPanel);
385

    
386
        /**
387
         * Add description button
388
         */
389
        Button btnAddDescription = new Button(buttonPanel, SWT.PUSH);
390
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON));
391
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
392
            @Override
393
            public void widgetSelected(SelectionEvent e) {
394
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(natTable.getShell(), CharacterMatrix.this);
395
                if(dialog.open()==Window.OK){
396
                    Collection<SpecimenOrObservationBase> specimens = dialog.getSpecimen();
397
                    boolean hasAdded = false;
398
                    for (SpecimenOrObservationBase specimen : specimens) {
399
                        SpecimenDescription description = getDescriptionForWorkingSet(specimen);
400
                        if(!workingSet.getDescriptions().contains(description)){
401
                            CharacterMatrix.this.descriptions.add(new RowWrapper(description));
402
                            workingSet.addDescription(description);
403
                            hasAdded = true;
404
                        }
405
                    }
406
                    if(hasAdded){
407
                        setDirty();
408
                    }
409
                }
410
            }
411
        });
412
    }
413

    
414
    private void toggleTreeFlat(boolean isTree) {
415
        init(workingSet.getUuid(), isTree);
416
        btnToggleFlat.setEnabled(isTree);
417
        btnToggleTree.setEnabled(!isTree);
418
        btnCollapseAll.setEnabled(isTree);
419
        btnExpandAll.setEnabled(isTree);
420
        natTable.doCommand(new StructuralRefreshCommand());
421
        natTable.doCommand(new VisualRefreshCommand());
422
        parent.layout();
423

    
424
    }
425

    
426
    public void init(UUID workingSetUuid, boolean treeView) {
427
        if(workingSet==null){
428
            this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
429
            if(workingSet.getDescriptiveSystem()==null){
430
                MessagingUtils.informationDialog("Editor could not be opened", "The working set has no feature tree selected.");
431
                return;
432
            }
433
            thisPart.setLabel(workingSet.getLabel());
434

    
435
            //get features/columns stored in working set
436
            FeatureTree tree = workingSet.getDescriptiveSystem();
437
            features = new ArrayList<>(tree.getDistinctFeatures());
438
            Collections.sort(features);
439

    
440
            descriptions = GlazedLists.eventList(getDescriptions(workingSet));
441
        }
442
        // use the SortedList constructor with 'null' for the Comparator
443
        // because the Comparator will be set by configuration
444
        SortedList<Object> sortedList = new SortedList<>(descriptions, new MatrixRowComparator());
445
        // wrap the SortedList with the TreeList
446
        TreeList<Object> treeList = new TreeList(sortedList, new DescriptionTreeFormat(workingSet.getMaxRank()), TreeList.NODES_START_EXPANDED);
447
        /**
448
         * data provider
449
         */
450
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
451
        bodyDataProvider = treeView?new ListDataProvider<>(treeList, columnPropertyAccessor):new ListDataProvider<>(sortedList, columnPropertyAccessor);
452

    
453
        ConfigRegistry configRegistry = new ConfigRegistry();
454

    
455

    
456
        /**
457
         * BODY layer
458
         *
459
         *
460

    
461
        CompositeLayer
462
         - (top) SummaryRowLayer
463
         - (bottom) ViewportLayer
464

    
465
             ^
466
        ViewportLayer
467

    
468
             ^
469
        TreeLayer (default visible)
470

    
471
             ^
472
        SelectionLayer
473

    
474
             ^
475
        RowHideShowLayer
476

    
477
             ^
478
        ColumnHideShowLayer
479

    
480
             ^
481
        ColumnReorderLayer
482

    
483
             ^
484
        RowReorderLayer
485

    
486
             ^
487
        DataLayer
488

    
489
         *
490

    
491
         */
492
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
493

    
494
        //register labels for columns
495
        ColumnOverrideLabelAccumulator bodyColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
496
        bodyDataLayer.setConfigLabelAccumulator(bodyColumnLabelAccumulator);
497
        propertyToLabelMap.put(TAXON_COLUMN, "Taxon");
498
        bodyColumnLabelAccumulator.registerColumnOverrides(0, TAXON_COLUMN);
499
        propertyToLabelMap.put(COLLECTOR_COLUMN, "Collector + No");
500
        bodyColumnLabelAccumulator.registerColumnOverrides(1, COLLECTOR_COLUMN);
501
        propertyToLabelMap.put(IDENTIFIER_COLUMN, "Identifier");
502
        bodyColumnLabelAccumulator.registerColumnOverrides(2, IDENTIFIER_COLUMN);
503
        propertyToLabelMap.put(COUNTRY_COLUMN, "Country");
504
        bodyColumnLabelAccumulator.registerColumnOverrides(3, COUNTRY_COLUMN);
505
        for(int i=0;i<features.size();i++){
506
            Feature feature = features.get(i);
507
            initLabels(bodyColumnLabelAccumulator, i, feature);
508
        }
509

    
510
        // layer for event handling of GlazedLists and PropertyChanges
511
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList);
512
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
513
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
514

    
515
        RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
516
        ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
517
        ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
518
        RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
519
        SelectionLayer selectionLayer = new SelectionLayer(rowHideShowLayer);
520
        TreeLayer treeLayer = new TreeLayer(selectionLayer, treeRowModel);
521
        ViewportLayer viewportLayer = treeView?new ViewportLayer(treeLayer):new ViewportLayer(selectionLayer);
522

    
523
        // create a standalone FixedSummaryRowLayer
524
        // since the summary row should be fixed at the top of the body
525
        // region the horizontal dependency of the FixedSummaryRowLayer
526
        // is the ViewportLayer
527
        FixedSummaryRowLayer summaryRowLayer =
528
                new FixedSummaryRowLayer(bodyDataLayer, viewportLayer, configRegistry, false);
529
        //register labels with summary prefix for summary layer
530
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
531
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
532
        for(int i=0;i<features.size();i++){
533
            Feature feature = features.get(i);
534
            summaryColumnLabelAccumulator.registerColumnOverrides(
535
                    i+LEADING_COLUMN_COUNT,
536
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
537
        }
538
        // because the horizontal dependency is the ViewportLayer
539
        // we need to set the composite dependency to false
540
        summaryRowLayer.setHorizontalCompositeDependency(false);
541

    
542
        CompositeLayer composite = new CompositeLayer(1, 2);
543
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
544
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
545

    
546

    
547
        /**
548
         * column header layer
549
         */
550
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
551
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
552
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
553
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
554

    
555
        // add the SortHeaderLayer to the column header layer stack
556
        // as we use GlazedLists, we use the GlazedListsSortModel which
557
        // delegates the sorting to the SortedList
558
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
559
                columnHeaderLayer,
560
                new GlazedListsSortModel<>(
561
                        sortedList,
562
                        columnPropertyAccessor,
563
                        configRegistry,
564
                        columnHeaderDataLayer));
565

    
566

    
567
        /**
568
         * row header layer
569
         */
570
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
571
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
572
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
573
                composite, selectionLayer);
574
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
575

    
576

    
577
        /**
578
         * corner layer
579
         */
580
        ILayer cornerLayer = new CornerLayer(
581
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
582
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
583

    
584

    
585
        /**
586
         * GRID layer (composition of all other layers)
587
         */
588
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
589

    
590
        natTable.setLayer(gridLayer);
591

    
592
        /**
593
         * CONFIGURATION
594
         */
595
        natTable.setConfigRegistry(configRegistry);
596

    
597
        //add default configuration because autoconfigure is set to false in constructor
598
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
599

    
600
        //FIXME: this is for DEBUG ONLY
601
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
602

    
603
        // override the default sort configuration and change the mouse bindings
604
        // to sort on a single click
605
        //currently removed sorting because of using the TreeConfiguration
606
        natTable.addConfiguration(new SingleClickSortConfiguration());
607

    
608
        // add the header menu configuration for adding the column header menu
609
        // with hide/show actions
610
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
611

    
612
            @Override
613
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
614
                return super.createColumnHeaderMenu(natTable)
615
                        .withHideColumnMenuItem()
616
                        .withShowAllColumnsMenuItem();
617
            }
618

    
619
            @Override
620
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
621
                return super.createRowHeaderMenu(natTable)
622
                        .withHideRowMenuItem()
623
                        .withShowAllRowsMenuItem();
624
            }
625

    
626
            @Override
627
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
628
                return super.createCornerMenu(natTable)
629
                        .withShowAllColumnsMenuItem()
630
                        .withShowAllRowsMenuItem();
631
            }
632
        });
633

    
634
        // add custom configuration for data conversion and add column labels to viewport layer
635
        viewportLayer.addConfiguration(new AbstractRegistryConfiguration() {
636
            @Override
637
            public void configureRegistry(IConfigRegistry configRegistry) {
638
                //add display converter for string representation
639
                configRegistry.registerConfigAttribute(
640
                        CellConfigAttributes.DISPLAY_CONVERTER,
641
                        new SupplementalInfoDisplayConverter(),
642
                        DisplayMode.NORMAL,
643
                        TAXON_COLUMN);
644
                configRegistry.registerConfigAttribute(
645
                        CellConfigAttributes.DISPLAY_CONVERTER,
646
                        new SupplementalInfoDisplayConverter(),
647
                        DisplayMode.NORMAL,
648
                        COLLECTOR_COLUMN);
649
                configRegistry.registerConfigAttribute(
650
                        CellConfigAttributes.DISPLAY_CONVERTER,
651
                        new SupplementalInfoDisplayConverter(),
652
                        DisplayMode.NORMAL,
653
                        IDENTIFIER_COLUMN);
654
                configRegistry.registerConfigAttribute(
655
                        CellConfigAttributes.DISPLAY_CONVERTER,
656
                        new SupplementalInfoDisplayConverter(),
657
                        DisplayMode.NORMAL,
658
                        COUNTRY_COLUMN);
659
                features.forEach(feature->registerColumnConfiguration(feature, configRegistry));
660
            }
661

    
662
        });
663

    
664
        //register aggregation configuration for each feature
665
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
666

    
667
        // add the ExportCommandHandler to the ViewportLayer in order to make
668
        // exporting work
669
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
670

    
671
        //propagate single cell selection
672
        natTable.addLayerListener(new ILayerListener() {
673
            @Override
674
            public void handleLayerEvent(ILayerEvent event) {
675
                if(event instanceof CellSelectionEvent){
676
                    CellSelectionEvent cellSelectionEvent = (CellSelectionEvent)event;
677
                    Collection<ILayerCell> selectedCells = cellSelectionEvent.getSelectionLayer().getSelectedCells();
678
                    StructuredSelection selection = new StructuredSelection();
679
                    if(selectedCells.size()==1){
680
                        ILayerCell cell = selectedCells.iterator().next();
681
                        Object dataValue = cell.getDataValue();
682
                        if(dataValue!=null){
683
                            selection = new StructuredSelection(dataValue);
684
                        }
685
                    }
686
                    selService.setSelection(selection);
687
                }
688
            }
689
        });
690

    
691
        natTable.configure();
692

    
693
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
694

    
695
        wsLabel.setText(workingSet.getLabel());
696
        wsLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
697
        wsLabel.getParent().layout();
698

    
699
        parent.layout();
700
    }
701

    
702
    private void selectStateItem(ComboViewer comboStates, String stateName){
703
        String[] items = comboStates.getCombo().getItems();
704
        for(int i=0;i<items.length;i++){
705
            if(items[i].equals(stateName)){
706
                comboStates.getCombo().select(i);
707
                break;
708
            }
709
        }
710
    }
711

    
712
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
713
        Set<Feature> wsFeatures = workingSet.getDescriptiveSystem().getDistinctFeatures();
714
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
715

    
716
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
717
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
718
            //gather specimen description features and check for match with WS features
719
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
720
                Feature feature = specimenDescriptionElement.getFeature();
721
                specimenDescriptionFeatures.add(feature);
722
                if(wsFeatures.contains(feature)){
723
                    matchingDescriptionElements.add(specimenDescriptionElement);
724
                }
725
            }
726
            //if description with the exact same features is found return the description
727
            if(specimenDescriptionFeatures.equals(wsFeatures)){
728
                return specimenDescription;
729
            }
730
        }
731
        //Create new specimen description if no match was found
732
        setDirty();
733
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
734
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+": "+newDesription.generateTitle(), true);
735

    
736
        //check for equals description element (same feature and same values)
737
        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
738
        for(DescriptionElementBase element:matchingDescriptionElements){
739
            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
740
            if(list==null){
741
                list = new ArrayList<>();
742
            }
743
            list.add(element);
744
            featureToElementMap.put(element.getFeature(), list);
745
        }
746
        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
747
        for(Feature feature:featureToElementMap.keySet()){
748
            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
749
            //no duplicate description elements found for this feature
750
            if(elements.size()==1){
751
                descriptionElementsToClone.add(elements.get(0));
752
            }
753
            //duplicates found -> check if all are equal
754
            else{
755
                DescriptionElementBase match = null;
756
                for (DescriptionElementBase descriptionElementBase : elements) {
757
                    if(match==null){
758
                        match = descriptionElementBase;
759
                    }
760
                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
761
                        match = null;
762
                        MessagingUtils.informationDialog("Multiple data found",
763
                                String.format("Multiple description elements with different values "
764
                                        + "found for feature '%s'.\nData will not be copied to new specimen description.", feature.getLabel()));
765
                        break;
766
                    }
767
                }
768
                if(match!=null){
769
                    descriptionElementsToClone.add(match);
770
                }
771
            }
772
        }
773
        //clone matching descriptionElements
774
        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
775
            DescriptionElementBase clone;
776
            try {
777
                clone = descriptionElementBase.clone(newDesription);
778
                clone.getSources().forEach(source -> source.setOriginalNameString(DescriptionHelper.getLabel(descriptionElementBase)));
779
            } catch (CloneNotSupportedException e) {
780
                MessagingUtils.error(CharacterMatrix.class, e);
781
            }
782
        }
783
        return newDesription;
784

    
785
    }
786

    
787
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
788
            int index, Feature feature) {
789

    
790
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
791
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
792

    
793
        String featureLabel = feature.getLabel();
794
        String property = featureLabel;
795
        //show unit for quantitative data
796
        if(feature.isSupportsQuantitativeData()){
797
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
798
            if(recommendedMeasurementUnits.size()!=1){
799
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
800
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
801
                return;
802
            }
803
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
804
            featureLabel += " ["+unit.getLabel()+"]";
805
        }
806
        propertyToLabelMap.put(property, featureLabel);
807
    }
808

    
809
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
810
        //make cell editable
811
        configRegistry.registerConfigAttribute(
812
                EditConfigAttributes.CELL_EDITABLE_RULE,
813
                IEditableRule.ALWAYS_EDITABLE,
814
                DisplayMode.EDIT,
815
                MatrixUtility.getProperty(feature)
816
                );
817
        if(feature.isSupportsQuantitativeData()){
818
            //add display converter for string representation
819
            configRegistry.registerConfigAttribute(
820
                    CellConfigAttributes.DISPLAY_CONVERTER,
821
                    new QuantitativeDataDisplayConverter(),
822
                    DisplayMode.NORMAL,
823
                    MatrixUtility.getProperty(feature));
824
            //register quantitative editor
825
            configRegistry.registerConfigAttribute(
826
                    EditConfigAttributes.CELL_EDITOR,
827
                    new QuantitativeDataCellEditor(feature, this),
828
                    DisplayMode.EDIT,
829
                    MatrixUtility.getProperty(feature));
830
        }
831
        else if(feature.isSupportsCategoricalData()){
832
            //add display converter for string representation
833
            configRegistry.registerConfigAttribute(
834
                    CellConfigAttributes.DISPLAY_CONVERTER,
835
                    new CategoricalDataDisplayConverter(),
836
                    DisplayMode.NORMAL,
837
                    MatrixUtility.getProperty(feature));
838

    
839
            //add combo box cell editor
840
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
841

    
842
                @Override
843
                public List<?> getValues(int columnIndex, int rowIndex) {
844
                    List<State> states = new ArrayList<>();
845
                    Feature feature = indexToFeatureMap.get(columnIndex);
846
                    if(feature.isSupportsCategoricalData()){
847
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
848
                        for (TermVocabulary<State> voc : stateVocs) {
849
                            states.addAll(voc.getTerms());
850
                        }
851
                    }
852
                    return states;
853
                }
854
            }, 5, this, feature);
855
            //register editor
856
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
857
                    comboBoxCellEditor,
858
                    DisplayMode.EDIT,
859
                    MatrixUtility.getProperty(feature));
860

    
861
        }
862

    
863
    }
864

    
865
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
866
        List<RowWrapper> rowWrappers = new ArrayList<>();
867
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
868
        for (DescriptionBase descriptionBase : wsDescriptions) {
869
            if(descriptionBase instanceof SpecimenDescription){
870
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
871
            }
872
        }
873
        return rowWrappers;
874
    }
875

    
876
    public Map<Integer, Feature> getIndexToFeatureMap() {
877
        return indexToFeatureMap;
878
    }
879

    
880
    public LinkedMap<String, String> getPropertyToLabelMap() {
881
        return propertyToLabelMap;
882
    }
883

    
884
    public void setDirty() {
885
        this.dirty.setDirty(true);
886
    }
887

    
888
    public NatTable getNatTable() {
889
        return natTable;
890
    }
891

    
892
    public WorkingSet getWorkingSet() {
893
        return workingSet;
894
    }
895

    
896
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
897
        return specimenCache;
898
    }
899

    
900
    public void setSpecimenCache(Collection<SpecimenOrObservationBase> specimenCache) {
901
        this.specimenCache = specimenCache;
902
    }
903

    
904
    /**
905
     * @return the bodyDataProvider
906
     */
907
    public ListDataProvider<Object> getBodyDataProvider() {
908
        return bodyDataProvider;
909
    }
910

    
911
    @Persist
912
    @Override
913
    public void save(IProgressMonitor monitor) {
914
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
915
        conversation.commit();
916
        dirty.setDirty(false);
917
    }
918

    
919
    @Focus
920
    public void setFocus(){
921
        if(conversation!=null){
922
            conversation.bind();
923
        }
924
        if(cdmEntitySession != null) {
925
            cdmEntitySession.bind();
926
        }
927
    }
928

    
929
    @PreDestroy
930
    public void dispose(){
931
        if (conversation != null) {
932
            conversation.close();
933
            conversation = null;
934
        }
935
        if(cdmEntitySession != null) {
936
            cdmEntitySession.dispose();
937
            cdmEntitySession = null;
938
        }
939
        dirty.setDirty(false);
940
        if(natTableState!=null){
941
            try (FileOutputStream tableStateStream =
942
                    new FileOutputStream(getStatePropertiesFile())) {
943
                natTableState.store(tableStateStream, null);
944
            } catch (IOException ioe) {
945
                ioe.printStackTrace();
946
            }
947
        }
948
    }
949

    
950
    private File getStatePropertiesFile() {
951
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
952
    }
953

    
954
    /**
955
     * {@inheritDoc}
956
     */
957
    @Override
958
    public void update(CdmDataChangeMap arg0) {
959
    }
960

    
961
    /**
962
     * {@inheritDoc}
963
     */
964
    @Override
965
    public ConversationHolder getConversationHolder() {
966
        return conversation;
967
    }
968

    
969
    /**
970
     * {@inheritDoc}
971
     */
972
    @Override
973
    public void changed(Object element) {
974
        setDirty();
975
        natTable.refresh();
976
    }
977

    
978
    /**
979
     * {@inheritDoc}
980
     */
981
    @Override
982
    public void forceDirty() {
983
        setDirty();
984
    }
985

    
986

    
987
    /**
988
     * {@inheritDoc}
989
     */
990
    @Override
991
    public ICdmEntitySession getCdmEntitySession() {
992
        return cdmEntitySession;
993
    }
994

    
995

    
996
    /**
997
     * {@inheritDoc}
998
     */
999
    @Override
1000
    public Collection<WorkingSet> getRootEntities() {
1001
        return Collections.singleton(this.workingSet);
1002
    }
1003

    
1004

    
1005
    /**
1006
     * {@inheritDoc}
1007
     */
1008
    @Override
1009
    public Map<Object, List<String>> getPropertyPathsMap() {
1010
        Map<Object, List<String>> propertyMap = new HashMap<>();
1011
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
1012
        return propertyMap;
1013
    }
1014

    
1015
}
(2-2/11)