Project

General

Profile

Download (42.1 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2017 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.editor.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.Comparator;
20
import java.util.HashMap;
21
import java.util.HashSet;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Properties;
25
import java.util.Set;
26
import java.util.UUID;
27

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

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

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

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

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

    
161
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
162

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

    
169
    private WorkingSet workingSet;
170

    
171
    private Composite parent;
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
    @PostConstruct
199
    public void create(Composite parent) {
200
        if(CdmStore.isActive() && conversation==null){
201
            conversation = CdmStore.createConversation();
202
        }
203
        if(cdmEntitySession == null){
204
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
205
        }
206
        else{
207
            return;
208
        }
209
        parent.setLayout(new GridLayout());
210
        this.parent = parent;
211
    }
212

    
213

    
214
    public void init(UUID workingSetUuid) {
215
        this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
216
        if(workingSet.getDescriptiveSystem()==null){
217
            MessagingUtils.informationDialog("Editor could not be opened", "The working set has no feature tree selected.");
218
            return;
219
        }
220
        thisPart.setLabel(workingSet.getLabel());
221

    
222
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
223
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
224
        toolbarComposite.setLayout(new GridLayout(4, false));
225

    
226
        //get features/columns stored in working set
227
        FeatureTree tree = workingSet.getDescriptiveSystem();
228
        List<Feature> features = new ArrayList<>(tree.getDistinctFeatures());
229
        Collections.sort(features);
230

    
231
        descriptions = GlazedLists.eventList(getDescriptions(workingSet));
232
        // use the SortedList constructor with 'null' for the Comparator
233
        // because the Comparator will be set by configuration
234
        SortedList<Object> sortedList = new SortedList<>(descriptions, null);
235
        // wrap the SortedList with the TreeList
236
        TreeList treeList = new TreeList(sortedList, new DescriptionTreeFormat(), TreeList.NODES_START_EXPANDED);
237

    
238
        ConfigRegistry configRegistry = new ConfigRegistry();
239

    
240
        /**
241
         * data provider
242
         */
243
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
244
        IDataProvider bodyDataProvider = new ListDataProvider<Object>(treeList, columnPropertyAccessor);
245

    
246
        /**
247
         * BODY layer
248
         *
249
         *
250

    
251
        CompositeLayer
252
         - (top) SummaryRowLayer
253
         - (bottom) ViewportLayer
254

    
255
             ^
256
        ViewportLayer
257

    
258
             ^
259
        SelectionLayer
260

    
261
             ^
262
        RowHideShowLayer
263

    
264
             ^
265
        ColumnHideShowLayer
266

    
267
             ^
268
        ColumnReorderLayer
269

    
270
             ^
271
        RowReorderLayer
272

    
273
             ^
274
        DataLayer
275

    
276
         *
277

    
278
         */
279
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
280

    
281
        //register labels for columns
282
        ColumnOverrideLabelAccumulator bodyColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
283
        bodyDataLayer.setConfigLabelAccumulator(bodyColumnLabelAccumulator);
284
        propertyToLabelMap.put(TAXON_COLUMN, "Taxon");
285
        bodyColumnLabelAccumulator.registerColumnOverrides(0, TAXON_COLUMN);
286
        propertyToLabelMap.put(COLLECTOR_COLUMN, "Collector + No");
287
        bodyColumnLabelAccumulator.registerColumnOverrides(1, COLLECTOR_COLUMN);
288
        propertyToLabelMap.put(IDENTIFIER_COLUMN, "Identifier");
289
        bodyColumnLabelAccumulator.registerColumnOverrides(2, IDENTIFIER_COLUMN);
290
        propertyToLabelMap.put(COUNTRY_COLUMN, "Country");
291
        bodyColumnLabelAccumulator.registerColumnOverrides(3, COUNTRY_COLUMN);
292
        for(int i=0;i<features.size();i++){
293
            Feature feature = features.get(i);
294
            initLabels(bodyColumnLabelAccumulator, i, feature);
295
        }
296

    
297
        // layer for event handling of GlazedLists and PropertyChanges
298
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList);
299
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
300
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
301

    
302
        RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
303
        ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
304
        ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
305
        RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
306
        SelectionLayer selectionLayer = new SelectionLayer(rowHideShowLayer);
307
        TreeLayer treeLayer = new TreeLayer(selectionLayer, treeRowModel);
308
        ViewportLayer viewportLayer = new ViewportLayer(treeLayer);
309

    
310

    
311

    
312
        // create a standalone FixedSummaryRowLayer
313
        // since the summary row should be fixed at the top of the body
314
        // region the horizontal dependency of the FixedSummaryRowLayer
315
        // is the ViewportLayer
316
        FixedSummaryRowLayer summaryRowLayer =
317
                new FixedSummaryRowLayer(bodyDataLayer, viewportLayer, configRegistry, false);
318
        //regoster labels with summary prefix for summary layer
319
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
320
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
321
        for(int i=0;i<features.size();i++){
322
            Feature feature = features.get(i);
323
            summaryColumnLabelAccumulator.registerColumnOverrides(
324
                    i+LEADING_COLUMN_COUNT,
325
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
326
        }
327
        // because the horizontal dependency is the ViewportLayer
328
        // we need to set the composite dependency to false
329
        summaryRowLayer.setHorizontalCompositeDependency(false);
330

    
331
        CompositeLayer composite = new CompositeLayer(1, 2);
332
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
333
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
334

    
335

    
336

    
337

    
338
        /**
339
         * column header layer
340
         */
341
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
342
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
343
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
344
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
345

    
346
        // add the SortHeaderLayer to the column header layer stack
347
        // as we use GlazedLists, we use the GlazedListsSortModel which
348
        // delegates the sorting to the SortedList
349
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
350
                columnHeaderLayer,
351
                new GlazedListsSortModel<>(
352
                        sortedList,
353
                        columnPropertyAccessor,
354
                        configRegistry,
355
                        columnHeaderDataLayer));
356

    
357

    
358
        /**
359
         * row header layer
360
         */
361
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
362
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
363
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
364
                composite, selectionLayer);
