Project

General

Profile

Download (40.4 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2017 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.editor.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.DebugMenuConfiguration;
99
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
100
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
101
import org.eclipse.swt.SWT;
102
import org.eclipse.swt.events.SelectionAdapter;
103
import org.eclipse.swt.events.SelectionEvent;
104
import org.eclipse.swt.layout.GridData;
105
import org.eclipse.swt.layout.GridLayout;
106
import org.eclipse.swt.widgets.Button;
107
import org.eclipse.swt.widgets.Composite;
108
import org.eclipse.swt.widgets.Label;
109

    
110
import ca.odell.glazedlists.EventList;
111
import ca.odell.glazedlists.GlazedLists;
112
import ca.odell.glazedlists.SortedList;
113
import ca.odell.glazedlists.TreeList;
114
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
115
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
116
import eu.etaxonomy.cdm.api.service.IWorkingSetService;
117
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
118
import eu.etaxonomy.cdm.model.common.TermVocabulary;
119
import eu.etaxonomy.cdm.model.description.DescriptionBase;
120
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
121
import eu.etaxonomy.cdm.model.description.Feature;
122
import eu.etaxonomy.cdm.model.description.FeatureTree;
123
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
124
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
125
import eu.etaxonomy.cdm.model.description.State;
126
import eu.etaxonomy.cdm.model.description.WorkingSet;
127
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
128
import eu.etaxonomy.cdm.model.taxon.Taxon;
129
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
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 Composite parent;
174

    
175
    private ConversationHolder conversation;
176

    
177
    private ICdmEntitySession cdmEntitySession;
178

    
179
    @Inject
180
    private ESelectionService selService;
181

    
182
    @Inject
183
    private MDirtyable dirty;
184

    
185
    @Inject
186
    private MPart thisPart;
187

    
188
    private NatTable natTable;
189

    
190
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
191

    
192
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
193

    
194
    private Properties natTableState;
195

    
196
    private EventList<Object> descriptions;
197

    
198
    private Collection<SpecimenOrObservationBase> specimenCache = null;
199

    
200
    @PostConstruct
201
    public void create(Composite parent) {
202
        if(CdmStore.isActive() && conversation==null){
203
            conversation = CdmStore.createConversation();
204
        }
205
        if(cdmEntitySession == null){
206
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
207
        }
208
        else{
209
            return;
210
        }
211
        parent.setLayout(new GridLayout());
212
        this.parent = parent;
213
    }
214

    
215

    
216
    public void init(UUID workingSetUuid) {
217
        this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
218
        thisPart.setLabel(workingSet.getLabel());
219

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

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

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

    
236
        ConfigRegistry configRegistry = new ConfigRegistry();
237

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

    
244
        /**
245
         * BODY layer
246
         *
247
         *
248

    
249
        CompositeLayer
250
         - (top) SummaryRowLayer
251
         - (bottom) ViewportLayer
252

    
253
             ^
254
        ViewportLayer
255

    
256
             ^
257
        SelectionLayer
258

    
259
             ^
260
        RowHideShowLayer
261

    
262
             ^
263
        ColumnHideShowLayer
264

    
265
             ^
266
        ColumnReorderLayer
267

    
268
             ^
269
        RowReorderLayer
270

    
271
             ^
272
        DataLayer
273

    
274
         *
275

    
276
         */
277
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
278

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

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

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

    
308

    
309

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

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

    
333

    
334

    
335

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

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

    
355

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

    
365

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

    
373

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

    
379

    
380

    
381
        natTable = new NatTable(parent, gridLayer, false);
382

    
383

    
384
        /**
385
         * CONFIGURATION
386
         */
387
        natTable.setConfigRegistry(configRegistry);
388

    
389

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

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

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

    
400

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

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

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

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

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

    
455
        });
456

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

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

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

    
484
        natTable.configure();
485

    
486
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
487

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

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

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

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

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

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

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

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

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

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

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

    
688
    }
689

    
690
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
691
            int index, Feature feature) {
692

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

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

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

    
742
            //add combo box cell editor
743
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
744

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

    
764
        }
765

    
766
    }
767

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

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

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

    
787
    public void setDirty() {
788
        this.dirty.setDirty(true);
789
    }
790

    
791
    public NatTable getNatTable() {
792
        return natTable;
793
    }
794

    
795
    public WorkingSet getWorkingSet() {
796
        return workingSet;
797
    }
798

    
799
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
800
        return specimenCache;
801
    }
802

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

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

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

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

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

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

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

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

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

    
882

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

    
891

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

    
900

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

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

    
917
        private Map parentMapping = new HashMap<>();
918

    
919
        /**
920
         * Populate path with a list describing the path from a root node to
921
         * this element. Upon returning, the list must have size >= 1, where the
922
         * provided element identical to the list's last element. This
923
         * implementation will use the first object found for a last name as
924
         * root node by storing it within a map. If there is already an object
925
         * stored for the lastname of the given element, it will be used as root
926
         * for the path.
927
         */
928
        @Override
929
        public void getPath(List path, RowWrapper element) {
930
            //TODO: check for multiple taxon nodes in multiple classifications
931
            Taxon taxon = (Taxon) element.getAssociatedTaxa().iterator().next();
932
            Set<TaxonNode> taxonNodes = taxon.getTaxonNodes();
933
            if(taxonNodes!=null){
934
                TaxonNode node = taxonNodes.iterator().next();
935
                TaxonNode parent = HibernateProxyHelper.deproxy(node.getParent(), TaxonNode.class);
936
                while(parent!=null){
937
                    path.add(parent);
938
                    parent = HibernateProxyHelper.deproxy(parent.getParent(), TaxonNode.class);
939
                }
940
            }
941
            path.add(element);
942
        }
943

    
944
        /**
945
         * Simply always return true.
946
         *
947
         * @return true if this element can have child elements, or
948
         *         false if it is always a leaf node.
949
         */
950
        @Override
951
        public boolean allowsChildren(RowWrapper element) {
952
            return true;
953
        }
954

    
955
        /**
956
         * Returns the comparator used to order path elements of the specified
957
         * depth. If enforcing order at this level is not intended, this method
958
         * should return null. We do a simple sorting of the last
959
         * names of the persons to show so the tree nodes are sorted in
960
         * alphabetical order.
961
         */
962
        @Override
963
        public Comparator<RowWrapper> getComparator(int depth) {
964
            return new Comparator<RowWrapper>() {
965

    
966
                @Override
967
                public int compare(RowWrapper o1, RowWrapper o2) {
968
                    return o1.getSpecimenDescription().getId()-(o2.getSpecimenDescription().getId());
969
                }
970

    
971
            };
972
        }
973
    }
974

    
975

    
976
}
(2-2/9)