365
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
366

    
367

    
368
        /**
369
         * corner layer
370
         */
371
        ILayer cornerLayer = new CornerLayer(
372
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
373
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
374

    
375

    
376
        /**
377
         * GRID layer (composition of all other layers)
378
         */
379
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
380

    
381

    
382

    
383
        natTable = new NatTable(parent, gridLayer, false);
384

    
385

    
386
        /**
387
         * CONFIGURATION
388
         */
389
        natTable.setConfigRegistry(configRegistry);
390

    
391

    
392
        //add default configuration because autoconfigure is set to false in constructor
393
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
394

    
395
        //FIXME: this is for DEBUG ONLY
396
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
397

    
398
        // override the default sort configuration and change the mouse bindings
399
        // to sort on a single click
400
        natTable.addConfiguration(new SingleClickSortConfiguration());
401

    
402

    
403
        // add the header menu configuration for adding the column header menu
404
        // with hide/show actions
405
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
406

    
407
            @Override
408
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
409
                return super.createColumnHeaderMenu(natTable)
410
                        .withHideColumnMenuItem()
411
                        .withShowAllColumnsMenuItem();
412
            }
413

    
414
            @Override
415
            protected PopupMenuBuilder createRowHeaderMenu(NatTable natTable) {
416
                return super.createRowHeaderMenu(natTable)
417
                        .withHideRowMenuItem()
418
                        .withShowAllRowsMenuItem();
419
            }
420

    
421
            @Override
422
            protected PopupMenuBuilder createCornerMenu(NatTable natTable) {
423
                return super.createCornerMenu(natTable)
424
                        .withShowAllColumnsMenuItem()
425
                        .withShowAllRowsMenuItem();
426
            }
427
        });
428

    
429
        // add custom configuration for data conversion and add column labels to viewport layer
430
        viewportLayer.addConfiguration(new AbstractRegistryConfiguration() {
431
            @Override
432
            public void configureRegistry(IConfigRegistry configRegistry) {
433
                //add display converter for string representation
434
                configRegistry.registerConfigAttribute(
435
                        CellConfigAttributes.DISPLAY_CONVERTER,
436
                        new SupplementalInfoDisplayConverter(),
437
                        DisplayMode.NORMAL,
438
                        TAXON_COLUMN);
439
                configRegistry.registerConfigAttribute(
440
                        CellConfigAttributes.DISPLAY_CONVERTER,
441
                        new SupplementalInfoDisplayConverter(),
442
                        DisplayMode.NORMAL,
443
                        COLLECTOR_COLUMN);
444
                configRegistry.registerConfigAttribute(
445
                        CellConfigAttributes.DISPLAY_CONVERTER,
446
                        new SupplementalInfoDisplayConverter(),
447
                        DisplayMode.NORMAL,
448
                        IDENTIFIER_COLUMN);
449
                configRegistry.registerConfigAttribute(
450
                        CellConfigAttributes.DISPLAY_CONVERTER,
451
                        new SupplementalInfoDisplayConverter(),
452
                        DisplayMode.NORMAL,
453
                        COUNTRY_COLUMN);
454
                features.forEach(feature->registerColumnConfiguration(feature, configRegistry));
455
            }
456

    
457
        });
458

    
459
        //register aggregation configuration for each feature
460
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
461

    
462
        // add the ExportCommandHandler to the ViewportLayer in order to make
463
        // exporting work
464
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
465

    
466
        //propagate single cell selection
467
        natTable.addLayerListener(new ILayerListener() {
468
            @Override
469
            public void handleLayerEvent(ILayerEvent event) {
470
                if(event instanceof CellSelectionEvent){
471
                    CellSelectionEvent cellSelectionEvent = (CellSelectionEvent)event;
472
                    Collection<ILayerCell> selectedCells = cellSelectionEvent.getSelectionLayer().getSelectedCells();
473
                    StructuredSelection selection = new StructuredSelection();
474
                    if(selectedCells.size()==1){
475
                        ILayerCell cell = selectedCells.iterator().next();
476
                        Object dataValue = cell.getDataValue();
477
                        if(dataValue!=null){
478
                            selection = new StructuredSelection(dataValue);
479
                        }
480
                    }
481
                    selService.setSelection(selection);
482
                }
483
            }
484
        });
485

    
486
        natTable.configure();
487

    
488
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
489

    
490
        /**
491
         * Info label
492
         */
493
        Label wsLabel = new Label(toolbarComposite, SWT.NONE);
494
        wsLabel.setText(workingSet.getLabel());
495
        wsLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
496

    
497
        /**
498
         * Table state persistence
499
         */
500
        natTableState = new Properties();
501
        //load persisted state
502
        File statePropertiesFile = getStatePropertiesFile();
503
        FileInputStream inputStream;
504
        try {
505
            inputStream = new FileInputStream(statePropertiesFile);
506
            natTableState.load(inputStream);
507
        } catch (IOException e) {
508
            MessagingUtils.info("No initial state properties file found for character matrix");
509
        }
510

    
511
        DisplayPersistenceDialogCommandHandler handler =
512
                new DisplayPersistenceDialogCommandHandler(natTableState, natTable);
513
        gridLayer.registerCommandHandler(handler);
514
        // create a combobox for showing the available view states
515
        ComboViewer comboStates= new ComboViewer(toolbarComposite, SWT.DROP_DOWN) ;
516
        Collection<String> availableStates = PersistenceHelper.getAvailableStates(natTableState);
517
        comboStates.setLabelProvider(new LabelProvider(){
518
            @Override
519
            public String getText(Object element) {
520
                if(element instanceof String && ((String) element).isEmpty()){
521
                    return "-default-";
522
                }
523
                return super.getText(element);
524
            }
525
        });
526
        comboStates.setContentProvider(new ArrayContentProvider());
527
        comboStates.addSelectionChangedListener(e->
528
        {
529
            int index = comboStates.getCombo().getSelectionIndex();
530
            if (index >= 0) {
531
                String selected = comboStates.getCombo().getItem(index);
532
                // load the state
533
                natTable.loadState(selected, natTableState);
534
                natTableState.setProperty(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY, selected);
535
            }
536
        });
537
        comboStates.setInput(availableStates);
538
        if(comboStates.getCombo().getItemCount()>0){
539
            comboStates.getCombo().select(0);
540
        }
541

    
542
        // add listener to update the combo on view state management changes
543
        handler.addStateChangeListener(new IStateChangedListener() {
544
            @Override
545
            public void handleStateChange(StateChangeEvent event) {
546
                comboStates.setInput(PersistenceHelper.getAvailableStates(natTableState));
547
                selectStateItem(comboStates, event.getViewConfigName());
548
            }
549
        });
550

    
551
        // add button to show dialog
552
        Button btnManageState = new Button(toolbarComposite, SWT.PUSH);
553
        btnManageState.setImage(ImageResources.getImage(ImageResources.SETTINGS));
554
        btnManageState.addSelectionListener(new SelectionAdapter() {
555
            @Override
556
            public void widgetSelected(SelectionEvent e) {
557
                natTable.doCommand(new DisplayPersistenceDialogCommand(natTable));
558
                selectStateItem(comboStates, natTableState.get(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY).toString());
559
            }
560
        });
561

    
562
        /**
563
         * excel export
564
         */
565
        Button btnExcelExport = new Button(toolbarComposite, SWT.PUSH);
566
        btnExcelExport.setToolTipText("Export to Excel");
567
        btnExcelExport.setImage(ImageResources.getImage(ImageResources.EXPORT));
568
        btnExcelExport.addSelectionListener(new SelectionAdapter() {
569
            @Override
570
            public void widgetSelected(SelectionEvent e) {
571
                natTable.doCommand(
572
                        new ExportCommand(
573
                                natTable.getConfigRegistry(),
574
                                natTable.getShell()));
575
            }
576
        });
577

    
578
        /**
579
         * Add description button
580
         */
581
        Button btnAddDescription = new Button(parent, SWT.PUSH);
582
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON));
583
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
584
            @Override
585
            public void widgetSelected(SelectionEvent e) {
586
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(natTable.getShell(), CharacterMatrix.this);
587
                if(dialog.open()==Window.OK){
588
                    Collection<SpecimenOrObservationBase> specimens = dialog.getSpecimen();
589
                    boolean hasAdded = false;
590
                    for (SpecimenOrObservationBase specimen : specimens) {
591
                        SpecimenDescription description = getDescriptionForWorkingSet(specimen);
592
                        if(!workingSet.getDescriptions().contains(description)){
593
                            CharacterMatrix.this.descriptions.add(new RowWrapper(description));
594
                            workingSet.addDescription(description);
595
                            hasAdded = true;
596
                        }
597
                    }
598
                    if(hasAdded){
599
                        setDirty();
600
                    }
601
                }
602
            }
603
        });
604
        parent.layout();
605
    }
606

    
607
    private void selectStateItem(ComboViewer comboStates, String stateName){
608
        String[] items = comboStates.getCombo().getItems();
609
        for(int i=0;i<items.length;i++){
610
            if(items[i].equals(stateName)){
611
                comboStates.getCombo().select(i);
612
                break;
613
            }
614
        }
615
    }
616

    
617
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
618
        Set<Feature> wsFeatures = workingSet.getDescriptiveSystem().getDistinctFeatures();
619
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
620

    
621
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
622
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
623
            //gather specimen description features and check for match with WS features
624
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
625
                Feature feature = specimenDescriptionElement.getFeature();
626
                specimenDescriptionFeatures.add(feature);
627
                if(wsFeatures.contains(feature)){
628
                    matchingDescriptionElements.add(specimenDescriptionElement);
629
                }
630
            }
631
            //if description with the exact same features is found return the description
632
            if(specimenDescriptionFeatures.equals(wsFeatures)){
633
                return specimenDescription;
634
            }
635
        }
636
        //Create new specimen description if no match was found
637
        setDirty();
638
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
639
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+": "+newDesription.generateTitle(), true);
640

    
641
        //check for equals description element (same feature and same values)
642
        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
643
        for(DescriptionElementBase element:matchingDescriptionElements){
644
            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
645
            if(list==null){
646
                list = new ArrayList<>();
647
            }
648
            list.add(element);
649
            featureToElementMap.put(element.getFeature(), list);
650
        }
651
        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
652
        for(Feature feature:featureToElementMap.keySet()){
653
            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
654
            //no duplicate description elements found for this feature
655
            if(elements.size()==1){
656
                descriptionElementsToClone.add(elements.get(0));
657
            }
658
            //duplicates found -> check if all are equal
659
            else{
660
                DescriptionElementBase match = null;
661
                for (DescriptionElementBase descriptionElementBase : elements) {
662
                    if(match==null){
663
                        match = descriptionElementBase;
664
                    }
665
                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
666
                        match = null;
667
                        MessagingUtils.informationDialog("Multiple data found",
668
                                String.format("Multiple description elements with different values "
669
                                        + "found for feature '%s'.\nData will not be copied to new specimen description.", feature.getLabel()));
670
                        break;
671
                    }
672
                }
673
                if(match!=null){
674
                    descriptionElementsToClone.add(match);
675
                }
676
            }
677
        }
678
        //clone matching descriptionElements
679
        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
680
            DescriptionElementBase clone;
681
            try {
682
                clone = descriptionElementBase.clone(newDesription);
683
                clone.getSources().forEach(source -> source.setOriginalNameString(DescriptionHelper.getLabel(descriptionElementBase)));
684
            } catch (CloneNotSupportedException e) {
685
                MessagingUtils.error(CharacterMatrix.class, e);
686
            }
687
        }
688
        return newDesription;
689

    
690
    }
691

    
692
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
693
            int index, Feature feature) {
694

    
695
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
696
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
697

    
698
        String featureLabel = feature.getLabel();
699
        String property = featureLabel;
700
        //show unit for quantitative data
701
        if(feature.isSupportsQuantitativeData()){
702
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
703
            if(recommendedMeasurementUnits.size()!=1){
704
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
705
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
706
                return;
707
            }
708
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
709
            featureLabel += " ["+unit.getLabel()+"]";
710
        }
711
        propertyToLabelMap.put(property, featureLabel);
712
    }
713

    
714
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
715
        //make cell editable
716
        configRegistry.registerConfigAttribute(
717
                EditConfigAttributes.CELL_EDITABLE_RULE,
718
                IEditableRule.ALWAYS_EDITABLE,
719
                DisplayMode.EDIT,
720
                MatrixUtility.getProperty(feature)
721
                );
722
        if(feature.isSupportsQuantitativeData()){
723
            //add display converter for string representation
724
            configRegistry.registerConfigAttribute(
725
                    CellConfigAttributes.DISPLAY_CONVERTER,
726
                    new QuantitativeDataDisplayConverter(),
727
                    DisplayMode.NORMAL,
728
                    MatrixUtility.getProperty(feature));
729
            //register quantitative editor
730
            configRegistry.registerConfigAttribute(
731
                    EditConfigAttributes.CELL_EDITOR,
732
                    new QuantitativeDataCellEditor(feature.getRecommendedStatisticalMeasures(), this),
733
                    DisplayMode.EDIT,
734
                    MatrixUtility.getProperty(feature));
735
        }
736
        else if(feature.isSupportsCategoricalData()){
737
            //add display converter for string representation
738
            configRegistry.registerConfigAttribute(
739
                    CellConfigAttributes.DISPLAY_CONVERTER,
740
                    new CategoricalDataDisplayConverter(),
741
                    DisplayMode.NORMAL,
742
                    MatrixUtility.getProperty(feature));
743

    
744
            //add combo box cell editor
745
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
746

    
747
                @Override
748
                public List<?> getValues(int columnIndex, int rowIndex) {
749
                    List<State> states = new ArrayList<>();
750
                    Feature feature = indexToFeatureMap.get(columnIndex);
751
                    if(feature.isSupportsCategoricalData()){
752
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
753
                        for (TermVocabulary<State> voc : stateVocs) {
754
                            states.addAll(voc.getTerms());
755
                        }
756
                    }
757
                    return states;
758
                }
759
            }, 5, this);
760
            //register editor
761
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
762
                    comboBoxCellEditor,
763
                    DisplayMode.EDIT,
764
                    MatrixUtility.getProperty(feature));
765

    
766
        }
767

    
768
    }
769

    
770
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
771
        List<RowWrapper> rowWrappers = new ArrayList<>();
772
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
773
        for (DescriptionBase descriptionBase : wsDescriptions) {
774
            if(descriptionBase instanceof SpecimenDescription){
775
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
776
            }
777
        }
778
        return rowWrappers;
779
    }
780

    
781
    public Map<Integer, Feature> getIndexToFeatureMap() {
782
        return indexToFeatureMap;
783
    }
784

    
785
    public LinkedMap<String, String> getPropertyToLabelMap() {
786
        return propertyToLabelMap;
787
    }
788

    
789
    public void setDirty() {
790
        this.dirty.setDirty(true);
791
    }
792

    
793
    public NatTable getNatTable() {
794
        return natTable;
795
    }
796

    
797
    public WorkingSet getWorkingSet() {
798
        return workingSet;
799
    }
800

    
801
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
802
        return specimenCache;
803
    }
804

    
805
    public void setSpecimenCache(Collection<SpecimenOrObservationBase> specimenCache) {
806
        this.specimenCache = specimenCache;
807
    }
808

    
809
    @Persist
810
    @Override
811
    public void save(IProgressMonitor monitor) {
812
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
813
        conversation.commit();
814
        dirty.setDirty(false);
815
    }
816

    
817
    @Focus
818
    public void setFocus(){
819
        if(conversation!=null){
820
            conversation.bind();
821
        }
822
        if(cdmEntitySession != null) {
823
            cdmEntitySession.bind();
824
        }
825
    }
826

    
827
    @PreDestroy
828
    public void dispose(){
829
        if (conversation != null) {
830
            conversation.close();
831
            conversation = null;
832
        }
833
        if(cdmEntitySession != null) {
834
            cdmEntitySession.dispose();
835
            cdmEntitySession = null;
836
        }
837
        dirty.setDirty(false);
838
        if(natTableState!=null){
839
            try (FileOutputStream tableStateStream =
840
                    new FileOutputStream(getStatePropertiesFile())) {
841
                natTableState.store(tableStateStream, null);
842
            } catch (IOException ioe) {
843
                ioe.printStackTrace();
844
            }
845
        }
846
    }
847

    
848
    private File getStatePropertiesFile() {
849
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
850
    }
851

    
852
    /**
853
     * {@inheritDoc}
854
     */
855
    @Override
856
    public void update(CdmDataChangeMap arg0) {
857
    }
858

    
859
    /**
860
     * {@inheritDoc}
861
     */
862
    @Override
863
    public ConversationHolder getConversationHolder() {
864
        return conversation;
865
    }
866

    
867
    /**
868
     * {@inheritDoc}
869
     */
870
    @Override
871
    public void changed(Object element) {
872
        setDirty();
873
        natTable.refresh();
874
    }
875

    
876
    /**
877
     * {@inheritDoc}
878
     */
879
    @Override
880
    public void forceDirty() {
881
        setDirty();
882
    }
883

    
884

    
885
    /**
886
     * {@inheritDoc}
887
     */
888
    @Override
889
    public ICdmEntitySession getCdmEntitySession() {
890
        return cdmEntitySession;
891
    }
892

    
893

    
894
    /**
895
     * {@inheritDoc}
896
     */
897
    @Override
898
    public Collection<WorkingSet> getRootEntities() {
899
        return Collections.singleton(this.workingSet);
900
    }
901

    
902

    
903
    /**
904
     * {@inheritDoc}
905
     */
906
    @Override
907
    public Map<Object, List<String>> getPropertyPathsMap() {
908
        Map<Object, List<String>> propertyMap = new HashMap<>();
909
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
910
        return propertyMap;
911
    }
912

    
913
    /*
914
    * Using a String directly as the tree item has the possible disadvantage of
915
    * haven non-unique items in the tree within subtrees.
916
    */
917
    private class DescriptionTreeFormat implements TreeList.Format<Object> {
918

    
919
        private Map parentMapping = new HashMap<>();
920

    
921
        /**
922
         * Populate path with a list describing the path from a root node to
923
         * this element. Upon returning, the list must have size >= 1, where the
924
         * provided element identical to the list's last element. This
925
         * implementation will use the first object found for a last name as
926
         * root node by storing it within a map. If there is already an object
927
         * stored for the lastname of the given element, it will be used as root
928
         * for the path.
929
         */
930
        @Override
931
        public void getPath(List path, Object element) {
932
            if(element instanceof RowWrapper){
933
                //TODO: check for multiple taxon nodes in multiple classifications
934
                Taxon taxon = (Taxon) ((RowWrapper) element).getAssociatedTaxa().iterator().next();
935
                Set<TaxonNode> taxonNodes = taxon.getTaxonNodes();
936
                if(taxonNodes!=null){
937
                    TaxonNode node = taxonNodes.iterator().next();
938
                    addPathRecursive(path, node);
939
//                    Object rowWrapperParentNode = parentMapping.get(node);
940
//                    if(rowWrapperParentNode!=null){
941
//                        path.add(rowWrapperParentNode);
942
//                    }
943
//                    else{
944
//                        TaxonNode parentNode = HibernateProxyHelper.deproxy(node.getParent(), TaxonNode.class);
945
//                        while(parentNode!=null){
946
//                            path.add(parentNode);
947
//                            parentMapping.put(node, parentNode);
948
//                            if(parentNode instanceof TaxonNode){
949
//                                if(parentMapping.get(parentNode)!=null){
950
//                                    path.add(parentMapping).get(parentNode);
951
//                                }
952
//                                else{
953
//                                    parentNode = HibernateProxyHelper.deproxy(parentNode.getParent(), TaxonNode.class);
954
//                                }
955
//                            }
956
//                        }
957
//                    }
958
                }
959
            }
960
            path.add(element);
961
        }
962

    
963
        private void addPathRecursive(List path, TaxonNode node){
964
            if(node.getParent()!=null){
965
                addPathRecursive(path, node.getParent());
966
                path.add(node);
967
            }
968
        }
969

    
970
        /**
971
         * Simply always return true.
972
         *
973
         * @return true if this element can have child elements, or
974
         *         false if it is always a leaf node.
975
         */
976
        @Override
977
        public boolean allowsChildren(Object element) {
978
            return true;
979
        }
980

    
981
        /**
982
         * Returns the comparator used to order path elements of the specified
983
         * depth. If enforcing order at this level is not intended, this method
984
         * should return null. We do a simple sorting of the last
985
         * names of the persons to show so the tree nodes are sorted in
986
         * alphabetical order.
987
         */
988
        @Override
989
        public Comparator<Object> getComparator(int depth) {
990
            return new Comparator<Object>() {
991

    
992
                @Override
993
                public int compare(Object o1, Object o2) {
994
//                    if(o1 instanceof RowWrapper && o2 instanceof RowWrapper){
995
//                        return ((RowWrapper) o1).getSpecimenDescription().getId()-(((RowWrapper) o2).getSpecimenDescription().getId());
996
//                    }
997
//                    else
998
                        if(o1 instanceof TaxonNode && o2 instanceof TaxonNode){
999
                        return ((TaxonNode) o1).getTaxon().getName().getNameCache().compareTo(((TaxonNode) o2).getTaxon().getName().getNameCache());
1000
                    }
1001
                    return 0;
1002
                }
1003

    
1004
            };
1005
        }
1006
    }
1007

    
1008

    
1009
}
(2-2/9)